blob: eca990518959b186fe462708eb52ccb7796c4655 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
211 int dirfd; /* File descriptor for the directory */
212 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000213 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000214 int lastErrno; /* The unix errno from last I/O error */
215 void *lockingContext; /* Locking style specific state */
216 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000217 const char *zPath; /* Name of the file */
218 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000219 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000220#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000221 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000222#endif
drh7ed97b92010-01-20 13:07:21 +0000223#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000224 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000225#endif
226#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000227 int isDelete; /* Delete on close if true */
228 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
drhf0b190d2011-07-26 16:03:07 +0000253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
255#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
drha7e61d82011-03-12 17:02:57 +0000256
257/*
drh198bf392006-01-06 21:52:49 +0000258** Include code that is common to all os_*.c files
259*/
260#include "os_common.h"
261
262/*
drh0ccebe72005-06-07 22:22:50 +0000263** Define various macros that are missing from some systems.
264*/
drhbbd42a62004-05-22 17:41:58 +0000265#ifndef O_LARGEFILE
266# define O_LARGEFILE 0
267#endif
268#ifdef SQLITE_DISABLE_LFS
269# undef O_LARGEFILE
270# define O_LARGEFILE 0
271#endif
272#ifndef O_NOFOLLOW
273# define O_NOFOLLOW 0
274#endif
275#ifndef O_BINARY
276# define O_BINARY 0
277#endif
278
279/*
drh2b4b5962005-06-15 17:47:55 +0000280** The threadid macro resolves to the thread-id or to 0. Used for
281** testing and debugging only.
282*/
drhd677b3d2007-08-20 22:48:41 +0000283#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000284#define threadid pthread_self()
285#else
286#define threadid 0
287#endif
288
drh99ab3b12011-03-02 15:09:07 +0000289/*
drh9a3baf12011-04-25 18:01:27 +0000290** Different Unix systems declare open() in different ways. Same use
291** open(const char*,int,mode_t). Others use open(const char*,int,...).
292** The difference is important when using a pointer to the function.
293**
294** The safest way to deal with the problem is to always use this wrapper
295** which always has the same well-defined interface.
296*/
297static int posixOpen(const char *zFile, int flags, int mode){
298 return open(zFile, flags, mode);
299}
300
301/*
drh99ab3b12011-03-02 15:09:07 +0000302** Many system calls are accessed through pointer-to-functions so that
303** they may be overridden at runtime to facilitate fault injection during
304** testing and sandboxing. The following array holds the names and pointers
305** to all overrideable system calls.
306*/
307static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000308 const char *zName; /* Name of the sytem call */
309 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
310 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000311} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000312 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
313#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000314
drh58ad5802011-03-23 22:02:23 +0000315 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000316#define osClose ((int(*)(int))aSyscall[1].pCurrent)
317
drh58ad5802011-03-23 22:02:23 +0000318 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000319#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
320
drh58ad5802011-03-23 22:02:23 +0000321 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000322#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
323
drh58ad5802011-03-23 22:02:23 +0000324 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
326
327/*
328** The DJGPP compiler environment looks mostly like Unix, but it
329** lacks the fcntl() system call. So redefine fcntl() to be something
330** that always succeeds. This means that locking does not occur under
331** DJGPP. But it is DOS - what did you expect?
332*/
333#ifdef __DJGPP__
334 { "fstat", 0, 0 },
335#define osFstat(a,b,c) 0
336#else
drh58ad5802011-03-23 22:02:23 +0000337 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000338#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
339#endif
340
drh58ad5802011-03-23 22:02:23 +0000341 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000342#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
343
drh58ad5802011-03-23 22:02:23 +0000344 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000346
drh58ad5802011-03-23 22:02:23 +0000347 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000348#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
349
drhd4a80312011-04-15 14:33:20 +0000350#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000351 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000352#else
drh58ad5802011-03-23 22:02:23 +0000353 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000354#endif
355#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
356
357#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000358 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000359#else
drh58ad5802011-03-23 22:02:23 +0000360 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000361#endif
362#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000365#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
366
drhd4a80312011-04-15 14:33:20 +0000367#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000368 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000369#else
drh58ad5802011-03-23 22:02:23 +0000370 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000371#endif
372#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
373 aSyscall[12].pCurrent)
374
375#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000376 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000377#else
drh58ad5802011-03-23 22:02:23 +0000378 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000379#endif
380#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
381 aSyscall[13].pCurrent)
382
drha6c47492011-04-11 18:35:09 +0000383#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000384 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000385#else
386 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000387#endif
drh2aa5a002011-04-13 13:42:25 +0000388#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000389
390#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000391 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000392#else
drh58ad5802011-03-23 22:02:23 +0000393 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000394#endif
dan0fd7d862011-03-29 10:04:23 +0000395#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000396
drh036ac7f2011-08-08 23:18:05 +0000397 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
398#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
399
drhe562be52011-03-02 18:01:10 +0000400}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000401
402/*
403** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000404** "unix" VFSes. Return SQLITE_OK opon successfully updating the
405** system call pointer, or SQLITE_NOTFOUND if there is no configurable
406** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000407*/
408static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000409 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
410 const char *zName, /* Name of system call to override */
411 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000412){
drh58ad5802011-03-23 22:02:23 +0000413 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000414 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000415
416 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000417 if( zName==0 ){
418 /* If no zName is given, restore all system calls to their default
419 ** settings and return NULL
420 */
dan51438a72011-04-02 17:00:47 +0000421 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000422 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
423 if( aSyscall[i].pDefault ){
424 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000425 }
426 }
427 }else{
428 /* If zName is specified, operate on only the one system call
429 ** specified.
430 */
431 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
432 if( strcmp(zName, aSyscall[i].zName)==0 ){
433 if( aSyscall[i].pDefault==0 ){
434 aSyscall[i].pDefault = aSyscall[i].pCurrent;
435 }
drh1df30962011-03-02 19:06:42 +0000436 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000437 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
438 aSyscall[i].pCurrent = pNewFunc;
439 break;
440 }
441 }
442 }
443 return rc;
444}
445
drh1df30962011-03-02 19:06:42 +0000446/*
447** Return the value of a system call. Return NULL if zName is not a
448** recognized system call name. NULL is also returned if the system call
449** is currently undefined.
450*/
drh58ad5802011-03-23 22:02:23 +0000451static sqlite3_syscall_ptr unixGetSystemCall(
452 sqlite3_vfs *pNotUsed,
453 const char *zName
454){
455 unsigned int i;
456
457 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000458 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
459 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
460 }
461 return 0;
462}
463
464/*
465** Return the name of the first system call after zName. If zName==NULL
466** then return the name of the first system call. Return NULL if zName
467** is the last system call or if zName is not the name of a valid
468** system call.
469*/
470static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000471 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000472
473 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000474 if( zName ){
475 for(i=0; i<ArraySize(aSyscall)-1; i++){
476 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000477 }
478 }
dan0fd7d862011-03-29 10:04:23 +0000479 for(i++; i<ArraySize(aSyscall); i++){
480 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000481 }
482 return 0;
483}
484
drhad4f1e52011-03-04 15:43:57 +0000485/*
486** Retry open() calls that fail due to EINTR
487*/
488static int robust_open(const char *z, int f, int m){
489 int rc;
490 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
491 return rc;
492}
danielk197713adf8a2004-06-03 16:08:41 +0000493
drh107886a2008-11-21 22:21:50 +0000494/*
dan9359c7b2009-08-21 08:29:10 +0000495** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000496** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000497** vxworksFileId objects used by this file, all of which may be
498** shared by multiple threads.
499**
500** Function unixMutexHeld() is used to assert() that the global mutex
501** is held when required. This function is only used as part of assert()
502** statements. e.g.
503**
504** unixEnterMutex()
505** assert( unixMutexHeld() );
506** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000507*/
508static void unixEnterMutex(void){
509 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
510}
511static void unixLeaveMutex(void){
512 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
513}
dan9359c7b2009-08-21 08:29:10 +0000514#ifdef SQLITE_DEBUG
515static int unixMutexHeld(void) {
516 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
517}
518#endif
drh107886a2008-11-21 22:21:50 +0000519
drh734c9862008-11-28 15:37:20 +0000520
521#ifdef SQLITE_DEBUG
522/*
523** Helper function for printing out trace information from debugging
524** binaries. This returns the string represetation of the supplied
525** integer lock-type.
526*/
drh308c2a52010-05-14 11:30:18 +0000527static const char *azFileLock(int eFileLock){
528 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000529 case NO_LOCK: return "NONE";
530 case SHARED_LOCK: return "SHARED";
531 case RESERVED_LOCK: return "RESERVED";
532 case PENDING_LOCK: return "PENDING";
533 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000534 }
535 return "ERROR";
536}
537#endif
538
539#ifdef SQLITE_LOCK_TRACE
540/*
541** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000542**
drh734c9862008-11-28 15:37:20 +0000543** This routine is used for troubleshooting locks on multithreaded
544** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
545** command-line option on the compiler. This code is normally
546** turned off.
547*/
548static int lockTrace(int fd, int op, struct flock *p){
549 char *zOpName, *zType;
550 int s;
551 int savedErrno;
552 if( op==F_GETLK ){
553 zOpName = "GETLK";
554 }else if( op==F_SETLK ){
555 zOpName = "SETLK";
556 }else{
drh99ab3b12011-03-02 15:09:07 +0000557 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000558 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
559 return s;
560 }
561 if( p->l_type==F_RDLCK ){
562 zType = "RDLCK";
563 }else if( p->l_type==F_WRLCK ){
564 zType = "WRLCK";
565 }else if( p->l_type==F_UNLCK ){
566 zType = "UNLCK";
567 }else{
568 assert( 0 );
569 }
570 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000571 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000572 savedErrno = errno;
573 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
574 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
575 (int)p->l_pid, s);
576 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
577 struct flock l2;
578 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000579 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000580 if( l2.l_type==F_RDLCK ){
581 zType = "RDLCK";
582 }else if( l2.l_type==F_WRLCK ){
583 zType = "WRLCK";
584 }else if( l2.l_type==F_UNLCK ){
585 zType = "UNLCK";
586 }else{
587 assert( 0 );
588 }
589 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
590 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
591 }
592 errno = savedErrno;
593 return s;
594}
drh99ab3b12011-03-02 15:09:07 +0000595#undef osFcntl
596#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000597#endif /* SQLITE_LOCK_TRACE */
598
drhff812312011-02-23 13:33:46 +0000599/*
600** Retry ftruncate() calls that fail due to EINTR
601*/
drhff812312011-02-23 13:33:46 +0000602static int robust_ftruncate(int h, sqlite3_int64 sz){
603 int rc;
drh99ab3b12011-03-02 15:09:07 +0000604 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000605 return rc;
606}
drh734c9862008-11-28 15:37:20 +0000607
608/*
609** This routine translates a standard POSIX errno code into something
610** useful to the clients of the sqlite3 functions. Specifically, it is
611** intended to translate a variety of "try again" errors into SQLITE_BUSY
612** and a variety of "please close the file descriptor NOW" errors into
613** SQLITE_IOERR
614**
615** Errors during initialization of locks, or file system support for locks,
616** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
617*/
618static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
619 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000620#if 0
621 /* At one point this code was not commented out. In theory, this branch
622 ** should never be hit, as this function should only be called after
623 ** a locking-related function (i.e. fcntl()) has returned non-zero with
624 ** the value of errno as the first argument. Since a system call has failed,
625 ** errno should be non-zero.
626 **
627 ** Despite this, if errno really is zero, we still don't want to return
628 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
629 ** propagated back to the caller. Commenting this branch out means errno==0
630 ** will be handled by the "default:" case below.
631 */
drh734c9862008-11-28 15:37:20 +0000632 case 0:
633 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000634#endif
635
drh734c9862008-11-28 15:37:20 +0000636 case EAGAIN:
637 case ETIMEDOUT:
638 case EBUSY:
639 case EINTR:
640 case ENOLCK:
641 /* random NFS retry error, unless during file system support
642 * introspection, in which it actually means what it says */
643 return SQLITE_BUSY;
644
645 case EACCES:
646 /* EACCES is like EAGAIN during locking operations, but not any other time*/
647 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
648 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
649 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
650 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
651 return SQLITE_BUSY;
652 }
653 /* else fall through */
654 case EPERM:
655 return SQLITE_PERM;
656
danea83bc62011-04-01 11:56:32 +0000657 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
658 ** this module never makes such a call. And the code in SQLite itself
659 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
660 ** this case is also commented out. If the system does set errno to EDEADLK,
661 ** the default SQLITE_IOERR_XXX code will be returned. */
662#if 0
drh734c9862008-11-28 15:37:20 +0000663 case EDEADLK:
664 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000665#endif
drh734c9862008-11-28 15:37:20 +0000666
667#if EOPNOTSUPP!=ENOTSUP
668 case EOPNOTSUPP:
669 /* something went terribly awry, unless during file system support
670 * introspection, in which it actually means what it says */
671#endif
672#ifdef ENOTSUP
673 case ENOTSUP:
674 /* invalid fd, unless during file system support introspection, in which
675 * it actually means what it says */
676#endif
677 case EIO:
678 case EBADF:
679 case EINVAL:
680 case ENOTCONN:
681 case ENODEV:
682 case ENXIO:
683 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000684#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000685 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000686#endif
drh734c9862008-11-28 15:37:20 +0000687 case ENOSYS:
688 /* these should force the client to close the file and reconnect */
689
690 default:
691 return sqliteIOErr;
692 }
693}
694
695
696
697/******************************************************************************
698****************** Begin Unique File ID Utility Used By VxWorks ***************
699**
700** On most versions of unix, we can get a unique ID for a file by concatenating
701** the device number and the inode number. But this does not work on VxWorks.
702** On VxWorks, a unique file id must be based on the canonical filename.
703**
704** A pointer to an instance of the following structure can be used as a
705** unique file ID in VxWorks. Each instance of this structure contains
706** a copy of the canonical filename. There is also a reference count.
707** The structure is reclaimed when the number of pointers to it drops to
708** zero.
709**
710** There are never very many files open at one time and lookups are not
711** a performance-critical path, so it is sufficient to put these
712** structures on a linked list.
713*/
714struct vxworksFileId {
715 struct vxworksFileId *pNext; /* Next in a list of them all */
716 int nRef; /* Number of references to this one */
717 int nName; /* Length of the zCanonicalName[] string */
718 char *zCanonicalName; /* Canonical filename */
719};
720
721#if OS_VXWORKS
722/*
drh9b35ea62008-11-29 02:20:26 +0000723** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000724** variable:
725*/
726static struct vxworksFileId *vxworksFileList = 0;
727
728/*
729** Simplify a filename into its canonical form
730** by making the following changes:
731**
732** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000733** * convert /./ into just /
734** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000735**
736** Changes are made in-place. Return the new name length.
737**
738** The original filename is in z[0..n-1]. Return the number of
739** characters in the simplified name.
740*/
741static int vxworksSimplifyName(char *z, int n){
742 int i, j;
743 while( n>1 && z[n-1]=='/' ){ n--; }
744 for(i=j=0; i<n; i++){
745 if( z[i]=='/' ){
746 if( z[i+1]=='/' ) continue;
747 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
748 i += 1;
749 continue;
750 }
751 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
752 while( j>0 && z[j-1]!='/' ){ j--; }
753 if( j>0 ){ j--; }
754 i += 2;
755 continue;
756 }
757 }
758 z[j++] = z[i];
759 }
760 z[j] = 0;
761 return j;
762}
763
764/*
765** Find a unique file ID for the given absolute pathname. Return
766** a pointer to the vxworksFileId object. This pointer is the unique
767** file ID.
768**
769** The nRef field of the vxworksFileId object is incremented before
770** the object is returned. A new vxworksFileId object is created
771** and added to the global list if necessary.
772**
773** If a memory allocation error occurs, return NULL.
774*/
775static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
776 struct vxworksFileId *pNew; /* search key and new file ID */
777 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
778 int n; /* Length of zAbsoluteName string */
779
780 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000781 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000782 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
783 if( pNew==0 ) return 0;
784 pNew->zCanonicalName = (char*)&pNew[1];
785 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
786 n = vxworksSimplifyName(pNew->zCanonicalName, n);
787
788 /* Search for an existing entry that matching the canonical name.
789 ** If found, increment the reference count and return a pointer to
790 ** the existing file ID.
791 */
792 unixEnterMutex();
793 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
794 if( pCandidate->nName==n
795 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
796 ){
797 sqlite3_free(pNew);
798 pCandidate->nRef++;
799 unixLeaveMutex();
800 return pCandidate;
801 }
802 }
803
804 /* No match was found. We will make a new file ID */
805 pNew->nRef = 1;
806 pNew->nName = n;
807 pNew->pNext = vxworksFileList;
808 vxworksFileList = pNew;
809 unixLeaveMutex();
810 return pNew;
811}
812
813/*
814** Decrement the reference count on a vxworksFileId object. Free
815** the object when the reference count reaches zero.
816*/
817static void vxworksReleaseFileId(struct vxworksFileId *pId){
818 unixEnterMutex();
819 assert( pId->nRef>0 );
820 pId->nRef--;
821 if( pId->nRef==0 ){
822 struct vxworksFileId **pp;
823 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
824 assert( *pp==pId );
825 *pp = pId->pNext;
826 sqlite3_free(pId);
827 }
828 unixLeaveMutex();
829}
830#endif /* OS_VXWORKS */
831/*************** End of Unique File ID Utility Used By VxWorks ****************
832******************************************************************************/
833
834
835/******************************************************************************
836*************************** Posix Advisory Locking ****************************
837**
drh9b35ea62008-11-29 02:20:26 +0000838** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000839** section 6.5.2.2 lines 483 through 490 specify that when a process
840** sets or clears a lock, that operation overrides any prior locks set
841** by the same process. It does not explicitly say so, but this implies
842** that it overrides locks set by the same process using a different
843** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000844**
845** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000846** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
847**
848** Suppose ./file1 and ./file2 are really the same file (because
849** one is a hard or symbolic link to the other) then if you set
850** an exclusive lock on fd1, then try to get an exclusive lock
851** on fd2, it works. I would have expected the second lock to
852** fail since there was already a lock on the file due to fd1.
853** But not so. Since both locks came from the same process, the
854** second overrides the first, even though they were on different
855** file descriptors opened on different file names.
856**
drh734c9862008-11-28 15:37:20 +0000857** This means that we cannot use POSIX locks to synchronize file access
858** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000859** to synchronize access for threads in separate processes, but not
860** threads within the same process.
861**
862** To work around the problem, SQLite has to manage file locks internally
863** on its own. Whenever a new database is opened, we have to find the
864** specific inode of the database file (the inode is determined by the
865** st_dev and st_ino fields of the stat structure that fstat() fills in)
866** and check for locks already existing on that inode. When locks are
867** created or removed, we have to look at our own internal record of the
868** locks to see if another thread has previously set a lock on that same
869** inode.
870**
drh9b35ea62008-11-29 02:20:26 +0000871** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
872** For VxWorks, we have to use the alternative unique ID system based on
873** canonical filename and implemented in the previous division.)
874**
danielk1977ad94b582007-08-20 06:44:22 +0000875** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000876** descriptor. It is now a structure that holds the integer file
877** descriptor and a pointer to a structure that describes the internal
878** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000879** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000880** point to the same locking structure. The locking structure keeps
881** a reference count (so we will know when to delete it) and a "cnt"
882** field that tells us its internal lock status. cnt==0 means the
883** file is unlocked. cnt==-1 means the file has an exclusive lock.
884** cnt>0 means there are cnt shared locks on the file.
885**
886** Any attempt to lock or unlock a file first checks the locking
887** structure. The fcntl() system call is only invoked to set a
888** POSIX lock if the internal lock structure transitions between
889** a locked and an unlocked state.
890**
drh734c9862008-11-28 15:37:20 +0000891** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000892**
893** If you close a file descriptor that points to a file that has locks,
894** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000895** released. To work around this problem, each unixInodeInfo object
896** maintains a count of the number of pending locks on tha inode.
897** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000898** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000899** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000900** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000901** be closed and that list is walked (and cleared) when the last lock
902** clears.
903**
drh9b35ea62008-11-29 02:20:26 +0000904** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000905**
drh9b35ea62008-11-29 02:20:26 +0000906** Many older versions of linux use the LinuxThreads library which is
907** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000908** A cannot be modified or overridden by a different thread B.
909** Only thread A can modify the lock. Locking behavior is correct
910** if the appliation uses the newer Native Posix Thread Library (NPTL)
911** on linux - with NPTL a lock created by thread A can override locks
912** in thread B. But there is no way to know at compile-time which
913** threading library is being used. So there is no way to know at
914** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000915** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000916** current process.
drh5fdae772004-06-29 03:29:00 +0000917**
drh8af6c222010-05-14 12:43:01 +0000918** SQLite used to support LinuxThreads. But support for LinuxThreads
919** was dropped beginning with version 3.7.0. SQLite will still work with
920** LinuxThreads provided that (1) there is no more than one connection
921** per database file in the same process and (2) database connections
922** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000923*/
924
925/*
926** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000927** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000928*/
929struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000930 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000931#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000932 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000933#else
drh107886a2008-11-21 22:21:50 +0000934 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000935#endif
936};
937
938/*
drhbbd42a62004-05-22 17:41:58 +0000939** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000940** inode. Or, on LinuxThreads, there is one of these structures for
941** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000942**
danielk1977ad94b582007-08-20 06:44:22 +0000943** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000944** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000945** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000946*/
drh8af6c222010-05-14 12:43:01 +0000947struct unixInodeInfo {
948 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000949 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000950 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
951 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000952 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000953 unixShmNode *pShmNode; /* Shared memory associated with this inode */
954 int nLock; /* Number of outstanding file locks */
955 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
956 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
957 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000958#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000959 unsigned long long sharedByte; /* for AFP simulated shared lock */
960#endif
drh6c7d5c52008-11-21 20:32:33 +0000961#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000962 sem_t *pSem; /* Named POSIX semaphore */
963 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000964#endif
drhbbd42a62004-05-22 17:41:58 +0000965};
966
drhda0e7682008-07-30 15:27:54 +0000967/*
drh8af6c222010-05-14 12:43:01 +0000968** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000969*/
drhd91c68f2010-05-14 14:52:25 +0000970static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000971
drh5fdae772004-06-29 03:29:00 +0000972/*
dane18d4952011-02-21 11:46:24 +0000973**
974** This function - unixLogError_x(), is only ever called via the macro
975** unixLogError().
976**
977** It is invoked after an error occurs in an OS function and errno has been
978** set. It logs a message using sqlite3_log() containing the current value of
979** errno and, if possible, the human-readable equivalent from strerror() or
980** strerror_r().
981**
982** The first argument passed to the macro should be the error code that
983** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
984** The two subsequent arguments should be the name of the OS function that
985** failed (e.g. "unlink", "open") and the the associated file-system path,
986** if any.
987*/
drh0e9365c2011-03-02 02:08:13 +0000988#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
989static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000990 int errcode, /* SQLite error code */
991 const char *zFunc, /* Name of OS function that failed */
992 const char *zPath, /* File path associated with error */
993 int iLine /* Source line number where error occurred */
994){
995 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +0000996 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +0000997
998 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
999 ** the strerror() function to obtain the human-readable error message
1000 ** equivalent to errno. Otherwise, use strerror_r().
1001 */
1002#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1003 char aErr[80];
1004 memset(aErr, 0, sizeof(aErr));
1005 zErr = aErr;
1006
1007 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1008 ** assume that the system provides the the GNU version of strerror_r() that
1009 ** returns a pointer to a buffer containing the error message. That pointer
1010 ** may point to aErr[], or it may point to some static storage somewhere.
1011 ** Otherwise, assume that the system provides the POSIX version of
1012 ** strerror_r(), which always writes an error message into aErr[].
1013 **
1014 ** If the code incorrectly assumes that it is the POSIX version that is
1015 ** available, the error message will often be an empty string. Not a
1016 ** huge problem. Incorrectly concluding that the GNU version is available
1017 ** could lead to a segfault though.
1018 */
1019#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1020 zErr =
1021# endif
drh0e9365c2011-03-02 02:08:13 +00001022 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001023
1024#elif SQLITE_THREADSAFE
1025 /* This is a threadsafe build, but strerror_r() is not available. */
1026 zErr = "";
1027#else
1028 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001029 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001030#endif
1031
1032 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001033 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001034 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001035 "os_unix.c:%d: (%d) %s(%s) - %s",
1036 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001037 );
1038
1039 return errcode;
1040}
1041
drh0e9365c2011-03-02 02:08:13 +00001042/*
1043** Close a file descriptor.
1044**
1045** We assume that close() almost always works, since it is only in a
1046** very sick application or on a very sick platform that it might fail.
1047** If it does fail, simply leak the file descriptor, but do log the
1048** error.
1049**
1050** Note that it is not safe to retry close() after EINTR since the
1051** file descriptor might have already been reused by another thread.
1052** So we don't even try to recover from an EINTR. Just log the error
1053** and move on.
1054*/
1055static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001056 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001057 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1058 pFile ? pFile->zPath : 0, lineno);
1059 }
1060}
dane18d4952011-02-21 11:46:24 +00001061
1062/*
danb0ac3e32010-06-16 10:55:42 +00001063** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001064*/
drh0e9365c2011-03-02 02:08:13 +00001065static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001066 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001067 UnixUnusedFd *p;
1068 UnixUnusedFd *pNext;
1069 for(p=pInode->pUnused; p; p=pNext){
1070 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001071 robust_close(pFile, p->fd, __LINE__);
1072 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001073 }
drh0e9365c2011-03-02 02:08:13 +00001074 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001075}
1076
1077/*
drh8af6c222010-05-14 12:43:01 +00001078** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001079**
1080** The mutex entered using the unixEnterMutex() function must be held
1081** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001082*/
danb0ac3e32010-06-16 10:55:42 +00001083static void releaseInodeInfo(unixFile *pFile){
1084 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001085 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001086 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001087 pInode->nRef--;
1088 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001089 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001090 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001091 if( pInode->pPrev ){
1092 assert( pInode->pPrev->pNext==pInode );
1093 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001094 }else{
drh8af6c222010-05-14 12:43:01 +00001095 assert( inodeList==pInode );
1096 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001097 }
drh8af6c222010-05-14 12:43:01 +00001098 if( pInode->pNext ){
1099 assert( pInode->pNext->pPrev==pInode );
1100 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001101 }
drh8af6c222010-05-14 12:43:01 +00001102 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001103 }
drhbbd42a62004-05-22 17:41:58 +00001104 }
1105}
1106
1107/*
drh8af6c222010-05-14 12:43:01 +00001108** Given a file descriptor, locate the unixInodeInfo object that
1109** describes that file descriptor. Create a new one if necessary. The
1110** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001111**
dan9359c7b2009-08-21 08:29:10 +00001112** The mutex entered using the unixEnterMutex() function must be held
1113** when this function is called.
1114**
drh6c7d5c52008-11-21 20:32:33 +00001115** Return an appropriate error code.
1116*/
drh8af6c222010-05-14 12:43:01 +00001117static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001118 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001119 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001120){
1121 int rc; /* System call return code */
1122 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001123 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1124 struct stat statbuf; /* Low-level file information */
1125 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001126
dan9359c7b2009-08-21 08:29:10 +00001127 assert( unixMutexHeld() );
1128
drh6c7d5c52008-11-21 20:32:33 +00001129 /* Get low-level information about the file that we can used to
1130 ** create a unique name for the file.
1131 */
1132 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001133 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001134 if( rc!=0 ){
1135 pFile->lastErrno = errno;
1136#ifdef EOVERFLOW
1137 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1138#endif
1139 return SQLITE_IOERR;
1140 }
1141
drheb0d74f2009-02-03 15:27:02 +00001142#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001143 /* On OS X on an msdos filesystem, the inode number is reported
1144 ** incorrectly for zero-size files. See ticket #3260. To work
1145 ** around this problem (we consider it a bug in OS X, not SQLite)
1146 ** we always increase the file size to 1 by writing a single byte
1147 ** prior to accessing the inode number. The one byte written is
1148 ** an ASCII 'S' character which also happens to be the first byte
1149 ** in the header of every SQLite database. In this way, if there
1150 ** is a race condition such that another thread has already populated
1151 ** the first page of the database, no damage is done.
1152 */
drh7ed97b92010-01-20 13:07:21 +00001153 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001154 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001155 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001156 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001157 return SQLITE_IOERR;
1158 }
drh99ab3b12011-03-02 15:09:07 +00001159 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001160 if( rc!=0 ){
1161 pFile->lastErrno = errno;
1162 return SQLITE_IOERR;
1163 }
1164 }
drheb0d74f2009-02-03 15:27:02 +00001165#endif
drh6c7d5c52008-11-21 20:32:33 +00001166
drh8af6c222010-05-14 12:43:01 +00001167 memset(&fileId, 0, sizeof(fileId));
1168 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001169#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001170 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001171#else
drh8af6c222010-05-14 12:43:01 +00001172 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001173#endif
drh8af6c222010-05-14 12:43:01 +00001174 pInode = inodeList;
1175 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1176 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001177 }
drh8af6c222010-05-14 12:43:01 +00001178 if( pInode==0 ){
1179 pInode = sqlite3_malloc( sizeof(*pInode) );
1180 if( pInode==0 ){
1181 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001182 }
drh8af6c222010-05-14 12:43:01 +00001183 memset(pInode, 0, sizeof(*pInode));
1184 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1185 pInode->nRef = 1;
1186 pInode->pNext = inodeList;
1187 pInode->pPrev = 0;
1188 if( inodeList ) inodeList->pPrev = pInode;
1189 inodeList = pInode;
1190 }else{
1191 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001192 }
drh8af6c222010-05-14 12:43:01 +00001193 *ppInode = pInode;
1194 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001195}
drh6c7d5c52008-11-21 20:32:33 +00001196
aswift5b1a2562008-08-22 00:22:35 +00001197
1198/*
danielk197713adf8a2004-06-03 16:08:41 +00001199** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001200** file by this or any other process. If such a lock is held, set *pResOut
1201** to a non-zero value otherwise *pResOut is set to zero. The return value
1202** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001203*/
danielk1977861f7452008-06-05 11:39:11 +00001204static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001205 int rc = SQLITE_OK;
1206 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001207 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001208
danielk1977861f7452008-06-05 11:39:11 +00001209 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1210
drh054889e2005-11-30 03:20:31 +00001211 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001212 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001213
1214 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001215 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001216 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001217 }
1218
drh2ac3ee92004-06-07 16:27:46 +00001219 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001220 */
danielk197709480a92009-02-09 05:32:32 +00001221#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001222 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001223 struct flock lock;
1224 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001225 lock.l_start = RESERVED_BYTE;
1226 lock.l_len = 1;
1227 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001228 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1229 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1230 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001231 } else if( lock.l_type!=F_UNLCK ){
1232 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001233 }
1234 }
danielk197709480a92009-02-09 05:32:32 +00001235#endif
danielk197713adf8a2004-06-03 16:08:41 +00001236
drh6c7d5c52008-11-21 20:32:33 +00001237 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001238 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001239
aswift5b1a2562008-08-22 00:22:35 +00001240 *pResOut = reserved;
1241 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001242}
1243
1244/*
drha7e61d82011-03-12 17:02:57 +00001245** Attempt to set a system-lock on the file pFile. The lock is
1246** described by pLock.
1247**
drh77197112011-03-15 19:08:48 +00001248** If the pFile was opened read/write from unix-excl, then the only lock
1249** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001250** the first time any lock is attempted. All subsequent system locking
1251** operations become no-ops. Locking operations still happen internally,
1252** in order to coordinate access between separate database connections
1253** within this process, but all of that is handled in memory and the
1254** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001255**
1256** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1257** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1258** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001259**
1260** Zero is returned if the call completes successfully, or -1 if a call
1261** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001262*/
1263static int unixFileLock(unixFile *pFile, struct flock *pLock){
1264 int rc;
drh3cb93392011-03-12 18:10:44 +00001265 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001266 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001267 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001268 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1269 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1270 ){
drh3cb93392011-03-12 18:10:44 +00001271 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001272 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001273 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001274 lock.l_whence = SEEK_SET;
1275 lock.l_start = SHARED_FIRST;
1276 lock.l_len = SHARED_SIZE;
1277 lock.l_type = F_WRLCK;
1278 rc = osFcntl(pFile->h, F_SETLK, &lock);
1279 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001280 pInode->bProcessLock = 1;
1281 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001282 }else{
1283 rc = 0;
1284 }
1285 }else{
1286 rc = osFcntl(pFile->h, F_SETLK, pLock);
1287 }
1288 return rc;
1289}
1290
1291/*
drh308c2a52010-05-14 11:30:18 +00001292** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001293** of the following:
1294**
drh2ac3ee92004-06-07 16:27:46 +00001295** (1) SHARED_LOCK
1296** (2) RESERVED_LOCK
1297** (3) PENDING_LOCK
1298** (4) EXCLUSIVE_LOCK
1299**
drhb3e04342004-06-08 00:47:47 +00001300** Sometimes when requesting one lock state, additional lock states
1301** are inserted in between. The locking might fail on one of the later
1302** transitions leaving the lock state different from what it started but
1303** still short of its goal. The following chart shows the allowed
1304** transitions and the inserted intermediate states:
1305**
1306** UNLOCKED -> SHARED
1307** SHARED -> RESERVED
1308** SHARED -> (PENDING) -> EXCLUSIVE
1309** RESERVED -> (PENDING) -> EXCLUSIVE
1310** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001311**
drha6abd042004-06-09 17:37:22 +00001312** This routine will only increase a lock. Use the sqlite3OsUnlock()
1313** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001314*/
drh308c2a52010-05-14 11:30:18 +00001315static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001316 /* The following describes the implementation of the various locks and
1317 ** lock transitions in terms of the POSIX advisory shared and exclusive
1318 ** lock primitives (called read-locks and write-locks below, to avoid
1319 ** confusion with SQLite lock names). The algorithms are complicated
1320 ** slightly in order to be compatible with windows systems simultaneously
1321 ** accessing the same database file, in case that is ever required.
1322 **
1323 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1324 ** byte', each single bytes at well known offsets, and the 'shared byte
1325 ** range', a range of 510 bytes at a well known offset.
1326 **
1327 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1328 ** byte'. If this is successful, a random byte from the 'shared byte
1329 ** range' is read-locked and the lock on the 'pending byte' released.
1330 **
danielk197790ba3bd2004-06-25 08:32:25 +00001331 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1332 ** A RESERVED lock is implemented by grabbing a write-lock on the
1333 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001334 **
1335 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001336 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1337 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1338 ** obtained, but existing SHARED locks are allowed to persist. A process
1339 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1340 ** This property is used by the algorithm for rolling back a journal file
1341 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001342 **
danielk197790ba3bd2004-06-25 08:32:25 +00001343 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1344 ** implemented by obtaining a write-lock on the entire 'shared byte
1345 ** range'. Since all other locks require a read-lock on one of the bytes
1346 ** within this range, this ensures that no other locks are held on the
1347 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001348 **
1349 ** The reason a single byte cannot be used instead of the 'shared byte
1350 ** range' is that some versions of windows do not support read-locks. By
1351 ** locking a random byte from a range, concurrent SHARED locks may exist
1352 ** even if the locking primitive used is always a write-lock.
1353 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001354 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001355 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001356 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001357 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001358 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001359
drh054889e2005-11-30 03:20:31 +00001360 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001361 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1362 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001363 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001364
1365 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001366 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001367 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001368 */
drh308c2a52010-05-14 11:30:18 +00001369 if( pFile->eFileLock>=eFileLock ){
1370 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1371 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001372 return SQLITE_OK;
1373 }
1374
drh0c2694b2009-09-03 16:23:44 +00001375 /* Make sure the locking sequence is correct.
1376 ** (1) We never move from unlocked to anything higher than shared lock.
1377 ** (2) SQLite never explicitly requests a pendig lock.
1378 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001379 */
drh308c2a52010-05-14 11:30:18 +00001380 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1381 assert( eFileLock!=PENDING_LOCK );
1382 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001383
drh8af6c222010-05-14 12:43:01 +00001384 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001385 */
drh6c7d5c52008-11-21 20:32:33 +00001386 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001387 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001388
danielk1977ad94b582007-08-20 06:44:22 +00001389 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001390 ** handle that precludes the requested lock, return BUSY.
1391 */
drh8af6c222010-05-14 12:43:01 +00001392 if( (pFile->eFileLock!=pInode->eFileLock &&
1393 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001394 ){
1395 rc = SQLITE_BUSY;
1396 goto end_lock;
1397 }
1398
1399 /* If a SHARED lock is requested, and some thread using this PID already
1400 ** has a SHARED or RESERVED lock, then increment reference counts and
1401 ** return SQLITE_OK.
1402 */
drh308c2a52010-05-14 11:30:18 +00001403 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001404 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001405 assert( eFileLock==SHARED_LOCK );
1406 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001407 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001408 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001409 pInode->nShared++;
1410 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001411 goto end_lock;
1412 }
1413
danielk19779a1d0ab2004-06-01 14:09:28 +00001414
drh3cde3bb2004-06-12 02:17:14 +00001415 /* A PENDING lock is needed before acquiring a SHARED lock and before
1416 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1417 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001418 */
drh0c2694b2009-09-03 16:23:44 +00001419 lock.l_len = 1L;
1420 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001421 if( eFileLock==SHARED_LOCK
1422 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001423 ){
drh308c2a52010-05-14 11:30:18 +00001424 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001425 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001426 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001427 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001428 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001429 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001430 pFile->lastErrno = tErrno;
1431 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 goto end_lock;
1433 }
drh3cde3bb2004-06-12 02:17:14 +00001434 }
1435
1436
1437 /* If control gets to this point, then actually go ahead and make
1438 ** operating system calls for the specified lock.
1439 */
drh308c2a52010-05-14 11:30:18 +00001440 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001441 assert( pInode->nShared==0 );
1442 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001443 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001444
drh2ac3ee92004-06-07 16:27:46 +00001445 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001446 lock.l_start = SHARED_FIRST;
1447 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001448 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001449 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001450 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001451 }
dan661d71a2011-03-30 19:08:03 +00001452
drh2ac3ee92004-06-07 16:27:46 +00001453 /* Drop the temporary PENDING lock */
1454 lock.l_start = PENDING_BYTE;
1455 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001456 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001457 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1458 /* This could happen with a network mount */
1459 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001460 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001461 }
dan661d71a2011-03-30 19:08:03 +00001462
1463 if( rc ){
1464 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001465 pFile->lastErrno = tErrno;
1466 }
dan661d71a2011-03-30 19:08:03 +00001467 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001468 }else{
drh308c2a52010-05-14 11:30:18 +00001469 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001470 pInode->nLock++;
1471 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001472 }
drh8af6c222010-05-14 12:43:01 +00001473 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001474 /* We are trying for an exclusive lock but another thread in this
1475 ** same process is still holding a shared lock. */
1476 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001477 }else{
drh3cde3bb2004-06-12 02:17:14 +00001478 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001479 ** assumed that there is a SHARED or greater lock on the file
1480 ** already.
1481 */
drh308c2a52010-05-14 11:30:18 +00001482 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001483 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001484
1485 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1486 if( eFileLock==RESERVED_LOCK ){
1487 lock.l_start = RESERVED_BYTE;
1488 lock.l_len = 1L;
1489 }else{
1490 lock.l_start = SHARED_FIRST;
1491 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001492 }
dan661d71a2011-03-30 19:08:03 +00001493
1494 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001495 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001496 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001497 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001498 pFile->lastErrno = tErrno;
1499 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001500 }
drhbbd42a62004-05-22 17:41:58 +00001501 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001502
drh8f941bc2009-01-14 23:03:40 +00001503
1504#ifndef NDEBUG
1505 /* Set up the transaction-counter change checking flags when
1506 ** transitioning from a SHARED to a RESERVED lock. The change
1507 ** from SHARED to RESERVED marks the beginning of a normal
1508 ** write operation (not a hot journal rollback).
1509 */
1510 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001511 && pFile->eFileLock<=SHARED_LOCK
1512 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001513 ){
1514 pFile->transCntrChng = 0;
1515 pFile->dbUpdate = 0;
1516 pFile->inNormalWrite = 1;
1517 }
1518#endif
1519
1520
danielk1977ecb2a962004-06-02 06:30:16 +00001521 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001522 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001523 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001524 }else if( eFileLock==EXCLUSIVE_LOCK ){
1525 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001526 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001527 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001528
1529end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001530 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001531 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1532 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001533 return rc;
1534}
1535
1536/*
dan08da86a2009-08-21 17:18:03 +00001537** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001538** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001539*/
1540static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001541 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001542 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001543 p->pNext = pInode->pUnused;
1544 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001545 pFile->h = -1;
1546 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001547}
1548
1549/*
drh308c2a52010-05-14 11:30:18 +00001550** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001551** must be either NO_LOCK or SHARED_LOCK.
1552**
1553** If the locking level of the file descriptor is already at or below
1554** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001555**
1556** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1557** the byte range is divided into 2 parts and the first part is unlocked then
1558** set to a read lock, then the other part is simply unlocked. This works
1559** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1560** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001561*/
drha7e61d82011-03-12 17:02:57 +00001562static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001563 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001564 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001565 struct flock lock;
1566 int rc = SQLITE_OK;
1567 int h;
drha6abd042004-06-09 17:37:22 +00001568
drh054889e2005-11-30 03:20:31 +00001569 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001570 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001571 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001572 getpid()));
drha6abd042004-06-09 17:37:22 +00001573
drh308c2a52010-05-14 11:30:18 +00001574 assert( eFileLock<=SHARED_LOCK );
1575 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001576 return SQLITE_OK;
1577 }
drh6c7d5c52008-11-21 20:32:33 +00001578 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001579 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001580 pInode = pFile->pInode;
1581 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001582 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001584 SimulateIOErrorBenign(1);
1585 SimulateIOError( h=(-1) )
1586 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001587
1588#ifndef NDEBUG
1589 /* When reducing a lock such that other processes can start
1590 ** reading the database file again, make sure that the
1591 ** transaction counter was updated if any part of the database
1592 ** file changed. If the transaction counter is not updated,
1593 ** other connections to the same file might not realize that
1594 ** the file has changed and hence might not know to flush their
1595 ** cache. The use of a stale cache can lead to database corruption.
1596 */
dan7c246102010-04-12 19:00:29 +00001597#if 0
drh8f941bc2009-01-14 23:03:40 +00001598 assert( pFile->inNormalWrite==0
1599 || pFile->dbUpdate==0
1600 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001601#endif
drh8f941bc2009-01-14 23:03:40 +00001602 pFile->inNormalWrite = 0;
1603#endif
1604
drh7ed97b92010-01-20 13:07:21 +00001605 /* downgrading to a shared lock on NFS involves clearing the write lock
1606 ** before establishing the readlock - to avoid a race condition we downgrade
1607 ** the lock in 2 blocks, so that part of the range will be covered by a
1608 ** write lock until the rest is covered by a read lock:
1609 ** 1: [WWWWW]
1610 ** 2: [....W]
1611 ** 3: [RRRRW]
1612 ** 4: [RRRR.]
1613 */
drh308c2a52010-05-14 11:30:18 +00001614 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001615
1616#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001617 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001618 assert( handleNFSUnlock==0 );
1619#endif
1620#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001621 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001622 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001623 off_t divSize = SHARED_SIZE - 1;
1624
1625 lock.l_type = F_UNLCK;
1626 lock.l_whence = SEEK_SET;
1627 lock.l_start = SHARED_FIRST;
1628 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001629 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001630 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001631 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001632 if( IS_LOCK_ERROR(rc) ){
1633 pFile->lastErrno = tErrno;
1634 }
1635 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001636 }
drh7ed97b92010-01-20 13:07:21 +00001637 lock.l_type = F_RDLCK;
1638 lock.l_whence = SEEK_SET;
1639 lock.l_start = SHARED_FIRST;
1640 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001641 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001642 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001643 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1644 if( IS_LOCK_ERROR(rc) ){
1645 pFile->lastErrno = tErrno;
1646 }
1647 goto end_unlock;
1648 }
1649 lock.l_type = F_UNLCK;
1650 lock.l_whence = SEEK_SET;
1651 lock.l_start = SHARED_FIRST+divSize;
1652 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001653 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001654 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001655 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001656 if( IS_LOCK_ERROR(rc) ){
1657 pFile->lastErrno = tErrno;
1658 }
1659 goto end_unlock;
1660 }
drh30f776f2011-02-25 03:25:07 +00001661 }else
1662#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1663 {
drh7ed97b92010-01-20 13:07:21 +00001664 lock.l_type = F_RDLCK;
1665 lock.l_whence = SEEK_SET;
1666 lock.l_start = SHARED_FIRST;
1667 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001668 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001669 /* In theory, the call to unixFileLock() cannot fail because another
1670 ** process is holding an incompatible lock. If it does, this
1671 ** indicates that the other process is not following the locking
1672 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1673 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1674 ** an assert to fail). */
1675 rc = SQLITE_IOERR_RDLOCK;
1676 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001677 goto end_unlock;
1678 }
drh9c105bb2004-10-02 20:38:28 +00001679 }
1680 }
drhbbd42a62004-05-22 17:41:58 +00001681 lock.l_type = F_UNLCK;
1682 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001683 lock.l_start = PENDING_BYTE;
1684 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001685 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001686 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001687 }else{
danea83bc62011-04-01 11:56:32 +00001688 rc = SQLITE_IOERR_UNLOCK;
1689 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001690 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001691 }
drhbbd42a62004-05-22 17:41:58 +00001692 }
drh308c2a52010-05-14 11:30:18 +00001693 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001694 /* Decrement the shared lock counter. Release the lock using an
1695 ** OS call only when all threads in this same process have released
1696 ** the lock.
1697 */
drh8af6c222010-05-14 12:43:01 +00001698 pInode->nShared--;
1699 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001700 lock.l_type = F_UNLCK;
1701 lock.l_whence = SEEK_SET;
1702 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001703 SimulateIOErrorBenign(1);
1704 SimulateIOError( h=(-1) )
1705 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001706 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001707 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001708 }else{
danea83bc62011-04-01 11:56:32 +00001709 rc = SQLITE_IOERR_UNLOCK;
1710 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001711 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001712 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001713 }
drha6abd042004-06-09 17:37:22 +00001714 }
1715
drhbbd42a62004-05-22 17:41:58 +00001716 /* Decrement the count of locks against this same file. When the
1717 ** count reaches zero, close any other file descriptors whose close
1718 ** was deferred because of outstanding locks.
1719 */
drh8af6c222010-05-14 12:43:01 +00001720 pInode->nLock--;
1721 assert( pInode->nLock>=0 );
1722 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001723 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001724 }
1725 }
aswift5b1a2562008-08-22 00:22:35 +00001726
1727end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001728 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001729 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001730 return rc;
drhbbd42a62004-05-22 17:41:58 +00001731}
1732
1733/*
drh308c2a52010-05-14 11:30:18 +00001734** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001735** must be either NO_LOCK or SHARED_LOCK.
1736**
1737** If the locking level of the file descriptor is already at or below
1738** the requested locking level, this routine is a no-op.
1739*/
drh308c2a52010-05-14 11:30:18 +00001740static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001741 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001742}
1743
1744/*
danielk1977e339d652008-06-28 11:23:00 +00001745** This function performs the parts of the "close file" operation
1746** common to all locking schemes. It closes the directory and file
1747** handles, if they are valid, and sets all fields of the unixFile
1748** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001749**
1750** It is *not* necessary to hold the mutex when this routine is called,
1751** even on VxWorks. A mutex will be acquired on VxWorks by the
1752** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001753*/
1754static int closeUnixFile(sqlite3_file *id){
1755 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001756 if( pFile->dirfd>=0 ){
1757 robust_close(pFile, pFile->dirfd, __LINE__);
1758 pFile->dirfd=-1;
danielk1977e339d652008-06-28 11:23:00 +00001759 }
dan661d71a2011-03-30 19:08:03 +00001760 if( pFile->h>=0 ){
1761 robust_close(pFile, pFile->h, __LINE__);
1762 pFile->h = -1;
1763 }
1764#if OS_VXWORKS
1765 if( pFile->pId ){
1766 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001767 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001768 }
1769 vxworksReleaseFileId(pFile->pId);
1770 pFile->pId = 0;
1771 }
1772#endif
1773 OSTRACE(("CLOSE %-3d\n", pFile->h));
1774 OpenCounter(-1);
1775 sqlite3_free(pFile->pUnused);
1776 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001777 return SQLITE_OK;
1778}
1779
1780/*
danielk1977e3026632004-06-22 11:29:02 +00001781** Close a file.
1782*/
danielk197762079062007-08-15 17:08:46 +00001783static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001784 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001785 unixFile *pFile = (unixFile *)id;
1786 unixUnlock(id, NO_LOCK);
1787 unixEnterMutex();
1788
1789 /* unixFile.pInode is always valid here. Otherwise, a different close
1790 ** routine (e.g. nolockClose()) would be called instead.
1791 */
1792 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1793 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1794 /* If there are outstanding locks, do not actually close the file just
1795 ** yet because that would clear those locks. Instead, add the file
1796 ** descriptor to pInode->pUnused list. It will be automatically closed
1797 ** when the last lock is cleared.
1798 */
1799 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001800 }
dan661d71a2011-03-30 19:08:03 +00001801 releaseInodeInfo(pFile);
1802 rc = closeUnixFile(id);
1803 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001804 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001805}
1806
drh734c9862008-11-28 15:37:20 +00001807/************** End of the posix advisory lock implementation *****************
1808******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001809
drh734c9862008-11-28 15:37:20 +00001810/******************************************************************************
1811****************************** No-op Locking **********************************
1812**
1813** Of the various locking implementations available, this is by far the
1814** simplest: locking is ignored. No attempt is made to lock the database
1815** file for reading or writing.
1816**
1817** This locking mode is appropriate for use on read-only databases
1818** (ex: databases that are burned into CD-ROM, for example.) It can
1819** also be used if the application employs some external mechanism to
1820** prevent simultaneous access of the same database by two or more
1821** database connections. But there is a serious risk of database
1822** corruption if this locking mode is used in situations where multiple
1823** database connections are accessing the same database file at the same
1824** time and one or more of those connections are writing.
1825*/
drhbfe66312006-10-03 17:40:40 +00001826
drh734c9862008-11-28 15:37:20 +00001827static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1828 UNUSED_PARAMETER(NotUsed);
1829 *pResOut = 0;
1830 return SQLITE_OK;
1831}
drh734c9862008-11-28 15:37:20 +00001832static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1833 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1834 return SQLITE_OK;
1835}
drh734c9862008-11-28 15:37:20 +00001836static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1837 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1838 return SQLITE_OK;
1839}
1840
1841/*
drh9b35ea62008-11-29 02:20:26 +00001842** Close the file.
drh734c9862008-11-28 15:37:20 +00001843*/
1844static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001845 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001846}
1847
1848/******************* End of the no-op lock implementation *********************
1849******************************************************************************/
1850
1851/******************************************************************************
1852************************* Begin dot-file Locking ******************************
1853**
drh0c2694b2009-09-03 16:23:44 +00001854** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001855** files in order to control access to the database. This works on just
1856** about every filesystem imaginable. But there are serious downsides:
1857**
1858** (1) There is zero concurrency. A single reader blocks all other
1859** connections from reading or writing the database.
1860**
1861** (2) An application crash or power loss can leave stale lock files
1862** sitting around that need to be cleared manually.
1863**
1864** Nevertheless, a dotlock is an appropriate locking mode for use if no
1865** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001866**
1867** Dotfile locking works by creating a file in the same directory as the
1868** database and with the same name but with a ".lock" extension added.
1869** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1870** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001871*/
1872
1873/*
1874** The file suffix added to the data base filename in order to create the
1875** lock file.
1876*/
1877#define DOTLOCK_SUFFIX ".lock"
1878
drh7708e972008-11-29 00:56:52 +00001879/*
1880** This routine checks if there is a RESERVED lock held on the specified
1881** file by this or any other process. If such a lock is held, set *pResOut
1882** to a non-zero value otherwise *pResOut is set to zero. The return value
1883** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1884**
1885** In dotfile locking, either a lock exists or it does not. So in this
1886** variation of CheckReservedLock(), *pResOut is set to true if any lock
1887** is held on the file and false if the file is unlocked.
1888*/
drh734c9862008-11-28 15:37:20 +00001889static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1890 int rc = SQLITE_OK;
1891 int reserved = 0;
1892 unixFile *pFile = (unixFile*)id;
1893
1894 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1895
1896 assert( pFile );
1897
1898 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001899 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001900 /* Either this connection or some other connection in the same process
1901 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001902 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001903 }else{
1904 /* The lock is held if and only if the lockfile exists */
1905 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001906 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001907 }
drh308c2a52010-05-14 11:30:18 +00001908 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001909 *pResOut = reserved;
1910 return rc;
1911}
1912
drh7708e972008-11-29 00:56:52 +00001913/*
drh308c2a52010-05-14 11:30:18 +00001914** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001915** of the following:
1916**
1917** (1) SHARED_LOCK
1918** (2) RESERVED_LOCK
1919** (3) PENDING_LOCK
1920** (4) EXCLUSIVE_LOCK
1921**
1922** Sometimes when requesting one lock state, additional lock states
1923** are inserted in between. The locking might fail on one of the later
1924** transitions leaving the lock state different from what it started but
1925** still short of its goal. The following chart shows the allowed
1926** transitions and the inserted intermediate states:
1927**
1928** UNLOCKED -> SHARED
1929** SHARED -> RESERVED
1930** SHARED -> (PENDING) -> EXCLUSIVE
1931** RESERVED -> (PENDING) -> EXCLUSIVE
1932** PENDING -> EXCLUSIVE
1933**
1934** This routine will only increase a lock. Use the sqlite3OsUnlock()
1935** routine to lower a locking level.
1936**
1937** With dotfile locking, we really only support state (4): EXCLUSIVE.
1938** But we track the other locking levels internally.
1939*/
drh308c2a52010-05-14 11:30:18 +00001940static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001941 unixFile *pFile = (unixFile*)id;
1942 int fd;
1943 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001944 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001945
drh7708e972008-11-29 00:56:52 +00001946
1947 /* If we have any lock, then the lock file already exists. All we have
1948 ** to do is adjust our internal record of the lock level.
1949 */
drh308c2a52010-05-14 11:30:18 +00001950 if( pFile->eFileLock > NO_LOCK ){
1951 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001952 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001953#ifdef HAVE_UTIME
1954 utime(zLockFile, NULL);
1955#else
drh734c9862008-11-28 15:37:20 +00001956 utimes(zLockFile, NULL);
1957#endif
drh7708e972008-11-29 00:56:52 +00001958 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001959 }
1960
1961 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001962 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001963 if( fd<0 ){
1964 /* failed to open/create the file, someone else may have stolen the lock */
1965 int tErrno = errno;
1966 if( EEXIST == tErrno ){
1967 rc = SQLITE_BUSY;
1968 } else {
1969 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1970 if( IS_LOCK_ERROR(rc) ){
1971 pFile->lastErrno = tErrno;
1972 }
1973 }
drh7708e972008-11-29 00:56:52 +00001974 return rc;
drh734c9862008-11-28 15:37:20 +00001975 }
drh0e9365c2011-03-02 02:08:13 +00001976 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001977
1978 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001979 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001980 return rc;
1981}
1982
drh7708e972008-11-29 00:56:52 +00001983/*
drh308c2a52010-05-14 11:30:18 +00001984** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001985** must be either NO_LOCK or SHARED_LOCK.
1986**
1987** If the locking level of the file descriptor is already at or below
1988** the requested locking level, this routine is a no-op.
1989**
1990** When the locking level reaches NO_LOCK, delete the lock file.
1991*/
drh308c2a52010-05-14 11:30:18 +00001992static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001993 unixFile *pFile = (unixFile*)id;
1994 char *zLockFile = (char *)pFile->lockingContext;
1995
1996 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001997 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1998 pFile->eFileLock, getpid()));
1999 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002000
2001 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002002 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002003 return SQLITE_OK;
2004 }
drh7708e972008-11-29 00:56:52 +00002005
2006 /* To downgrade to shared, simply update our internal notion of the
2007 ** lock state. No need to mess with the file on disk.
2008 */
drh308c2a52010-05-14 11:30:18 +00002009 if( eFileLock==SHARED_LOCK ){
2010 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002011 return SQLITE_OK;
2012 }
2013
drh7708e972008-11-29 00:56:52 +00002014 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002015 assert( eFileLock==NO_LOCK );
drh036ac7f2011-08-08 23:18:05 +00002016 if( osUnlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002017 int rc = 0;
2018 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002019 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002020 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002021 }
2022 if( IS_LOCK_ERROR(rc) ){
2023 pFile->lastErrno = tErrno;
2024 }
2025 return rc;
2026 }
drh308c2a52010-05-14 11:30:18 +00002027 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002028 return SQLITE_OK;
2029}
2030
2031/*
drh9b35ea62008-11-29 02:20:26 +00002032** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002033*/
2034static int dotlockClose(sqlite3_file *id) {
2035 int rc;
2036 if( id ){
2037 unixFile *pFile = (unixFile*)id;
2038 dotlockUnlock(id, NO_LOCK);
2039 sqlite3_free(pFile->lockingContext);
2040 }
drh734c9862008-11-28 15:37:20 +00002041 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002042 return rc;
2043}
2044/****************** End of the dot-file lock implementation *******************
2045******************************************************************************/
2046
2047/******************************************************************************
2048************************** Begin flock Locking ********************************
2049**
2050** Use the flock() system call to do file locking.
2051**
drh6b9d6dd2008-12-03 19:34:47 +00002052** flock() locking is like dot-file locking in that the various
2053** fine-grain locking levels supported by SQLite are collapsed into
2054** a single exclusive lock. In other words, SHARED, RESERVED, and
2055** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2056** still works when you do this, but concurrency is reduced since
2057** only a single process can be reading the database at a time.
2058**
drh734c9862008-11-28 15:37:20 +00002059** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2060** compiling for VXWORKS.
2061*/
2062#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002063
drh6b9d6dd2008-12-03 19:34:47 +00002064/*
drhff812312011-02-23 13:33:46 +00002065** Retry flock() calls that fail with EINTR
2066*/
2067#ifdef EINTR
2068static int robust_flock(int fd, int op){
2069 int rc;
2070 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2071 return rc;
2072}
2073#else
drh5c819272011-02-23 14:00:12 +00002074# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002075#endif
2076
2077
2078/*
drh6b9d6dd2008-12-03 19:34:47 +00002079** This routine checks if there is a RESERVED lock held on the specified
2080** file by this or any other process. If such a lock is held, set *pResOut
2081** to a non-zero value otherwise *pResOut is set to zero. The return value
2082** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2083*/
drh734c9862008-11-28 15:37:20 +00002084static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2085 int rc = SQLITE_OK;
2086 int reserved = 0;
2087 unixFile *pFile = (unixFile*)id;
2088
2089 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2090
2091 assert( pFile );
2092
2093 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002094 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002095 reserved = 1;
2096 }
2097
2098 /* Otherwise see if some other process holds it. */
2099 if( !reserved ){
2100 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002101 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002102 if( !lrc ){
2103 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002104 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002105 if ( lrc ) {
2106 int tErrno = errno;
2107 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002108 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002109 if( IS_LOCK_ERROR(lrc) ){
2110 pFile->lastErrno = tErrno;
2111 rc = lrc;
2112 }
2113 }
2114 } else {
2115 int tErrno = errno;
2116 reserved = 1;
2117 /* someone else might have it reserved */
2118 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2119 if( IS_LOCK_ERROR(lrc) ){
2120 pFile->lastErrno = tErrno;
2121 rc = lrc;
2122 }
2123 }
2124 }
drh308c2a52010-05-14 11:30:18 +00002125 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002126
2127#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2128 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2129 rc = SQLITE_OK;
2130 reserved=1;
2131 }
2132#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2133 *pResOut = reserved;
2134 return rc;
2135}
2136
drh6b9d6dd2008-12-03 19:34:47 +00002137/*
drh308c2a52010-05-14 11:30:18 +00002138** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002139** of the following:
2140**
2141** (1) SHARED_LOCK
2142** (2) RESERVED_LOCK
2143** (3) PENDING_LOCK
2144** (4) EXCLUSIVE_LOCK
2145**
2146** Sometimes when requesting one lock state, additional lock states
2147** are inserted in between. The locking might fail on one of the later
2148** transitions leaving the lock state different from what it started but
2149** still short of its goal. The following chart shows the allowed
2150** transitions and the inserted intermediate states:
2151**
2152** UNLOCKED -> SHARED
2153** SHARED -> RESERVED
2154** SHARED -> (PENDING) -> EXCLUSIVE
2155** RESERVED -> (PENDING) -> EXCLUSIVE
2156** PENDING -> EXCLUSIVE
2157**
2158** flock() only really support EXCLUSIVE locks. We track intermediate
2159** lock states in the sqlite3_file structure, but all locks SHARED or
2160** above are really EXCLUSIVE locks and exclude all other processes from
2161** access the file.
2162**
2163** This routine will only increase a lock. Use the sqlite3OsUnlock()
2164** routine to lower a locking level.
2165*/
drh308c2a52010-05-14 11:30:18 +00002166static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002167 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002168 unixFile *pFile = (unixFile*)id;
2169
2170 assert( pFile );
2171
2172 /* if we already have a lock, it is exclusive.
2173 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002174 if (pFile->eFileLock > NO_LOCK) {
2175 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002176 return SQLITE_OK;
2177 }
2178
2179 /* grab an exclusive lock */
2180
drhff812312011-02-23 13:33:46 +00002181 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002182 int tErrno = errno;
2183 /* didn't get, must be busy */
2184 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2185 if( IS_LOCK_ERROR(rc) ){
2186 pFile->lastErrno = tErrno;
2187 }
2188 } else {
2189 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002190 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002191 }
drh308c2a52010-05-14 11:30:18 +00002192 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2193 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002194#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2195 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2196 rc = SQLITE_BUSY;
2197 }
2198#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2199 return rc;
2200}
2201
drh6b9d6dd2008-12-03 19:34:47 +00002202
2203/*
drh308c2a52010-05-14 11:30:18 +00002204** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002205** must be either NO_LOCK or SHARED_LOCK.
2206**
2207** If the locking level of the file descriptor is already at or below
2208** the requested locking level, this routine is a no-op.
2209*/
drh308c2a52010-05-14 11:30:18 +00002210static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002211 unixFile *pFile = (unixFile*)id;
2212
2213 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002214 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2215 pFile->eFileLock, getpid()));
2216 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002217
2218 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002219 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002220 return SQLITE_OK;
2221 }
2222
2223 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002224 if (eFileLock==SHARED_LOCK) {
2225 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002226 return SQLITE_OK;
2227 }
2228
2229 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002230 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002231#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002232 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002233#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002234 return SQLITE_IOERR_UNLOCK;
2235 }else{
drh308c2a52010-05-14 11:30:18 +00002236 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002237 return SQLITE_OK;
2238 }
2239}
2240
2241/*
2242** Close a file.
2243*/
2244static int flockClose(sqlite3_file *id) {
2245 if( id ){
2246 flockUnlock(id, NO_LOCK);
2247 }
2248 return closeUnixFile(id);
2249}
2250
2251#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2252
2253/******************* End of the flock lock implementation *********************
2254******************************************************************************/
2255
2256/******************************************************************************
2257************************ Begin Named Semaphore Locking ************************
2258**
2259** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002260**
2261** Semaphore locking is like dot-lock and flock in that it really only
2262** supports EXCLUSIVE locking. Only a single process can read or write
2263** the database file at a time. This reduces potential concurrency, but
2264** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002265*/
2266#if OS_VXWORKS
2267
drh6b9d6dd2008-12-03 19:34:47 +00002268/*
2269** This routine checks if there is a RESERVED lock held on the specified
2270** file by this or any other process. If such a lock is held, set *pResOut
2271** to a non-zero value otherwise *pResOut is set to zero. The return value
2272** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2273*/
drh734c9862008-11-28 15:37:20 +00002274static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2275 int rc = SQLITE_OK;
2276 int reserved = 0;
2277 unixFile *pFile = (unixFile*)id;
2278
2279 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2280
2281 assert( pFile );
2282
2283 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002284 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002285 reserved = 1;
2286 }
2287
2288 /* Otherwise see if some other process holds it. */
2289 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002290 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002291 struct stat statBuf;
2292
2293 if( sem_trywait(pSem)==-1 ){
2294 int tErrno = errno;
2295 if( EAGAIN != tErrno ){
2296 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2297 pFile->lastErrno = tErrno;
2298 } else {
2299 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002300 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002301 }
2302 }else{
2303 /* we could have it if we want it */
2304 sem_post(pSem);
2305 }
2306 }
drh308c2a52010-05-14 11:30:18 +00002307 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002308
2309 *pResOut = reserved;
2310 return rc;
2311}
2312
drh6b9d6dd2008-12-03 19:34:47 +00002313/*
drh308c2a52010-05-14 11:30:18 +00002314** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002315** of the following:
2316**
2317** (1) SHARED_LOCK
2318** (2) RESERVED_LOCK
2319** (3) PENDING_LOCK
2320** (4) EXCLUSIVE_LOCK
2321**
2322** Sometimes when requesting one lock state, additional lock states
2323** are inserted in between. The locking might fail on one of the later
2324** transitions leaving the lock state different from what it started but
2325** still short of its goal. The following chart shows the allowed
2326** transitions and the inserted intermediate states:
2327**
2328** UNLOCKED -> SHARED
2329** SHARED -> RESERVED
2330** SHARED -> (PENDING) -> EXCLUSIVE
2331** RESERVED -> (PENDING) -> EXCLUSIVE
2332** PENDING -> EXCLUSIVE
2333**
2334** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2335** lock states in the sqlite3_file structure, but all locks SHARED or
2336** above are really EXCLUSIVE locks and exclude all other processes from
2337** access the file.
2338**
2339** This routine will only increase a lock. Use the sqlite3OsUnlock()
2340** routine to lower a locking level.
2341*/
drh308c2a52010-05-14 11:30:18 +00002342static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002343 unixFile *pFile = (unixFile*)id;
2344 int fd;
drh8af6c222010-05-14 12:43:01 +00002345 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002346 int rc = SQLITE_OK;
2347
2348 /* if we already have a lock, it is exclusive.
2349 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002350 if (pFile->eFileLock > NO_LOCK) {
2351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 rc = SQLITE_OK;
2353 goto sem_end_lock;
2354 }
2355
2356 /* lock semaphore now but bail out when already locked. */
2357 if( sem_trywait(pSem)==-1 ){
2358 rc = SQLITE_BUSY;
2359 goto sem_end_lock;
2360 }
2361
2362 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364
2365 sem_end_lock:
2366 return rc;
2367}
2368
drh6b9d6dd2008-12-03 19:34:47 +00002369/*
drh308c2a52010-05-14 11:30:18 +00002370** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002371** must be either NO_LOCK or SHARED_LOCK.
2372**
2373** If the locking level of the file descriptor is already at or below
2374** the requested locking level, this routine is a no-op.
2375*/
drh308c2a52010-05-14 11:30:18 +00002376static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002377 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002378 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002379
2380 assert( pFile );
2381 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002382 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2383 pFile->eFileLock, getpid()));
2384 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002385
2386 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002387 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002388 return SQLITE_OK;
2389 }
2390
2391 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002392 if (eFileLock==SHARED_LOCK) {
2393 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002394 return SQLITE_OK;
2395 }
2396
2397 /* no, really unlock. */
2398 if ( sem_post(pSem)==-1 ) {
2399 int rc, tErrno = errno;
2400 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2401 if( IS_LOCK_ERROR(rc) ){
2402 pFile->lastErrno = tErrno;
2403 }
2404 return rc;
2405 }
drh308c2a52010-05-14 11:30:18 +00002406 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002407 return SQLITE_OK;
2408}
2409
2410/*
2411 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002412 */
drh734c9862008-11-28 15:37:20 +00002413static int semClose(sqlite3_file *id) {
2414 if( id ){
2415 unixFile *pFile = (unixFile*)id;
2416 semUnlock(id, NO_LOCK);
2417 assert( pFile );
2418 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002419 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002420 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002421 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002422 }
2423 return SQLITE_OK;
2424}
2425
2426#endif /* OS_VXWORKS */
2427/*
2428** Named semaphore locking is only available on VxWorks.
2429**
2430*************** End of the named semaphore lock implementation ****************
2431******************************************************************************/
2432
2433
2434/******************************************************************************
2435*************************** Begin AFP Locking *********************************
2436**
2437** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2438** on Apple Macintosh computers - both OS9 and OSX.
2439**
2440** Third-party implementations of AFP are available. But this code here
2441** only works on OSX.
2442*/
2443
drhd2cb50b2009-01-09 21:41:17 +00002444#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002445/*
2446** The afpLockingContext structure contains all afp lock specific state
2447*/
drhbfe66312006-10-03 17:40:40 +00002448typedef struct afpLockingContext afpLockingContext;
2449struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002450 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002451 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002452};
2453
2454struct ByteRangeLockPB2
2455{
2456 unsigned long long offset; /* offset to first byte to lock */
2457 unsigned long long length; /* nbr of bytes to lock */
2458 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2459 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2460 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2461 int fd; /* file desc to assoc this lock with */
2462};
2463
drhfd131da2007-08-07 17:13:03 +00002464#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002465
drh6b9d6dd2008-12-03 19:34:47 +00002466/*
2467** This is a utility for setting or clearing a bit-range lock on an
2468** AFP filesystem.
2469**
2470** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2471*/
2472static int afpSetLock(
2473 const char *path, /* Name of the file to be locked or unlocked */
2474 unixFile *pFile, /* Open file descriptor on path */
2475 unsigned long long offset, /* First byte to be locked */
2476 unsigned long long length, /* Number of bytes to lock */
2477 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002478){
drh6b9d6dd2008-12-03 19:34:47 +00002479 struct ByteRangeLockPB2 pb;
2480 int err;
drhbfe66312006-10-03 17:40:40 +00002481
2482 pb.unLockFlag = setLockFlag ? 0 : 1;
2483 pb.startEndFlag = 0;
2484 pb.offset = offset;
2485 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002486 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002487
drh308c2a52010-05-14 11:30:18 +00002488 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002489 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002490 offset, length));
drhbfe66312006-10-03 17:40:40 +00002491 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2492 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002493 int rc;
2494 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002495 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2496 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002497#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2498 rc = SQLITE_BUSY;
2499#else
drh734c9862008-11-28 15:37:20 +00002500 rc = sqliteErrorFromPosixError(tErrno,
2501 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002502#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002503 if( IS_LOCK_ERROR(rc) ){
2504 pFile->lastErrno = tErrno;
2505 }
2506 return rc;
drhbfe66312006-10-03 17:40:40 +00002507 } else {
aswift5b1a2562008-08-22 00:22:35 +00002508 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002509 }
2510}
2511
drh6b9d6dd2008-12-03 19:34:47 +00002512/*
2513** This routine checks if there is a RESERVED lock held on the specified
2514** file by this or any other process. If such a lock is held, set *pResOut
2515** to a non-zero value otherwise *pResOut is set to zero. The return value
2516** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2517*/
danielk1977e339d652008-06-28 11:23:00 +00002518static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002519 int rc = SQLITE_OK;
2520 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002521 unixFile *pFile = (unixFile*)id;
2522
aswift5b1a2562008-08-22 00:22:35 +00002523 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2524
2525 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002526 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002527 if( context->reserved ){
2528 *pResOut = 1;
2529 return SQLITE_OK;
2530 }
drh8af6c222010-05-14 12:43:01 +00002531 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002532
2533 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002534 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002535 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002536 }
2537
2538 /* Otherwise see if some other process holds it.
2539 */
aswift5b1a2562008-08-22 00:22:35 +00002540 if( !reserved ){
2541 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002542 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002543 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002544 /* if we succeeded in taking the reserved lock, unlock it to restore
2545 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002546 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002547 } else {
2548 /* if we failed to get the lock then someone else must have it */
2549 reserved = 1;
2550 }
2551 if( IS_LOCK_ERROR(lrc) ){
2552 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002553 }
2554 }
drhbfe66312006-10-03 17:40:40 +00002555
drh7ed97b92010-01-20 13:07:21 +00002556 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002557 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002558
2559 *pResOut = reserved;
2560 return rc;
drhbfe66312006-10-03 17:40:40 +00002561}
2562
drh6b9d6dd2008-12-03 19:34:47 +00002563/*
drh308c2a52010-05-14 11:30:18 +00002564** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002565** of the following:
2566**
2567** (1) SHARED_LOCK
2568** (2) RESERVED_LOCK
2569** (3) PENDING_LOCK
2570** (4) EXCLUSIVE_LOCK
2571**
2572** Sometimes when requesting one lock state, additional lock states
2573** are inserted in between. The locking might fail on one of the later
2574** transitions leaving the lock state different from what it started but
2575** still short of its goal. The following chart shows the allowed
2576** transitions and the inserted intermediate states:
2577**
2578** UNLOCKED -> SHARED
2579** SHARED -> RESERVED
2580** SHARED -> (PENDING) -> EXCLUSIVE
2581** RESERVED -> (PENDING) -> EXCLUSIVE
2582** PENDING -> EXCLUSIVE
2583**
2584** This routine will only increase a lock. Use the sqlite3OsUnlock()
2585** routine to lower a locking level.
2586*/
drh308c2a52010-05-14 11:30:18 +00002587static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002588 int rc = SQLITE_OK;
2589 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002590 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002591 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002592
2593 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002594 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2595 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002596 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002597
drhbfe66312006-10-03 17:40:40 +00002598 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002599 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002600 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002601 */
drh308c2a52010-05-14 11:30:18 +00002602 if( pFile->eFileLock>=eFileLock ){
2603 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2604 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002605 return SQLITE_OK;
2606 }
2607
2608 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002609 ** (1) We never move from unlocked to anything higher than shared lock.
2610 ** (2) SQLite never explicitly requests a pendig lock.
2611 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002612 */
drh308c2a52010-05-14 11:30:18 +00002613 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2614 assert( eFileLock!=PENDING_LOCK );
2615 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002616
drh8af6c222010-05-14 12:43:01 +00002617 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002618 */
drh6c7d5c52008-11-21 20:32:33 +00002619 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002620 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002621
2622 /* If some thread using this PID has a lock via a different unixFile*
2623 ** handle that precludes the requested lock, return BUSY.
2624 */
drh8af6c222010-05-14 12:43:01 +00002625 if( (pFile->eFileLock!=pInode->eFileLock &&
2626 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002627 ){
2628 rc = SQLITE_BUSY;
2629 goto afp_end_lock;
2630 }
2631
2632 /* If a SHARED lock is requested, and some thread using this PID already
2633 ** has a SHARED or RESERVED lock, then increment reference counts and
2634 ** return SQLITE_OK.
2635 */
drh308c2a52010-05-14 11:30:18 +00002636 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002637 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002638 assert( eFileLock==SHARED_LOCK );
2639 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002640 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002641 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002642 pInode->nShared++;
2643 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002644 goto afp_end_lock;
2645 }
drhbfe66312006-10-03 17:40:40 +00002646
2647 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002648 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2649 ** be released.
2650 */
drh308c2a52010-05-14 11:30:18 +00002651 if( eFileLock==SHARED_LOCK
2652 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002653 ){
2654 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002655 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002656 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002657 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002658 goto afp_end_lock;
2659 }
2660 }
2661
2662 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002663 ** operating system calls for the specified lock.
2664 */
drh308c2a52010-05-14 11:30:18 +00002665 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002666 int lrc1, lrc2, lrc1Errno;
2667 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002668
drh8af6c222010-05-14 12:43:01 +00002669 assert( pInode->nShared==0 );
2670 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002671
2672 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002673 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002674 /* note that the quality of the randomness doesn't matter that much */
2675 lk = random();
drh8af6c222010-05-14 12:43:01 +00002676 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002677 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002678 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002679 if( IS_LOCK_ERROR(lrc1) ){
2680 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002681 }
aswift5b1a2562008-08-22 00:22:35 +00002682 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002683 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002684
aswift5b1a2562008-08-22 00:22:35 +00002685 if( IS_LOCK_ERROR(lrc1) ) {
2686 pFile->lastErrno = lrc1Errno;
2687 rc = lrc1;
2688 goto afp_end_lock;
2689 } else if( IS_LOCK_ERROR(lrc2) ){
2690 rc = lrc2;
2691 goto afp_end_lock;
2692 } else if( lrc1 != SQLITE_OK ) {
2693 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002694 } else {
drh308c2a52010-05-14 11:30:18 +00002695 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002696 pInode->nLock++;
2697 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002698 }
drh8af6c222010-05-14 12:43:01 +00002699 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002700 /* We are trying for an exclusive lock but another thread in this
2701 ** same process is still holding a shared lock. */
2702 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002703 }else{
2704 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2705 ** assumed that there is a SHARED or greater lock on the file
2706 ** already.
2707 */
2708 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002709 assert( 0!=pFile->eFileLock );
2710 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002711 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002712 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002713 if( !failed ){
2714 context->reserved = 1;
2715 }
drhbfe66312006-10-03 17:40:40 +00002716 }
drh308c2a52010-05-14 11:30:18 +00002717 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002718 /* Acquire an EXCLUSIVE lock */
2719
2720 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002721 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002722 */
drh6b9d6dd2008-12-03 19:34:47 +00002723 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002724 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002725 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002726 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002727 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002728 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002729 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002730 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002731 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2732 ** a critical I/O error
2733 */
2734 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2735 SQLITE_IOERR_LOCK;
2736 goto afp_end_lock;
2737 }
2738 }else{
aswift5b1a2562008-08-22 00:22:35 +00002739 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002740 }
2741 }
aswift5b1a2562008-08-22 00:22:35 +00002742 if( failed ){
2743 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002744 }
2745 }
2746
2747 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002748 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002749 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002750 }else if( eFileLock==EXCLUSIVE_LOCK ){
2751 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002752 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002753 }
2754
2755afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002756 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002757 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2758 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002759 return rc;
2760}
2761
2762/*
drh308c2a52010-05-14 11:30:18 +00002763** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002764** must be either NO_LOCK or SHARED_LOCK.
2765**
2766** If the locking level of the file descriptor is already at or below
2767** the requested locking level, this routine is a no-op.
2768*/
drh308c2a52010-05-14 11:30:18 +00002769static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002770 int rc = SQLITE_OK;
2771 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002772 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002773 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2774 int skipShared = 0;
2775#ifdef SQLITE_TEST
2776 int h = pFile->h;
2777#endif
drhbfe66312006-10-03 17:40:40 +00002778
2779 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002780 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002781 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002782 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002783
drh308c2a52010-05-14 11:30:18 +00002784 assert( eFileLock<=SHARED_LOCK );
2785 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002786 return SQLITE_OK;
2787 }
drh6c7d5c52008-11-21 20:32:33 +00002788 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002789 pInode = pFile->pInode;
2790 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002791 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002792 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002793 SimulateIOErrorBenign(1);
2794 SimulateIOError( h=(-1) )
2795 SimulateIOErrorBenign(0);
2796
2797#ifndef NDEBUG
2798 /* When reducing a lock such that other processes can start
2799 ** reading the database file again, make sure that the
2800 ** transaction counter was updated if any part of the database
2801 ** file changed. If the transaction counter is not updated,
2802 ** other connections to the same file might not realize that
2803 ** the file has changed and hence might not know to flush their
2804 ** cache. The use of a stale cache can lead to database corruption.
2805 */
2806 assert( pFile->inNormalWrite==0
2807 || pFile->dbUpdate==0
2808 || pFile->transCntrChng==1 );
2809 pFile->inNormalWrite = 0;
2810#endif
aswiftaebf4132008-11-21 00:10:35 +00002811
drh308c2a52010-05-14 11:30:18 +00002812 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002813 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002814 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002815 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002816 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002817 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2818 } else {
2819 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002820 }
2821 }
drh308c2a52010-05-14 11:30:18 +00002822 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002823 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002824 }
drh308c2a52010-05-14 11:30:18 +00002825 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002826 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2827 if( !rc ){
2828 context->reserved = 0;
2829 }
aswiftaebf4132008-11-21 00:10:35 +00002830 }
drh8af6c222010-05-14 12:43:01 +00002831 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2832 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002833 }
aswiftaebf4132008-11-21 00:10:35 +00002834 }
drh308c2a52010-05-14 11:30:18 +00002835 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002836
drh7ed97b92010-01-20 13:07:21 +00002837 /* Decrement the shared lock counter. Release the lock using an
2838 ** OS call only when all threads in this same process have released
2839 ** the lock.
2840 */
drh8af6c222010-05-14 12:43:01 +00002841 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2842 pInode->nShared--;
2843 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002844 SimulateIOErrorBenign(1);
2845 SimulateIOError( h=(-1) )
2846 SimulateIOErrorBenign(0);
2847 if( !skipShared ){
2848 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2849 }
2850 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002851 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002852 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002853 }
2854 }
2855 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002856 pInode->nLock--;
2857 assert( pInode->nLock>=0 );
2858 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002859 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002860 }
2861 }
drhbfe66312006-10-03 17:40:40 +00002862 }
drh7ed97b92010-01-20 13:07:21 +00002863
drh6c7d5c52008-11-21 20:32:33 +00002864 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002865 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002866 return rc;
2867}
2868
2869/*
drh339eb0b2008-03-07 15:34:11 +00002870** Close a file & cleanup AFP specific locking context
2871*/
danielk1977e339d652008-06-28 11:23:00 +00002872static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002873 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002874 if( id ){
2875 unixFile *pFile = (unixFile*)id;
2876 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002877 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002878 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002879 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002880 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002881 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002882 ** the last lock is cleared.
2883 */
dan08da86a2009-08-21 17:18:03 +00002884 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002885 }
danb0ac3e32010-06-16 10:55:42 +00002886 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002887 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002888 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002889 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002890 }
drh7ed97b92010-01-20 13:07:21 +00002891 return rc;
drhbfe66312006-10-03 17:40:40 +00002892}
2893
drhd2cb50b2009-01-09 21:41:17 +00002894#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002895/*
2896** The code above is the AFP lock implementation. The code is specific
2897** to MacOSX and does not work on other unix platforms. No alternative
2898** is available. If you don't compile for a mac, then the "unix-afp"
2899** VFS is not available.
2900**
2901********************* End of the AFP lock implementation **********************
2902******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002903
drh7ed97b92010-01-20 13:07:21 +00002904/******************************************************************************
2905*************************** Begin NFS Locking ********************************/
2906
2907#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2908/*
drh308c2a52010-05-14 11:30:18 +00002909 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002910 ** must be either NO_LOCK or SHARED_LOCK.
2911 **
2912 ** If the locking level of the file descriptor is already at or below
2913 ** the requested locking level, this routine is a no-op.
2914 */
drh308c2a52010-05-14 11:30:18 +00002915static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002916 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002917}
2918
2919#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2920/*
2921** The code above is the NFS lock implementation. The code is specific
2922** to MacOSX and does not work on other unix platforms. No alternative
2923** is available.
2924**
2925********************* End of the NFS lock implementation **********************
2926******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002927
2928/******************************************************************************
2929**************** Non-locking sqlite3_file methods *****************************
2930**
2931** The next division contains implementations for all methods of the
2932** sqlite3_file object other than the locking methods. The locking
2933** methods were defined in divisions above (one locking method per
2934** division). Those methods that are common to all locking modes
2935** are gather together into this division.
2936*/
drhbfe66312006-10-03 17:40:40 +00002937
2938/*
drh734c9862008-11-28 15:37:20 +00002939** Seek to the offset passed as the second argument, then read cnt
2940** bytes into pBuf. Return the number of bytes actually read.
2941**
2942** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2943** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2944** one system to another. Since SQLite does not define USE_PREAD
2945** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2946** See tickets #2741 and #2681.
2947**
2948** To avoid stomping the errno value on a failed read the lastErrno value
2949** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002950*/
drh734c9862008-11-28 15:37:20 +00002951static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2952 int got;
drh7ed97b92010-01-20 13:07:21 +00002953#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002954 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002955#endif
drh734c9862008-11-28 15:37:20 +00002956 TIMER_START;
2957#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002958 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002959 SimulateIOError( got = -1 );
2960#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002961 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002962 SimulateIOError( got = -1 );
2963#else
2964 newOffset = lseek(id->h, offset, SEEK_SET);
2965 SimulateIOError( newOffset-- );
2966 if( newOffset!=offset ){
2967 if( newOffset == -1 ){
2968 ((unixFile*)id)->lastErrno = errno;
2969 }else{
2970 ((unixFile*)id)->lastErrno = 0;
2971 }
2972 return -1;
2973 }
drhe562be52011-03-02 18:01:10 +00002974 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002975#endif
2976 TIMER_END;
2977 if( got<0 ){
2978 ((unixFile*)id)->lastErrno = errno;
2979 }
drh308c2a52010-05-14 11:30:18 +00002980 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002981 return got;
drhbfe66312006-10-03 17:40:40 +00002982}
2983
2984/*
drh734c9862008-11-28 15:37:20 +00002985** Read data from a file into a buffer. Return SQLITE_OK if all
2986** bytes were read successfully and SQLITE_IOERR if anything goes
2987** wrong.
drh339eb0b2008-03-07 15:34:11 +00002988*/
drh734c9862008-11-28 15:37:20 +00002989static int unixRead(
2990 sqlite3_file *id,
2991 void *pBuf,
2992 int amt,
2993 sqlite3_int64 offset
2994){
dan08da86a2009-08-21 17:18:03 +00002995 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002996 int got;
2997 assert( id );
drh08c6d442009-02-09 17:34:07 +00002998
dan08da86a2009-08-21 17:18:03 +00002999 /* If this is a database file (not a journal, master-journal or temp
3000 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003001#if 0
dane946c392009-08-22 11:39:46 +00003002 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003003 || offset>=PENDING_BYTE+512
3004 || offset+amt<=PENDING_BYTE
3005 );
dan7c246102010-04-12 19:00:29 +00003006#endif
drh08c6d442009-02-09 17:34:07 +00003007
dan08da86a2009-08-21 17:18:03 +00003008 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003009 if( got==amt ){
3010 return SQLITE_OK;
3011 }else if( got<0 ){
3012 /* lastErrno set by seekAndRead */
3013 return SQLITE_IOERR_READ;
3014 }else{
dan08da86a2009-08-21 17:18:03 +00003015 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003016 /* Unread parts of the buffer must be zero-filled */
3017 memset(&((char*)pBuf)[got], 0, amt-got);
3018 return SQLITE_IOERR_SHORT_READ;
3019 }
3020}
3021
3022/*
3023** Seek to the offset in id->offset then read cnt bytes into pBuf.
3024** Return the number of bytes actually read. Update the offset.
3025**
3026** To avoid stomping the errno value on a failed write the lastErrno value
3027** is set before returning.
3028*/
3029static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3030 int got;
drh7ed97b92010-01-20 13:07:21 +00003031#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003032 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003033#endif
drh734c9862008-11-28 15:37:20 +00003034 TIMER_START;
3035#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003036 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003037#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003038 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003039#else
3040 newOffset = lseek(id->h, offset, SEEK_SET);
dan661d71a2011-03-30 19:08:03 +00003041 SimulateIOError( newOffset-- );
drh734c9862008-11-28 15:37:20 +00003042 if( newOffset!=offset ){
3043 if( newOffset == -1 ){
3044 ((unixFile*)id)->lastErrno = errno;
3045 }else{
3046 ((unixFile*)id)->lastErrno = 0;
3047 }
3048 return -1;
3049 }
drhe562be52011-03-02 18:01:10 +00003050 do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003051#endif
3052 TIMER_END;
3053 if( got<0 ){
3054 ((unixFile*)id)->lastErrno = errno;
3055 }
3056
drh308c2a52010-05-14 11:30:18 +00003057 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003058 return got;
3059}
3060
3061
3062/*
3063** Write data from a buffer into a file. Return SQLITE_OK on success
3064** or some other error code on failure.
3065*/
3066static int unixWrite(
3067 sqlite3_file *id,
3068 const void *pBuf,
3069 int amt,
3070 sqlite3_int64 offset
3071){
dan08da86a2009-08-21 17:18:03 +00003072 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003073 int wrote = 0;
3074 assert( id );
3075 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003076
dan08da86a2009-08-21 17:18:03 +00003077 /* If this is a database file (not a journal, master-journal or temp
3078 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003079#if 0
dane946c392009-08-22 11:39:46 +00003080 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003081 || offset>=PENDING_BYTE+512
3082 || offset+amt<=PENDING_BYTE
3083 );
dan7c246102010-04-12 19:00:29 +00003084#endif
drh08c6d442009-02-09 17:34:07 +00003085
drh8f941bc2009-01-14 23:03:40 +00003086#ifndef NDEBUG
3087 /* If we are doing a normal write to a database file (as opposed to
3088 ** doing a hot-journal rollback or a write to some file other than a
3089 ** normal database file) then record the fact that the database
3090 ** has changed. If the transaction counter is modified, record that
3091 ** fact too.
3092 */
dan08da86a2009-08-21 17:18:03 +00003093 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003094 pFile->dbUpdate = 1; /* The database has been modified */
3095 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003096 int rc;
drh8f941bc2009-01-14 23:03:40 +00003097 char oldCntr[4];
3098 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003099 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003100 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003101 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003102 pFile->transCntrChng = 1; /* The transaction counter has changed */
3103 }
3104 }
3105 }
3106#endif
3107
dan08da86a2009-08-21 17:18:03 +00003108 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003109 amt -= wrote;
3110 offset += wrote;
3111 pBuf = &((char*)pBuf)[wrote];
3112 }
3113 SimulateIOError(( wrote=(-1), amt=1 ));
3114 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003115
drh734c9862008-11-28 15:37:20 +00003116 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003117 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003118 /* lastErrno set by seekAndWrite */
3119 return SQLITE_IOERR_WRITE;
3120 }else{
dan08da86a2009-08-21 17:18:03 +00003121 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003122 return SQLITE_FULL;
3123 }
3124 }
dan6e09d692010-07-27 18:34:15 +00003125
drh734c9862008-11-28 15:37:20 +00003126 return SQLITE_OK;
3127}
3128
3129#ifdef SQLITE_TEST
3130/*
3131** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003132** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003133*/
3134int sqlite3_sync_count = 0;
3135int sqlite3_fullsync_count = 0;
3136#endif
3137
3138/*
drh89240432009-03-25 01:06:01 +00003139** We do not trust systems to provide a working fdatasync(). Some do.
3140** Others do no. To be safe, we will stick with the (slower) fsync().
3141** If you know that your system does support fdatasync() correctly,
3142** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003143*/
drh89240432009-03-25 01:06:01 +00003144#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003145# define fdatasync fsync
3146#endif
3147
3148/*
3149** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3150** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3151** only available on Mac OS X. But that could change.
3152*/
3153#ifdef F_FULLFSYNC
3154# define HAVE_FULLFSYNC 1
3155#else
3156# define HAVE_FULLFSYNC 0
3157#endif
3158
3159
3160/*
3161** The fsync() system call does not work as advertised on many
3162** unix systems. The following procedure is an attempt to make
3163** it work better.
3164**
3165** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3166** for testing when we want to run through the test suite quickly.
3167** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3168** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3169** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003170**
3171** SQLite sets the dataOnly flag if the size of the file is unchanged.
3172** The idea behind dataOnly is that it should only write the file content
3173** to disk, not the inode. We only set dataOnly if the file size is
3174** unchanged since the file size is part of the inode. However,
3175** Ted Ts'o tells us that fdatasync() will also write the inode if the
3176** file size has changed. The only real difference between fdatasync()
3177** and fsync(), Ted tells us, is that fdatasync() will not flush the
3178** inode if the mtime or owner or other inode attributes have changed.
3179** We only care about the file size, not the other file attributes, so
3180** as far as SQLite is concerned, an fdatasync() is always adequate.
3181** So, we always use fdatasync() if it is available, regardless of
3182** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003183*/
3184static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003185 int rc;
drh734c9862008-11-28 15:37:20 +00003186
3187 /* The following "ifdef/elif/else/" block has the same structure as
3188 ** the one below. It is replicated here solely to avoid cluttering
3189 ** up the real code with the UNUSED_PARAMETER() macros.
3190 */
3191#ifdef SQLITE_NO_SYNC
3192 UNUSED_PARAMETER(fd);
3193 UNUSED_PARAMETER(fullSync);
3194 UNUSED_PARAMETER(dataOnly);
3195#elif HAVE_FULLFSYNC
3196 UNUSED_PARAMETER(dataOnly);
3197#else
3198 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003199 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003200#endif
3201
3202 /* Record the number of times that we do a normal fsync() and
3203 ** FULLSYNC. This is used during testing to verify that this procedure
3204 ** gets called with the correct arguments.
3205 */
3206#ifdef SQLITE_TEST
3207 if( fullSync ) sqlite3_fullsync_count++;
3208 sqlite3_sync_count++;
3209#endif
3210
3211 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3212 ** no-op
3213 */
3214#ifdef SQLITE_NO_SYNC
3215 rc = SQLITE_OK;
3216#elif HAVE_FULLFSYNC
3217 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003218 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003219 }else{
3220 rc = 1;
3221 }
3222 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003223 ** It shouldn't be possible for fullfsync to fail on the local
3224 ** file system (on OSX), so failure indicates that FULLFSYNC
3225 ** isn't supported for this file system. So, attempt an fsync
3226 ** and (for now) ignore the overhead of a superfluous fcntl call.
3227 ** It'd be better to detect fullfsync support once and avoid
3228 ** the fcntl call every time sync is called.
3229 */
drh734c9862008-11-28 15:37:20 +00003230 if( rc ) rc = fsync(fd);
3231
drh7ed97b92010-01-20 13:07:21 +00003232#elif defined(__APPLE__)
3233 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3234 ** so currently we default to the macro that redefines fdatasync to fsync
3235 */
3236 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003237#else
drh0b647ff2009-03-21 14:41:04 +00003238 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003239#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003240 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003241 rc = fsync(fd);
3242 }
drh0b647ff2009-03-21 14:41:04 +00003243#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003244#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3245
3246 if( OS_VXWORKS && rc!= -1 ){
3247 rc = 0;
3248 }
chw97185482008-11-17 08:05:31 +00003249 return rc;
drhbfe66312006-10-03 17:40:40 +00003250}
3251
drh734c9862008-11-28 15:37:20 +00003252/*
3253** Make sure all writes to a particular file are committed to disk.
3254**
3255** If dataOnly==0 then both the file itself and its metadata (file
3256** size, access time, etc) are synced. If dataOnly!=0 then only the
3257** file data is synced.
3258**
3259** Under Unix, also make sure that the directory entry for the file
3260** has been created by fsync-ing the directory that contains the file.
3261** If we do not do this and we encounter a power failure, the directory
3262** entry for the journal might not exist after we reboot. The next
3263** SQLite to access the file will not know that the journal exists (because
3264** the directory entry for the journal was never created) and the transaction
3265** will not roll back - possibly leading to database corruption.
3266*/
3267static int unixSync(sqlite3_file *id, int flags){
3268 int rc;
3269 unixFile *pFile = (unixFile*)id;
3270
3271 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3272 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3273
3274 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3275 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3276 || (flags&0x0F)==SQLITE_SYNC_FULL
3277 );
3278
3279 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3280 ** line is to test that doing so does not cause any problems.
3281 */
3282 SimulateDiskfullError( return SQLITE_FULL );
3283
3284 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003285 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003286 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3287 SimulateIOError( rc=1 );
3288 if( rc ){
3289 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003290 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003291 }
3292 if( pFile->dirfd>=0 ){
drh308c2a52010-05-14 11:30:18 +00003293 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3294 HAVE_FULLFSYNC, isFullsync));
drh734c9862008-11-28 15:37:20 +00003295#ifndef SQLITE_DISABLE_DIRSYNC
3296 /* The directory sync is only attempted if full_fsync is
3297 ** turned off or unavailable. If a full_fsync occurred above,
3298 ** then the directory sync is superfluous.
3299 */
3300 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3301 /*
3302 ** We have received multiple reports of fsync() returning
3303 ** errors when applied to directories on certain file systems.
3304 ** A failed directory sync is not a big deal. So it seems
3305 ** better to ignore the error. Ticket #1657
3306 */
3307 /* pFile->lastErrno = errno; */
3308 /* return SQLITE_IOERR; */
3309 }
3310#endif
drh0e9365c2011-03-02 02:08:13 +00003311 /* Only need to sync once, so close the directory when we are done */
3312 robust_close(pFile, pFile->dirfd, __LINE__);
3313 pFile->dirfd = -1;
drh734c9862008-11-28 15:37:20 +00003314 }
3315 return rc;
3316}
3317
3318/*
3319** Truncate an open file to a specified size
3320*/
3321static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003322 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003323 int rc;
dan6e09d692010-07-27 18:34:15 +00003324 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003325 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003326
3327 /* If the user has configured a chunk-size for this file, truncate the
3328 ** file so that it consists of an integer number of chunks (i.e. the
3329 ** actual file size after the operation may be larger than the requested
3330 ** size).
3331 */
3332 if( pFile->szChunk ){
3333 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3334 }
3335
drhff812312011-02-23 13:33:46 +00003336 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003337 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003338 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003339 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003340 }else{
drh3313b142009-11-06 04:13:18 +00003341#ifndef NDEBUG
3342 /* If we are doing a normal write to a database file (as opposed to
3343 ** doing a hot-journal rollback or a write to some file other than a
3344 ** normal database file) and we truncate the file to zero length,
3345 ** that effectively updates the change counter. This might happen
3346 ** when restoring a database using the backup API from a zero-length
3347 ** source.
3348 */
dan6e09d692010-07-27 18:34:15 +00003349 if( pFile->inNormalWrite && nByte==0 ){
3350 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003351 }
3352#endif
3353
drh734c9862008-11-28 15:37:20 +00003354 return SQLITE_OK;
3355 }
3356}
3357
3358/*
3359** Determine the current size of a file in bytes
3360*/
3361static int unixFileSize(sqlite3_file *id, i64 *pSize){
3362 int rc;
3363 struct stat buf;
3364 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003365 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003366 SimulateIOError( rc=1 );
3367 if( rc!=0 ){
3368 ((unixFile*)id)->lastErrno = errno;
3369 return SQLITE_IOERR_FSTAT;
3370 }
3371 *pSize = buf.st_size;
3372
drh8af6c222010-05-14 12:43:01 +00003373 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003374 ** writes a single byte into that file in order to work around a bug
3375 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3376 ** layers, we need to report this file size as zero even though it is
3377 ** really 1. Ticket #3260.
3378 */
3379 if( *pSize==1 ) *pSize = 0;
3380
3381
3382 return SQLITE_OK;
3383}
3384
drhd2cb50b2009-01-09 21:41:17 +00003385#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003386/*
3387** Handler for proxy-locking file-control verbs. Defined below in the
3388** proxying locking division.
3389*/
3390static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003391#endif
drh715ff302008-12-03 22:32:44 +00003392
dan502019c2010-07-28 14:26:17 +00003393/*
3394** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3395** file-control operation.
3396**
3397** If the user has configured a chunk-size for this file, it could be
3398** that the file needs to be extended at this point. Otherwise, the
3399** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3400*/
3401static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003402 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003403 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003404 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003405 struct stat buf; /* Used to hold return values of fstat() */
3406
drh99ab3b12011-03-02 15:09:07 +00003407 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003408
drh7d2dc712011-07-25 23:25:47 +00003409 szChunk = pFile->szChunk;
3410 if( szChunk==0 ){
3411 nSize = nByte;
3412 }else{
3413 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3414 }
dan502019c2010-07-28 14:26:17 +00003415 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003416
dan502019c2010-07-28 14:26:17 +00003417#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003418 /* The code below is handling the return value of osFallocate()
3419 ** correctly. posix_fallocate() is defined to "returns zero on success,
3420 ** or an error number on failure". See the manpage for details. */
3421 int err;
drhff812312011-02-23 13:33:46 +00003422 do{
dan661d71a2011-03-30 19:08:03 +00003423 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3424 }while( err==EINTR );
3425 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003426#else
3427 /* If the OS does not have posix_fallocate(), fake it. First use
3428 ** ftruncate() to set the file size, then write a single byte to
3429 ** the last byte in each block within the extended region. This
3430 ** is the same technique used by glibc to implement posix_fallocate()
3431 ** on systems that do not have a real fallocate() system call.
3432 */
3433 int nBlk = buf.st_blksize; /* File-system block size */
3434 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003435
drhff812312011-02-23 13:33:46 +00003436 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003437 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003438 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003439 }
3440 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003441 while( iWrite<nSize ){
3442 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3443 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003444 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003445 }
dan502019c2010-07-28 14:26:17 +00003446#endif
3447 }
3448 }
3449
3450 return SQLITE_OK;
3451}
danielk1977ad94b582007-08-20 06:44:22 +00003452
danielk1977e3026632004-06-22 11:29:02 +00003453/*
drh9e33c2c2007-08-31 18:34:59 +00003454** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003455*/
drhcc6bb3e2007-08-31 16:11:35 +00003456static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003457 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003458 switch( op ){
3459 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003460 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003461 return SQLITE_OK;
3462 }
drh7708e972008-11-29 00:56:52 +00003463 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003464 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003465 return SQLITE_OK;
3466 }
dan6e09d692010-07-27 18:34:15 +00003467 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003468 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003469 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003470 }
drh9ff27ec2010-05-19 19:26:05 +00003471 case SQLITE_FCNTL_SIZE_HINT: {
drhf0b190d2011-07-26 16:03:07 +00003472 return fcntlSizeHint(pFile, *(i64 *)pArg);
3473 }
3474 case SQLITE_FCNTL_PERSIST_WAL: {
3475 int bPersist = *(int*)pArg;
3476 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003477 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003478 }else if( bPersist==0 ){
3479 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3480 }else{
3481 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3482 }
3483 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003484 }
drh8f941bc2009-01-14 23:03:40 +00003485#ifndef NDEBUG
3486 /* The pager calls this method to signal that it has done
3487 ** a rollback and that the database is therefore unchanged and
3488 ** it hence it is OK for the transaction change counter to be
3489 ** unchanged.
3490 */
3491 case SQLITE_FCNTL_DB_UNCHANGED: {
3492 ((unixFile*)id)->dbUpdate = 0;
3493 return SQLITE_OK;
3494 }
3495#endif
drhd2cb50b2009-01-09 21:41:17 +00003496#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003497 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003498 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003499 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003500 }
drhd2cb50b2009-01-09 21:41:17 +00003501#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003502 case SQLITE_FCNTL_SYNC_OMITTED: {
3503 return SQLITE_OK; /* A no-op */
3504 }
drh9e33c2c2007-08-31 18:34:59 +00003505 }
drh0b52b7d2011-01-26 19:46:22 +00003506 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003507}
3508
3509/*
danielk1977a3d4c882007-03-23 10:08:38 +00003510** Return the sector size in bytes of the underlying block device for
3511** the specified file. This is almost always 512 bytes, but may be
3512** larger for some devices.
3513**
3514** SQLite code assumes this function cannot fail. It also assumes that
3515** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003516** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003517** same for both.
3518*/
danielk1977397d65f2008-11-19 11:35:39 +00003519static int unixSectorSize(sqlite3_file *NotUsed){
3520 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003521 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003522}
3523
danielk197790949c22007-08-17 16:50:38 +00003524/*
danielk1977397d65f2008-11-19 11:35:39 +00003525** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003526*/
danielk1977397d65f2008-11-19 11:35:39 +00003527static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3528 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003529 return 0;
3530}
3531
drhd9e5c4f2010-05-12 18:01:39 +00003532#ifndef SQLITE_OMIT_WAL
3533
3534
3535/*
drhd91c68f2010-05-14 14:52:25 +00003536** Object used to represent an shared memory buffer.
3537**
3538** When multiple threads all reference the same wal-index, each thread
3539** has its own unixShm object, but they all point to a single instance
3540** of this unixShmNode object. In other words, each wal-index is opened
3541** only once per process.
3542**
3543** Each unixShmNode object is connected to a single unixInodeInfo object.
3544** We could coalesce this object into unixInodeInfo, but that would mean
3545** every open file that does not use shared memory (in other words, most
3546** open files) would have to carry around this extra information. So
3547** the unixInodeInfo object contains a pointer to this unixShmNode object
3548** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003549**
3550** unixMutexHeld() must be true when creating or destroying
3551** this object or while reading or writing the following fields:
3552**
3553** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003554**
3555** The following fields are read-only after the object is created:
3556**
3557** fid
3558** zFilename
3559**
drhd91c68f2010-05-14 14:52:25 +00003560** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003561** unixMutexHeld() is true when reading or writing any other field
3562** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003563*/
drhd91c68f2010-05-14 14:52:25 +00003564struct unixShmNode {
3565 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003566 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003567 char *zFilename; /* Name of the mmapped file */
3568 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003569 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003570 u16 nRegion; /* Size of array apRegion */
3571 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003572 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003573 int nRef; /* Number of unixShm objects pointing to this */
3574 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003575#ifdef SQLITE_DEBUG
3576 u8 exclMask; /* Mask of exclusive locks held */
3577 u8 sharedMask; /* Mask of shared locks held */
3578 u8 nextShmId; /* Next available unixShm.id value */
3579#endif
3580};
3581
3582/*
drhd9e5c4f2010-05-12 18:01:39 +00003583** Structure used internally by this VFS to record the state of an
3584** open shared memory connection.
3585**
drhd91c68f2010-05-14 14:52:25 +00003586** The following fields are initialized when this object is created and
3587** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003588**
drhd91c68f2010-05-14 14:52:25 +00003589** unixShm.pFile
3590** unixShm.id
3591**
3592** All other fields are read/write. The unixShm.pFile->mutex must be held
3593** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003594*/
3595struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003596 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3597 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003598 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003599 u16 sharedMask; /* Mask of shared locks held */
3600 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003601#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003602 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003603#endif
3604};
3605
3606/*
drhd9e5c4f2010-05-12 18:01:39 +00003607** Constants used for locking
3608*/
drhbd9676c2010-06-23 17:58:38 +00003609#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003610#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003611
drhd9e5c4f2010-05-12 18:01:39 +00003612/*
drh73b64e42010-05-30 19:55:15 +00003613** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003614**
3615** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3616** otherwise.
3617*/
3618static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003619 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3620 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003621 int ofst, /* First byte of the locking range */
3622 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003623){
3624 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003625 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003626
drhd91c68f2010-05-14 14:52:25 +00003627 /* Access to the unixShmNode object is serialized by the caller */
3628 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003629
drh73b64e42010-05-30 19:55:15 +00003630 /* Shared locks never span more than one byte */
3631 assert( n==1 || lockType!=F_RDLCK );
3632
3633 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003634 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003635
drh3cb93392011-03-12 18:10:44 +00003636 if( pShmNode->h>=0 ){
3637 /* Initialize the locking parameters */
3638 memset(&f, 0, sizeof(f));
3639 f.l_type = lockType;
3640 f.l_whence = SEEK_SET;
3641 f.l_start = ofst;
3642 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003643
drh3cb93392011-03-12 18:10:44 +00003644 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3645 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3646 }
drhd9e5c4f2010-05-12 18:01:39 +00003647
3648 /* Update the global lock state and do debug tracing */
3649#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003650 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003651 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003652 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003653 if( rc==SQLITE_OK ){
3654 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003655 OSTRACE(("unlock %d ok", ofst));
3656 pShmNode->exclMask &= ~mask;
3657 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003658 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003659 OSTRACE(("read-lock %d ok", ofst));
3660 pShmNode->exclMask &= ~mask;
3661 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003662 }else{
3663 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003664 OSTRACE(("write-lock %d ok", ofst));
3665 pShmNode->exclMask |= mask;
3666 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003667 }
3668 }else{
3669 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003670 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003671 }else if( lockType==F_RDLCK ){
3672 OSTRACE(("read-lock failed"));
3673 }else{
3674 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003675 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003676 }
3677 }
drh20e1f082010-05-31 16:10:12 +00003678 OSTRACE((" - afterwards %03x,%03x\n",
3679 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003680 }
drhd9e5c4f2010-05-12 18:01:39 +00003681#endif
3682
3683 return rc;
3684}
3685
drhd9e5c4f2010-05-12 18:01:39 +00003686
3687/*
drhd91c68f2010-05-14 14:52:25 +00003688** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003689**
3690** This is not a VFS shared-memory method; it is a utility function called
3691** by VFS shared-memory methods.
3692*/
drhd91c68f2010-05-14 14:52:25 +00003693static void unixShmPurge(unixFile *pFd){
3694 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003695 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003696 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003697 int i;
drhd91c68f2010-05-14 14:52:25 +00003698 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003699 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003700 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003701 if( p->h>=0 ){
3702 munmap(p->apRegion[i], p->szRegion);
3703 }else{
3704 sqlite3_free(p->apRegion[i]);
3705 }
dan13a3cb82010-06-11 19:04:21 +00003706 }
dan18801912010-06-14 14:07:50 +00003707 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003708 if( p->h>=0 ){
3709 robust_close(pFd, p->h, __LINE__);
3710 p->h = -1;
3711 }
drhd91c68f2010-05-14 14:52:25 +00003712 p->pInode->pShmNode = 0;
3713 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003714 }
3715}
3716
3717/*
danda9fe0c2010-07-13 18:44:03 +00003718** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003719** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003720**
drh7234c6d2010-06-19 15:10:09 +00003721** The file used to implement shared-memory is in the same directory
3722** as the open database file and has the same name as the open database
3723** file with the "-shm" suffix added. For example, if the database file
3724** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003725** for shared memory will be called "/home/user1/config.db-shm".
3726**
3727** Another approach to is to use files in /dev/shm or /dev/tmp or an
3728** some other tmpfs mount. But if a file in a different directory
3729** from the database file is used, then differing access permissions
3730** or a chroot() might cause two different processes on the same
3731** database to end up using different files for shared memory -
3732** meaning that their memory would not really be shared - resulting
3733** in database corruption. Nevertheless, this tmpfs file usage
3734** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3735** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3736** option results in an incompatible build of SQLite; builds of SQLite
3737** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3738** same database file at the same time, database corruption will likely
3739** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3740** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003741**
3742** When opening a new shared-memory file, if no other instances of that
3743** file are currently open, in this process or in other processes, then
3744** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003745**
3746** If the original database file (pDbFd) is using the "unix-excl" VFS
3747** that means that an exclusive lock is held on the database file and
3748** that no other processes are able to read or write the database. In
3749** that case, we do not really need shared memory. No shared memory
3750** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003751*/
danda9fe0c2010-07-13 18:44:03 +00003752static int unixOpenSharedMemory(unixFile *pDbFd){
3753 struct unixShm *p = 0; /* The connection to be opened */
3754 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3755 int rc; /* Result code */
3756 unixInodeInfo *pInode; /* The inode of fd */
3757 char *zShmFilename; /* Name of the file used for SHM */
3758 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003759
danda9fe0c2010-07-13 18:44:03 +00003760 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003761 p = sqlite3_malloc( sizeof(*p) );
3762 if( p==0 ) return SQLITE_NOMEM;
3763 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003764 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003765
danda9fe0c2010-07-13 18:44:03 +00003766 /* Check to see if a unixShmNode object already exists. Reuse an existing
3767 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003768 */
3769 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003770 pInode = pDbFd->pInode;
3771 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003772 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003773 struct stat sStat; /* fstat() info for database file */
3774
3775 /* Call fstat() to figure out the permissions on the database file. If
3776 ** a new *-shm file is created, an attempt will be made to create it
3777 ** with the same permissions. The actual permissions the file is created
3778 ** with are subject to the current umask setting.
3779 */
drh3cb93392011-03-12 18:10:44 +00003780 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003781 rc = SQLITE_IOERR_FSTAT;
3782 goto shm_open_err;
3783 }
3784
drha4ced192010-07-15 18:32:40 +00003785#ifdef SQLITE_SHM_DIRECTORY
3786 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3787#else
drh7234c6d2010-06-19 15:10:09 +00003788 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003789#endif
drh7234c6d2010-06-19 15:10:09 +00003790 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003791 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003792 rc = SQLITE_NOMEM;
3793 goto shm_open_err;
3794 }
drhd91c68f2010-05-14 14:52:25 +00003795 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003796 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003797#ifdef SQLITE_SHM_DIRECTORY
3798 sqlite3_snprintf(nShmFilename, zShmFilename,
3799 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3800 (u32)sStat.st_ino, (u32)sStat.st_dev);
3801#else
drh7234c6d2010-06-19 15:10:09 +00003802 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003803 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003804#endif
drhd91c68f2010-05-14 14:52:25 +00003805 pShmNode->h = -1;
3806 pDbFd->pInode->pShmNode = pShmNode;
3807 pShmNode->pInode = pDbFd->pInode;
3808 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3809 if( pShmNode->mutex==0 ){
3810 rc = SQLITE_NOMEM;
3811 goto shm_open_err;
3812 }
drhd9e5c4f2010-05-12 18:01:39 +00003813
drh3cb93392011-03-12 18:10:44 +00003814 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003815 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3816 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003817 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003818 const char *zRO;
3819 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003820 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003821 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3822 (sStat.st_mode & 0777));
3823 pShmNode->isReadonly = 1;
3824 }
3825 if( pShmNode->h<0 ){
3826 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3827 goto shm_open_err;
3828 }
drhd9e5c4f2010-05-12 18:01:39 +00003829 }
drh3cb93392011-03-12 18:10:44 +00003830
3831 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003832 ** If not, truncate the file to zero length.
3833 */
3834 rc = SQLITE_OK;
3835 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3836 if( robust_ftruncate(pShmNode->h, 0) ){
3837 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003838 }
3839 }
drh66dfec8b2011-06-01 20:01:49 +00003840 if( rc==SQLITE_OK ){
3841 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3842 }
3843 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003844 }
drhd9e5c4f2010-05-12 18:01:39 +00003845 }
3846
drhd91c68f2010-05-14 14:52:25 +00003847 /* Make the new connection a child of the unixShmNode */
3848 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003849#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003850 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003851#endif
drhd91c68f2010-05-14 14:52:25 +00003852 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003853 pDbFd->pShm = p;
3854 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003855
3856 /* The reference count on pShmNode has already been incremented under
3857 ** the cover of the unixEnterMutex() mutex and the pointer from the
3858 ** new (struct unixShm) object to the pShmNode has been set. All that is
3859 ** left to do is to link the new object into the linked list starting
3860 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3861 ** mutex.
3862 */
3863 sqlite3_mutex_enter(pShmNode->mutex);
3864 p->pNext = pShmNode->pFirst;
3865 pShmNode->pFirst = p;
3866 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003867 return SQLITE_OK;
3868
3869 /* Jump here on any error */
3870shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003871 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003872 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003873 unixLeaveMutex();
3874 return rc;
3875}
3876
3877/*
danda9fe0c2010-07-13 18:44:03 +00003878** This function is called to obtain a pointer to region iRegion of the
3879** shared-memory associated with the database file fd. Shared-memory regions
3880** are numbered starting from zero. Each shared-memory region is szRegion
3881** bytes in size.
3882**
3883** If an error occurs, an error code is returned and *pp is set to NULL.
3884**
3885** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3886** region has not been allocated (by any client, including one running in a
3887** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3888** bExtend is non-zero and the requested shared-memory region has not yet
3889** been allocated, it is allocated by this function.
3890**
3891** If the shared-memory region has already been allocated or is allocated by
3892** this call as described above, then it is mapped into this processes
3893** address space (if it is not already), *pp is set to point to the mapped
3894** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003895*/
danda9fe0c2010-07-13 18:44:03 +00003896static int unixShmMap(
3897 sqlite3_file *fd, /* Handle open on database file */
3898 int iRegion, /* Region to retrieve */
3899 int szRegion, /* Size of regions */
3900 int bExtend, /* True to extend file if necessary */
3901 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003902){
danda9fe0c2010-07-13 18:44:03 +00003903 unixFile *pDbFd = (unixFile*)fd;
3904 unixShm *p;
3905 unixShmNode *pShmNode;
3906 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003907
danda9fe0c2010-07-13 18:44:03 +00003908 /* If the shared-memory file has not yet been opened, open it now. */
3909 if( pDbFd->pShm==0 ){
3910 rc = unixOpenSharedMemory(pDbFd);
3911 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003912 }
drhd9e5c4f2010-05-12 18:01:39 +00003913
danda9fe0c2010-07-13 18:44:03 +00003914 p = pDbFd->pShm;
3915 pShmNode = p->pShmNode;
3916 sqlite3_mutex_enter(pShmNode->mutex);
3917 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003918 assert( pShmNode->pInode==pDbFd->pInode );
3919 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3920 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003921
3922 if( pShmNode->nRegion<=iRegion ){
3923 char **apNew; /* New apRegion[] array */
3924 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3925 struct stat sStat; /* Used by fstat() */
3926
3927 pShmNode->szRegion = szRegion;
3928
drh3cb93392011-03-12 18:10:44 +00003929 if( pShmNode->h>=0 ){
3930 /* The requested region is not mapped into this processes address space.
3931 ** Check to see if it has been allocated (i.e. if the wal-index file is
3932 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003933 */
drh3cb93392011-03-12 18:10:44 +00003934 if( osFstat(pShmNode->h, &sStat) ){
3935 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003936 goto shmpage_out;
3937 }
drh3cb93392011-03-12 18:10:44 +00003938
3939 if( sStat.st_size<nByte ){
3940 /* The requested memory region does not exist. If bExtend is set to
3941 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3942 **
3943 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3944 ** the requested memory region.
3945 */
3946 if( !bExtend ) goto shmpage_out;
3947 if( robust_ftruncate(pShmNode->h, nByte) ){
3948 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3949 pShmNode->zFilename);
3950 goto shmpage_out;
3951 }
3952 }
danda9fe0c2010-07-13 18:44:03 +00003953 }
3954
3955 /* Map the requested memory region into this processes address space. */
3956 apNew = (char **)sqlite3_realloc(
3957 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3958 );
3959 if( !apNew ){
3960 rc = SQLITE_IOERR_NOMEM;
3961 goto shmpage_out;
3962 }
3963 pShmNode->apRegion = apNew;
3964 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00003965 void *pMem;
3966 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00003967 pMem = mmap(0, szRegion,
3968 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00003969 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3970 );
3971 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00003972 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00003973 goto shmpage_out;
3974 }
3975 }else{
3976 pMem = sqlite3_malloc(szRegion);
3977 if( pMem==0 ){
3978 rc = SQLITE_NOMEM;
3979 goto shmpage_out;
3980 }
3981 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00003982 }
3983 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3984 pShmNode->nRegion++;
3985 }
3986 }
3987
3988shmpage_out:
3989 if( pShmNode->nRegion>iRegion ){
3990 *pp = pShmNode->apRegion[iRegion];
3991 }else{
3992 *pp = 0;
3993 }
drh66dfec8b2011-06-01 20:01:49 +00003994 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00003995 sqlite3_mutex_leave(pShmNode->mutex);
3996 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003997}
3998
3999/*
drhd9e5c4f2010-05-12 18:01:39 +00004000** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004001**
4002** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4003** different here than in posix. In xShmLock(), one can go from unlocked
4004** to shared and back or from unlocked to exclusive and back. But one may
4005** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004006*/
4007static int unixShmLock(
4008 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004009 int ofst, /* First lock to acquire or release */
4010 int n, /* Number of locks to acquire or release */
4011 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004012){
drh73b64e42010-05-30 19:55:15 +00004013 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4014 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4015 unixShm *pX; /* For looping over all siblings */
4016 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4017 int rc = SQLITE_OK; /* Result code */
4018 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004019
drhd91c68f2010-05-14 14:52:25 +00004020 assert( pShmNode==pDbFd->pInode->pShmNode );
4021 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004022 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004023 assert( n>=1 );
4024 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4025 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4026 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4027 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4028 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004029 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4030 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004031
drhc99597c2010-05-31 01:41:15 +00004032 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004033 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004034 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004035 if( flags & SQLITE_SHM_UNLOCK ){
4036 u16 allMask = 0; /* Mask of locks held by siblings */
4037
4038 /* See if any siblings hold this same lock */
4039 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4040 if( pX==p ) continue;
4041 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4042 allMask |= pX->sharedMask;
4043 }
4044
4045 /* Unlock the system-level locks */
4046 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004047 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004048 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004049 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004050 }
drh73b64e42010-05-30 19:55:15 +00004051
4052 /* Undo the local locks */
4053 if( rc==SQLITE_OK ){
4054 p->exclMask &= ~mask;
4055 p->sharedMask &= ~mask;
4056 }
4057 }else if( flags & SQLITE_SHM_SHARED ){
4058 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4059
4060 /* Find out which shared locks are already held by sibling connections.
4061 ** If any sibling already holds an exclusive lock, go ahead and return
4062 ** SQLITE_BUSY.
4063 */
4064 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004065 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004066 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004067 break;
4068 }
4069 allShared |= pX->sharedMask;
4070 }
4071
4072 /* Get shared locks at the system level, if necessary */
4073 if( rc==SQLITE_OK ){
4074 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004075 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004076 }else{
drh73b64e42010-05-30 19:55:15 +00004077 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004078 }
drhd9e5c4f2010-05-12 18:01:39 +00004079 }
drh73b64e42010-05-30 19:55:15 +00004080
4081 /* Get the local shared locks */
4082 if( rc==SQLITE_OK ){
4083 p->sharedMask |= mask;
4084 }
4085 }else{
4086 /* Make sure no sibling connections hold locks that will block this
4087 ** lock. If any do, return SQLITE_BUSY right away.
4088 */
4089 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004090 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4091 rc = SQLITE_BUSY;
4092 break;
4093 }
4094 }
4095
4096 /* Get the exclusive locks at the system level. Then if successful
4097 ** also mark the local connection as being locked.
4098 */
4099 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004100 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004101 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004102 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004103 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004104 }
drhd9e5c4f2010-05-12 18:01:39 +00004105 }
4106 }
drhd91c68f2010-05-14 14:52:25 +00004107 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004108 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4109 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004110 return rc;
4111}
4112
drh286a2882010-05-20 23:51:06 +00004113/*
4114** Implement a memory barrier or memory fence on shared memory.
4115**
4116** All loads and stores begun before the barrier must complete before
4117** any load or store begun after the barrier.
4118*/
4119static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004120 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004121){
drhff828942010-06-26 21:34:06 +00004122 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004123 unixEnterMutex();
4124 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004125}
4126
dan18801912010-06-14 14:07:50 +00004127/*
danda9fe0c2010-07-13 18:44:03 +00004128** Close a connection to shared-memory. Delete the underlying
4129** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004130**
4131** If there is no shared memory associated with the connection then this
4132** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004133*/
danda9fe0c2010-07-13 18:44:03 +00004134static int unixShmUnmap(
4135 sqlite3_file *fd, /* The underlying database file */
4136 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004137){
danda9fe0c2010-07-13 18:44:03 +00004138 unixShm *p; /* The connection to be closed */
4139 unixShmNode *pShmNode; /* The underlying shared-memory file */
4140 unixShm **pp; /* For looping over sibling connections */
4141 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004142
danda9fe0c2010-07-13 18:44:03 +00004143 pDbFd = (unixFile*)fd;
4144 p = pDbFd->pShm;
4145 if( p==0 ) return SQLITE_OK;
4146 pShmNode = p->pShmNode;
4147
4148 assert( pShmNode==pDbFd->pInode->pShmNode );
4149 assert( pShmNode->pInode==pDbFd->pInode );
4150
4151 /* Remove connection p from the set of connections associated
4152 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004153 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004154 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4155 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004156
danda9fe0c2010-07-13 18:44:03 +00004157 /* Free the connection p */
4158 sqlite3_free(p);
4159 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004160 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004161
4162 /* If pShmNode->nRef has reached 0, then close the underlying
4163 ** shared-memory file, too */
4164 unixEnterMutex();
4165 assert( pShmNode->nRef>0 );
4166 pShmNode->nRef--;
4167 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004168 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004169 unixShmPurge(pDbFd);
4170 }
4171 unixLeaveMutex();
4172
4173 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004174}
drh286a2882010-05-20 23:51:06 +00004175
danda9fe0c2010-07-13 18:44:03 +00004176
drhd9e5c4f2010-05-12 18:01:39 +00004177#else
drh6b017cc2010-06-14 18:01:46 +00004178# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004179# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004180# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004181# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004182#endif /* #ifndef SQLITE_OMIT_WAL */
4183
drh734c9862008-11-28 15:37:20 +00004184/*
4185** Here ends the implementation of all sqlite3_file methods.
4186**
4187********************** End sqlite3_file Methods *******************************
4188******************************************************************************/
4189
4190/*
drh6b9d6dd2008-12-03 19:34:47 +00004191** This division contains definitions of sqlite3_io_methods objects that
4192** implement various file locking strategies. It also contains definitions
4193** of "finder" functions. A finder-function is used to locate the appropriate
4194** sqlite3_io_methods object for a particular database file. The pAppData
4195** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4196** the correct finder-function for that VFS.
4197**
4198** Most finder functions return a pointer to a fixed sqlite3_io_methods
4199** object. The only interesting finder-function is autolockIoFinder, which
4200** looks at the filesystem type and tries to guess the best locking
4201** strategy from that.
4202**
drh1875f7a2008-12-08 18:19:17 +00004203** For finder-funtion F, two objects are created:
4204**
4205** (1) The real finder-function named "FImpt()".
4206**
dane946c392009-08-22 11:39:46 +00004207** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004208**
4209**
4210** A pointer to the F pointer is used as the pAppData value for VFS
4211** objects. We have to do this instead of letting pAppData point
4212** directly at the finder-function since C90 rules prevent a void*
4213** from be cast into a function pointer.
4214**
drh6b9d6dd2008-12-03 19:34:47 +00004215**
drh7708e972008-11-29 00:56:52 +00004216** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004217**
drh7708e972008-11-29 00:56:52 +00004218** * A constant sqlite3_io_methods object call METHOD that has locking
4219** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4220**
4221** * An I/O method finder function called FINDER that returns a pointer
4222** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004223*/
drhd9e5c4f2010-05-12 18:01:39 +00004224#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004225static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004226 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004227 CLOSE, /* xClose */ \
4228 unixRead, /* xRead */ \
4229 unixWrite, /* xWrite */ \
4230 unixTruncate, /* xTruncate */ \
4231 unixSync, /* xSync */ \
4232 unixFileSize, /* xFileSize */ \
4233 LOCK, /* xLock */ \
4234 UNLOCK, /* xUnlock */ \
4235 CKLOCK, /* xCheckReservedLock */ \
4236 unixFileControl, /* xFileControl */ \
4237 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004238 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004239 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004240 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004241 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004242 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004243}; \
drh0c2694b2009-09-03 16:23:44 +00004244static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4245 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004246 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004247} \
drh0c2694b2009-09-03 16:23:44 +00004248static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004249 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004250
4251/*
4252** Here are all of the sqlite3_io_methods objects for each of the
4253** locking strategies. Functions that return pointers to these methods
4254** are also created.
4255*/
4256IOMETHODS(
4257 posixIoFinder, /* Finder function name */
4258 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004259 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004260 unixClose, /* xClose method */
4261 unixLock, /* xLock method */
4262 unixUnlock, /* xUnlock method */
4263 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004264)
drh7708e972008-11-29 00:56:52 +00004265IOMETHODS(
4266 nolockIoFinder, /* Finder function name */
4267 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004268 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004269 nolockClose, /* xClose method */
4270 nolockLock, /* xLock method */
4271 nolockUnlock, /* xUnlock method */
4272 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004273)
drh7708e972008-11-29 00:56:52 +00004274IOMETHODS(
4275 dotlockIoFinder, /* Finder function name */
4276 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004277 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004278 dotlockClose, /* xClose method */
4279 dotlockLock, /* xLock method */
4280 dotlockUnlock, /* xUnlock method */
4281 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004282)
drh7708e972008-11-29 00:56:52 +00004283
chw78a13182009-04-07 05:35:03 +00004284#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004285IOMETHODS(
4286 flockIoFinder, /* Finder function name */
4287 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004288 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004289 flockClose, /* xClose method */
4290 flockLock, /* xLock method */
4291 flockUnlock, /* xUnlock method */
4292 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004293)
drh7708e972008-11-29 00:56:52 +00004294#endif
4295
drh6c7d5c52008-11-21 20:32:33 +00004296#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004297IOMETHODS(
4298 semIoFinder, /* Finder function name */
4299 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004300 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004301 semClose, /* xClose method */
4302 semLock, /* xLock method */
4303 semUnlock, /* xUnlock method */
4304 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004305)
aswiftaebf4132008-11-21 00:10:35 +00004306#endif
drh7708e972008-11-29 00:56:52 +00004307
drhd2cb50b2009-01-09 21:41:17 +00004308#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004309IOMETHODS(
4310 afpIoFinder, /* Finder function name */
4311 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004312 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004313 afpClose, /* xClose method */
4314 afpLock, /* xLock method */
4315 afpUnlock, /* xUnlock method */
4316 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004317)
drh715ff302008-12-03 22:32:44 +00004318#endif
4319
4320/*
4321** The proxy locking method is a "super-method" in the sense that it
4322** opens secondary file descriptors for the conch and lock files and
4323** it uses proxy, dot-file, AFP, and flock() locking methods on those
4324** secondary files. For this reason, the division that implements
4325** proxy locking is located much further down in the file. But we need
4326** to go ahead and define the sqlite3_io_methods and finder function
4327** for proxy locking here. So we forward declare the I/O methods.
4328*/
drhd2cb50b2009-01-09 21:41:17 +00004329#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004330static int proxyClose(sqlite3_file*);
4331static int proxyLock(sqlite3_file*, int);
4332static int proxyUnlock(sqlite3_file*, int);
4333static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004334IOMETHODS(
4335 proxyIoFinder, /* Finder function name */
4336 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004337 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004338 proxyClose, /* xClose method */
4339 proxyLock, /* xLock method */
4340 proxyUnlock, /* xUnlock method */
4341 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004342)
aswiftaebf4132008-11-21 00:10:35 +00004343#endif
drh7708e972008-11-29 00:56:52 +00004344
drh7ed97b92010-01-20 13:07:21 +00004345/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4346#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4347IOMETHODS(
4348 nfsIoFinder, /* Finder function name */
4349 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004350 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004351 unixClose, /* xClose method */
4352 unixLock, /* xLock method */
4353 nfsUnlock, /* xUnlock method */
4354 unixCheckReservedLock /* xCheckReservedLock method */
4355)
4356#endif
drh7708e972008-11-29 00:56:52 +00004357
drhd2cb50b2009-01-09 21:41:17 +00004358#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004359/*
drh6b9d6dd2008-12-03 19:34:47 +00004360** This "finder" function attempts to determine the best locking strategy
4361** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004362** object that implements that strategy.
4363**
4364** This is for MacOSX only.
4365*/
drh1875f7a2008-12-08 18:19:17 +00004366static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004367 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004368 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004369){
4370 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004371 const char *zFilesystem; /* Filesystem type name */
4372 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004373 } aMap[] = {
4374 { "hfs", &posixIoMethods },
4375 { "ufs", &posixIoMethods },
4376 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004377 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004378 { "webdav", &nolockIoMethods },
4379 { 0, 0 }
4380 };
4381 int i;
4382 struct statfs fsInfo;
4383 struct flock lockInfo;
4384
4385 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004386 /* If filePath==NULL that means we are dealing with a transient file
4387 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004388 return &nolockIoMethods;
4389 }
4390 if( statfs(filePath, &fsInfo) != -1 ){
4391 if( fsInfo.f_flags & MNT_RDONLY ){
4392 return &nolockIoMethods;
4393 }
4394 for(i=0; aMap[i].zFilesystem; i++){
4395 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4396 return aMap[i].pMethods;
4397 }
4398 }
4399 }
4400
4401 /* Default case. Handles, amongst others, "nfs".
4402 ** Test byte-range lock using fcntl(). If the call succeeds,
4403 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004404 */
drh7708e972008-11-29 00:56:52 +00004405 lockInfo.l_len = 1;
4406 lockInfo.l_start = 0;
4407 lockInfo.l_whence = SEEK_SET;
4408 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004409 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004410 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4411 return &nfsIoMethods;
4412 } else {
4413 return &posixIoMethods;
4414 }
drh7708e972008-11-29 00:56:52 +00004415 }else{
4416 return &dotlockIoMethods;
4417 }
4418}
drh0c2694b2009-09-03 16:23:44 +00004419static const sqlite3_io_methods
4420 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004421
drhd2cb50b2009-01-09 21:41:17 +00004422#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004423
chw78a13182009-04-07 05:35:03 +00004424#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4425/*
4426** This "finder" function attempts to determine the best locking strategy
4427** for the database file "filePath". It then returns the sqlite3_io_methods
4428** object that implements that strategy.
4429**
4430** This is for VXWorks only.
4431*/
4432static const sqlite3_io_methods *autolockIoFinderImpl(
4433 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004434 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004435){
4436 struct flock lockInfo;
4437
4438 if( !filePath ){
4439 /* If filePath==NULL that means we are dealing with a transient file
4440 ** that does not need to be locked. */
4441 return &nolockIoMethods;
4442 }
4443
4444 /* Test if fcntl() is supported and use POSIX style locks.
4445 ** Otherwise fall back to the named semaphore method.
4446 */
4447 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 ) {
chw78a13182009-04-07 05:35:03 +00004452 return &posixIoMethods;
4453 }else{
4454 return &semIoMethods;
4455 }
4456}
drh0c2694b2009-09-03 16:23:44 +00004457static const sqlite3_io_methods
4458 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004459
4460#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4461
drh7708e972008-11-29 00:56:52 +00004462/*
4463** An abstract type for a pointer to a IO method finder function:
4464*/
drh0c2694b2009-09-03 16:23:44 +00004465typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004466
aswiftaebf4132008-11-21 00:10:35 +00004467
drh734c9862008-11-28 15:37:20 +00004468/****************************************************************************
4469**************************** sqlite3_vfs methods ****************************
4470**
4471** This division contains the implementation of methods on the
4472** sqlite3_vfs object.
4473*/
4474
danielk1977a3d4c882007-03-23 10:08:38 +00004475/*
danielk1977e339d652008-06-28 11:23:00 +00004476** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004477*/
4478static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004479 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004480 int h, /* Open file descriptor of file being opened */
danielk1977ad94b582007-08-20 06:44:22 +00004481 int dirfd, /* Directory file descriptor */
drh218c5082008-03-07 00:27:10 +00004482 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004483 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004484 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004485 int isDelete, /* Delete on close if true */
4486 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004487){
drh7708e972008-11-29 00:56:52 +00004488 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004489 unixFile *pNew = (unixFile *)pId;
4490 int rc = SQLITE_OK;
4491
drh8af6c222010-05-14 12:43:01 +00004492 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004493
dane946c392009-08-22 11:39:46 +00004494 /* Parameter isDelete is only used on vxworks. Express this explicitly
4495 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004496 */
drh7708e972008-11-29 00:56:52 +00004497 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004498
dan00157392010-10-05 11:33:15 +00004499 /* Usually the path zFilename should not be a relative pathname. The
4500 ** exception is when opening the proxy "conch" file in builds that
4501 ** include the special Apple locking styles.
4502 */
dan00157392010-10-05 11:33:15 +00004503#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004504 assert( zFilename==0 || zFilename[0]=='/'
4505 || pVfs->pAppData==(void*)&autolockIoFinder );
4506#else
4507 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004508#endif
dan00157392010-10-05 11:33:15 +00004509
drh308c2a52010-05-14 11:30:18 +00004510 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004511 pNew->h = h;
drh218c5082008-03-07 00:27:10 +00004512 pNew->dirfd = dirfd;
drhd9e5c4f2010-05-12 18:01:39 +00004513 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004514 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4515 pNew->ctrlFlags = UNIXFILE_EXCL;
4516 }else{
4517 pNew->ctrlFlags = 0;
4518 }
drh77197112011-03-15 19:08:48 +00004519 if( isReadOnly ){
4520 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4521 }
drh339eb0b2008-03-07 15:34:11 +00004522
drh6c7d5c52008-11-21 20:32:33 +00004523#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004524 pNew->pId = vxworksFindFileId(zFilename);
4525 if( pNew->pId==0 ){
4526 noLock = 1;
4527 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004528 }
4529#endif
4530
drhda0e7682008-07-30 15:27:54 +00004531 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004532 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004533 }else{
drh0c2694b2009-09-03 16:23:44 +00004534 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004535#if SQLITE_ENABLE_LOCKING_STYLE
4536 /* Cache zFilename in the locking context (AFP and dotlock override) for
4537 ** proxyLock activation is possible (remote proxy is based on db name)
4538 ** zFilename remains valid until file is closed, to support */
4539 pNew->lockingContext = (void*)zFilename;
4540#endif
drhda0e7682008-07-30 15:27:54 +00004541 }
danielk1977e339d652008-06-28 11:23:00 +00004542
drh7ed97b92010-01-20 13:07:21 +00004543 if( pLockingStyle == &posixIoMethods
4544#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4545 || pLockingStyle == &nfsIoMethods
4546#endif
4547 ){
drh7708e972008-11-29 00:56:52 +00004548 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004549 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004550 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004551 /* If an error occured in findInodeInfo(), close the file descriptor
4552 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004553 ** in two scenarios:
4554 **
4555 ** (a) A call to fstat() failed.
4556 ** (b) A malloc failed.
4557 **
4558 ** Scenario (b) may only occur if the process is holding no other
4559 ** file descriptors open on the same file. If there were other file
4560 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004561 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004562 ** handle h - as it is guaranteed that no posix locks will be released
4563 ** by doing so.
4564 **
4565 ** If scenario (a) caused the error then things are not so safe. The
4566 ** implicit assumption here is that if fstat() fails, things are in
4567 ** such bad shape that dropping a lock or two doesn't matter much.
4568 */
drh0e9365c2011-03-02 02:08:13 +00004569 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004570 h = -1;
4571 }
drh7708e972008-11-29 00:56:52 +00004572 unixLeaveMutex();
4573 }
danielk1977e339d652008-06-28 11:23:00 +00004574
drhd2cb50b2009-01-09 21:41:17 +00004575#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004576 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004577 /* AFP locking uses the file path so it needs to be included in
4578 ** the afpLockingContext.
4579 */
4580 afpLockingContext *pCtx;
4581 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4582 if( pCtx==0 ){
4583 rc = SQLITE_NOMEM;
4584 }else{
4585 /* NB: zFilename exists and remains valid until the file is closed
4586 ** according to requirement F11141. So we do not need to make a
4587 ** copy of the filename. */
4588 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004589 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004590 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004591 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004592 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004593 if( rc!=SQLITE_OK ){
4594 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004595 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004596 h = -1;
4597 }
drh7708e972008-11-29 00:56:52 +00004598 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004599 }
drh7708e972008-11-29 00:56:52 +00004600 }
4601#endif
danielk1977e339d652008-06-28 11:23:00 +00004602
drh7708e972008-11-29 00:56:52 +00004603 else if( pLockingStyle == &dotlockIoMethods ){
4604 /* Dotfile locking uses the file path so it needs to be included in
4605 ** the dotlockLockingContext
4606 */
4607 char *zLockFile;
4608 int nFilename;
drhea678832008-12-10 19:26:22 +00004609 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004610 zLockFile = (char *)sqlite3_malloc(nFilename);
4611 if( zLockFile==0 ){
4612 rc = SQLITE_NOMEM;
4613 }else{
4614 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004615 }
drh7708e972008-11-29 00:56:52 +00004616 pNew->lockingContext = zLockFile;
4617 }
danielk1977e339d652008-06-28 11:23:00 +00004618
drh6c7d5c52008-11-21 20:32:33 +00004619#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004620 else if( pLockingStyle == &semIoMethods ){
4621 /* Named semaphore locking uses the file path so it needs to be
4622 ** included in the semLockingContext
4623 */
4624 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004625 rc = findInodeInfo(pNew, &pNew->pInode);
4626 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4627 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004628 int n;
drh2238dcc2009-08-27 17:56:20 +00004629 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004630 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004631 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004632 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004633 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4634 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004635 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004636 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004637 }
chw97185482008-11-17 08:05:31 +00004638 }
drh7708e972008-11-29 00:56:52 +00004639 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004640 }
drh7708e972008-11-29 00:56:52 +00004641#endif
aswift5b1a2562008-08-22 00:22:35 +00004642
4643 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004644#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004645 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004646 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004647 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004648 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004649 isDelete = 0;
4650 }
4651 pNew->isDelete = isDelete;
4652#endif
danielk1977e339d652008-06-28 11:23:00 +00004653 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004654 if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
4655 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004656 }else{
drh7708e972008-11-29 00:56:52 +00004657 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004658 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004659 }
danielk1977e339d652008-06-28 11:23:00 +00004660 return rc;
drh054889e2005-11-30 03:20:31 +00004661}
drh9c06c952005-11-26 00:25:00 +00004662
danielk1977ad94b582007-08-20 06:44:22 +00004663/*
4664** Open a file descriptor to the directory containing file zFilename.
4665** If successful, *pFd is set to the opened file descriptor and
4666** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
4667** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
4668** value.
4669**
4670** If SQLITE_OK is returned, the caller is responsible for closing
4671** the file descriptor *pFd using close().
4672*/
danielk1977fee2d252007-08-18 10:59:19 +00004673static int openDirectory(const char *zFilename, int *pFd){
danielk1977fee2d252007-08-18 10:59:19 +00004674 int ii;
drh777b17a2007-09-20 10:02:54 +00004675 int fd = -1;
drhf3a65f72007-08-22 20:18:21 +00004676 char zDirname[MAX_PATHNAME+1];
danielk1977fee2d252007-08-18 10:59:19 +00004677
drh153c62c2007-08-24 03:51:33 +00004678 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drh617634e2009-01-08 14:36:20 +00004679 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
danielk1977fee2d252007-08-18 10:59:19 +00004680 if( ii>0 ){
4681 zDirname[ii] = '\0';
drhad4f1e52011-03-04 15:43:57 +00004682 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drh777b17a2007-09-20 10:02:54 +00004683 if( fd>=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00004684#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00004685 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977fee2d252007-08-18 10:59:19 +00004686#endif
drh308c2a52010-05-14 11:30:18 +00004687 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004688 }
4689 }
danielk1977fee2d252007-08-18 10:59:19 +00004690 *pFd = fd;
dane18d4952011-02-21 11:46:24 +00004691 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
danielk1977fee2d252007-08-18 10:59:19 +00004692}
4693
danielk1977b4b47412007-08-17 15:53:36 +00004694/*
drh8b3cf822010-06-01 21:02:51 +00004695** Return the name of a directory in which to put temporary files.
4696** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004697*/
drh7234c6d2010-06-19 15:10:09 +00004698static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004699 static const char *azDirs[] = {
4700 0,
aswiftaebf4132008-11-21 00:10:35 +00004701 0,
danielk197717b90b52008-06-06 11:11:25 +00004702 "/var/tmp",
4703 "/usr/tmp",
4704 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004705 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004706 };
drh8b3cf822010-06-01 21:02:51 +00004707 unsigned int i;
4708 struct stat buf;
4709 const char *zDir = 0;
4710
4711 azDirs[0] = sqlite3_temp_directory;
4712 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004713 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004714 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004715 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004716 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004717 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004718 break;
4719 }
4720 return zDir;
4721}
4722
4723/*
4724** Create a temporary file name in zBuf. zBuf must be allocated
4725** by the calling process and must be big enough to hold at least
4726** pVfs->mxPathname bytes.
4727*/
4728static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004729 static const unsigned char zChars[] =
4730 "abcdefghijklmnopqrstuvwxyz"
4731 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4732 "0123456789";
drh41022642008-11-21 00:24:42 +00004733 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004734 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004735
4736 /* It's odd to simulate an io-error here, but really this is just
4737 ** using the io-error infrastructure to test that SQLite handles this
4738 ** function failing.
4739 */
4740 SimulateIOError( return SQLITE_IOERR );
4741
drh7234c6d2010-06-19 15:10:09 +00004742 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004743 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004744
4745 /* Check that the output buffer is large enough for the temporary file
4746 ** name. If it is not, return SQLITE_ERROR.
4747 */
danielk197700e13612008-11-17 19:18:54 +00004748 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004749 return SQLITE_ERROR;
4750 }
4751
4752 do{
4753 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004754 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004755 sqlite3_randomness(15, &zBuf[j]);
4756 for(i=0; i<15; i++, j++){
4757 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4758 }
4759 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004760 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004761 return SQLITE_OK;
4762}
4763
drhd2cb50b2009-01-09 21:41:17 +00004764#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004765/*
4766** Routine to transform a unixFile into a proxy-locking unixFile.
4767** Implementation in the proxy-lock division, but used by unixOpen()
4768** if SQLITE_PREFER_PROXY_LOCKING is defined.
4769*/
4770static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004771#endif
drhc66d5b62008-12-03 22:48:32 +00004772
dan08da86a2009-08-21 17:18:03 +00004773/*
4774** Search for an unused file descriptor that was opened on the database
4775** file (not a journal or master-journal file) identified by pathname
4776** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4777** argument to this function.
4778**
4779** Such a file descriptor may exist if a database connection was closed
4780** but the associated file descriptor could not be closed because some
4781** other file descriptor open on the same file is holding a file-lock.
4782** Refer to comments in the unixClose() function and the lengthy comment
4783** describing "Posix Advisory Locking" at the start of this file for
4784** further details. Also, ticket #4018.
4785**
4786** If a suitable file descriptor is found, then it is returned. If no
4787** such file descriptor is located, -1 is returned.
4788*/
dane946c392009-08-22 11:39:46 +00004789static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4790 UnixUnusedFd *pUnused = 0;
4791
4792 /* Do not search for an unused file descriptor on vxworks. Not because
4793 ** vxworks would not benefit from the change (it might, we're not sure),
4794 ** but because no way to test it is currently available. It is better
4795 ** not to risk breaking vxworks support for the sake of such an obscure
4796 ** feature. */
4797#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004798 struct stat sStat; /* Results of stat() call */
4799
4800 /* A stat() call may fail for various reasons. If this happens, it is
4801 ** almost certain that an open() call on the same path will also fail.
4802 ** For this reason, if an error occurs in the stat() call here, it is
4803 ** ignored and -1 is returned. The caller will try to open a new file
4804 ** descriptor on the same path, fail, and return an error to SQLite.
4805 **
4806 ** Even if a subsequent open() call does succeed, the consequences of
4807 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004808 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004809 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004810
4811 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004812 pInode = inodeList;
4813 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4814 || pInode->fileId.ino!=sStat.st_ino) ){
4815 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004816 }
drh8af6c222010-05-14 12:43:01 +00004817 if( pInode ){
dane946c392009-08-22 11:39:46 +00004818 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004819 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004820 pUnused = *pp;
4821 if( pUnused ){
4822 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004823 }
4824 }
4825 unixLeaveMutex();
4826 }
dane946c392009-08-22 11:39:46 +00004827#endif /* if !OS_VXWORKS */
4828 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004829}
danielk197717b90b52008-06-06 11:11:25 +00004830
4831/*
danddb0ac42010-07-14 14:48:58 +00004832** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004833** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004834** and a value suitable for passing as the third argument to open(2) is
4835** written to *pMode. If an IO error occurs, an SQLite error code is
4836** returned and the value of *pMode is not modified.
4837**
4838** If the file being opened is a temporary file, it is always created with
4839** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004840** is a database or master journal file, it is created with the permissions
4841** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004842**
drh8ab58662010-07-15 18:38:39 +00004843** Finally, if the file being opened is a WAL or regular journal file, then
4844** this function queries the file-system for the permissions on the
4845** corresponding database file and sets *pMode to this value. Whenever
4846** possible, WAL and journal files are created using the same permissions
4847** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004848**
4849** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4850** original filename is unavailable. But 8_3_NAMES is only used for
4851** FAT filesystems and permissions do not matter there, so just use
4852** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004853*/
4854static int findCreateFileMode(
4855 const char *zPath, /* Path of file (possibly) being created */
4856 int flags, /* Flags passed as 4th argument to xOpen() */
4857 mode_t *pMode /* OUT: Permissions to open file with */
4858){
4859 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004860 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004861 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004862 char zDb[MAX_PATHNAME+1]; /* Database file path */
4863 int nDb; /* Number of valid bytes in zDb */
4864 struct stat sStat; /* Output of stat() on database file */
4865
dana0c989d2010-11-05 18:07:37 +00004866 /* zPath is a path to a WAL or journal file. The following block derives
4867 ** the path to the associated database file from zPath. This block handles
4868 ** the following naming conventions:
4869 **
4870 ** "<path to db>-journal"
4871 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004872 ** "<path to db>-journalNN"
4873 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004874 **
drh81cc5162011-05-17 20:36:21 +00004875 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004876 ** used by the test_multiplex.c module.
4877 */
4878 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004879 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4880 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004881 memcpy(zDb, zPath, nDb);
4882 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004883
drh58384f12011-07-28 00:14:45 +00004884 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004885 *pMode = sStat.st_mode & 0777;
4886 }else{
4887 rc = SQLITE_IOERR_FSTAT;
4888 }
4889 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4890 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004891 }
4892 return rc;
4893}
4894
4895/*
danielk1977ad94b582007-08-20 06:44:22 +00004896** Open the file zPath.
4897**
danielk1977b4b47412007-08-17 15:53:36 +00004898** Previously, the SQLite OS layer used three functions in place of this
4899** one:
4900**
4901** sqlite3OsOpenReadWrite();
4902** sqlite3OsOpenReadOnly();
4903** sqlite3OsOpenExclusive();
4904**
4905** These calls correspond to the following combinations of flags:
4906**
4907** ReadWrite() -> (READWRITE | CREATE)
4908** ReadOnly() -> (READONLY)
4909** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4910**
4911** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4912** true, the file was configured to be automatically deleted when the
4913** file handle closed. To achieve the same effect using this new
4914** interface, add the DELETEONCLOSE flag to those specified above for
4915** OpenExclusive().
4916*/
4917static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004918 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4919 const char *zPath, /* Pathname of file to be opened */
4920 sqlite3_file *pFile, /* The file descriptor to be filled in */
4921 int flags, /* Input flags to control the opening */
4922 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004923){
dan08da86a2009-08-21 17:18:03 +00004924 unixFile *p = (unixFile *)pFile;
4925 int fd = -1; /* File descriptor returned by open() */
danielk1977fee2d252007-08-18 10:59:19 +00004926 int dirfd = -1; /* Directory file descriptor */
drh6b9d6dd2008-12-03 19:34:47 +00004927 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004928 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004929 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004930 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004931
4932 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4933 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4934 int isCreate = (flags & SQLITE_OPEN_CREATE);
4935 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4936 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004937#if SQLITE_ENABLE_LOCKING_STYLE
4938 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4939#endif
danielk1977b4b47412007-08-17 15:53:36 +00004940
danielk1977fee2d252007-08-18 10:59:19 +00004941 /* If creating a master or main-file journal, this function will open
4942 ** a file-descriptor on the directory too. The first time unixSync()
4943 ** is called the directory file descriptor will be fsync()ed and close()d.
4944 */
danddb0ac42010-07-14 14:48:58 +00004945 int isOpenDirectory = (isCreate && (
4946 eType==SQLITE_OPEN_MASTER_JOURNAL
4947 || eType==SQLITE_OPEN_MAIN_JOURNAL
4948 || eType==SQLITE_OPEN_WAL
4949 ));
danielk1977fee2d252007-08-18 10:59:19 +00004950
danielk197717b90b52008-06-06 11:11:25 +00004951 /* If argument zPath is a NULL pointer, this function is required to open
4952 ** a temporary file. Use this buffer to store the file name in.
4953 */
4954 char zTmpname[MAX_PATHNAME+1];
4955 const char *zName = zPath;
4956
danielk1977fee2d252007-08-18 10:59:19 +00004957 /* Check the following statements are true:
4958 **
4959 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4960 ** (b) if CREATE is set, then READWRITE must also be set, and
4961 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004962 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004963 */
danielk1977b4b47412007-08-17 15:53:36 +00004964 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004965 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004966 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004967 assert(isDelete==0 || isCreate);
4968
danddb0ac42010-07-14 14:48:58 +00004969 /* The main DB, main journal, WAL file and master journal are never
4970 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004971 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4972 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4973 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004974 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004975
danielk1977fee2d252007-08-18 10:59:19 +00004976 /* Assert that the upper layer has set one of the "file-type" flags. */
4977 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4978 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4979 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004980 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004981 );
4982
dan08da86a2009-08-21 17:18:03 +00004983 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00004984
dan08da86a2009-08-21 17:18:03 +00004985 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00004986 UnixUnusedFd *pUnused;
4987 pUnused = findReusableFd(zName, flags);
4988 if( pUnused ){
4989 fd = pUnused->fd;
4990 }else{
dan6aa657f2009-08-24 18:57:58 +00004991 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00004992 if( !pUnused ){
4993 return SQLITE_NOMEM;
4994 }
4995 }
4996 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00004997 }else if( !zName ){
4998 /* If zName is NULL, the upper layer is requesting a temp file. */
danielk197717b90b52008-06-06 11:11:25 +00004999 assert(isDelete && !isOpenDirectory);
drh8b3cf822010-06-01 21:02:51 +00005000 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005001 if( rc!=SQLITE_OK ){
5002 return rc;
5003 }
5004 zName = zTmpname;
5005 }
5006
dan08da86a2009-08-21 17:18:03 +00005007 /* Determine the value of the flags parameter passed to POSIX function
5008 ** open(). These must be calculated even if open() is not called, as
5009 ** they may be stored as part of the file handle and used by the
5010 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005011 if( isReadonly ) openFlags |= O_RDONLY;
5012 if( isReadWrite ) openFlags |= O_RDWR;
5013 if( isCreate ) openFlags |= O_CREAT;
5014 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5015 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005016
danielk1977b4b47412007-08-17 15:53:36 +00005017 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005018 mode_t openMode; /* Permissions to create file with */
5019 rc = findCreateFileMode(zName, flags, &openMode);
5020 if( rc!=SQLITE_OK ){
5021 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005022 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005023 return rc;
5024 }
drhad4f1e52011-03-04 15:43:57 +00005025 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005026 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005027 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5028 /* Failed to open the file for read/write access. Try read-only. */
5029 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005030 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005031 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005032 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005033 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005034 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005035 }
5036 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005037 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005038 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005039 }
danielk1977b4b47412007-08-17 15:53:36 +00005040 }
dan08da86a2009-08-21 17:18:03 +00005041 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005042 if( pOutFlags ){
5043 *pOutFlags = flags;
5044 }
5045
dane946c392009-08-22 11:39:46 +00005046 if( p->pUnused ){
5047 p->pUnused->fd = fd;
5048 p->pUnused->flags = flags;
5049 }
5050
danielk1977b4b47412007-08-17 15:53:36 +00005051 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005052#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005053 zPath = zName;
5054#else
drh036ac7f2011-08-08 23:18:05 +00005055 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005056#endif
danielk1977b4b47412007-08-17 15:53:36 +00005057 }
drh41022642008-11-21 00:24:42 +00005058#if SQLITE_ENABLE_LOCKING_STYLE
5059 else{
dan08da86a2009-08-21 17:18:03 +00005060 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005061 }
5062#endif
5063
danielk1977fee2d252007-08-18 10:59:19 +00005064 if( isOpenDirectory ){
aswiftaebf4132008-11-21 00:10:35 +00005065 rc = openDirectory(zPath, &dirfd);
danielk1977fee2d252007-08-18 10:59:19 +00005066 if( rc!=SQLITE_OK ){
dan08da86a2009-08-21 17:18:03 +00005067 /* It is safe to close fd at this point, because it is guaranteed not
5068 ** to be open on a database file. If it were open on a database file,
dane946c392009-08-22 11:39:46 +00005069 ** it would not be safe to close as this would release any locks held
5070 ** on the file by this process. */
dan08da86a2009-08-21 17:18:03 +00005071 assert( eType!=SQLITE_OPEN_MAIN_DB );
drh0e9365c2011-03-02 02:08:13 +00005072 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005073 goto open_finished;
danielk1977fee2d252007-08-18 10:59:19 +00005074 }
5075 }
danielk1977e339d652008-06-28 11:23:00 +00005076
5077#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005078 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005079#endif
5080
drhda0e7682008-07-30 15:27:54 +00005081 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005082
drh7ed97b92010-01-20 13:07:21 +00005083
5084#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5085 struct statfs fsInfo;
5086 if( fstatfs(fd, &fsInfo) == -1 ){
5087 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005088 if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
5089 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005090 return SQLITE_IOERR_ACCESS;
5091 }
5092 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5093 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5094 }
5095#endif
5096
5097#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005098#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005099 isAutoProxy = 1;
5100#endif
5101 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005102 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5103 int useProxy = 0;
5104
dan08da86a2009-08-21 17:18:03 +00005105 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5106 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005107 if( envforce!=NULL ){
5108 useProxy = atoi(envforce)>0;
5109 }else{
5110 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005111 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005112 /* In theory, the close(fd) call is sub-optimal. If the file opened
5113 ** with fd is a database file, and there are other connections open
5114 ** on that file that are currently holding advisory locks on it,
5115 ** then the call to close() will cancel those locks. In practice,
5116 ** we're assuming that statfs() doesn't fail very often. At least
5117 ** not while other file descriptors opened by the same process on
5118 ** the same file are working. */
5119 p->lastErrno = errno;
5120 if( dirfd>=0 ){
drh0e9365c2011-03-02 02:08:13 +00005121 robust_close(p, dirfd, __LINE__);
dane946c392009-08-22 11:39:46 +00005122 }
drh0e9365c2011-03-02 02:08:13 +00005123 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005124 rc = SQLITE_IOERR_ACCESS;
5125 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005126 }
5127 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5128 }
5129 if( useProxy ){
drh77197112011-03-15 19:08:48 +00005130 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5131 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005132 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005133 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005134 if( rc!=SQLITE_OK ){
5135 /* Use unixClose to clean up the resources added in fillInUnixFile
5136 ** and clear all the structure's references. Specifically,
5137 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5138 */
5139 unixClose(pFile);
5140 return rc;
5141 }
aswiftaebf4132008-11-21 00:10:35 +00005142 }
dane946c392009-08-22 11:39:46 +00005143 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005144 }
5145 }
5146#endif
5147
drh77197112011-03-15 19:08:48 +00005148 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
5149 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005150open_finished:
5151 if( rc!=SQLITE_OK ){
5152 sqlite3_free(p->pUnused);
5153 }
5154 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005155}
5156
dane946c392009-08-22 11:39:46 +00005157
danielk1977b4b47412007-08-17 15:53:36 +00005158/*
danielk1977fee2d252007-08-18 10:59:19 +00005159** Delete the file at zPath. If the dirSync argument is true, fsync()
5160** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005161*/
drh6b9d6dd2008-12-03 19:34:47 +00005162static int unixDelete(
5163 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5164 const char *zPath, /* Name of file to be deleted */
5165 int dirSync /* If true, fsync() directory after deleting file */
5166){
danielk1977fee2d252007-08-18 10:59:19 +00005167 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005168 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005169 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005170 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005171 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005172 }
danielk1977d39fa702008-10-16 13:27:40 +00005173#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005174 if( dirSync ){
5175 int fd;
5176 rc = openDirectory(zPath, &fd);
5177 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005178#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005179 if( fsync(fd)==-1 )
5180#else
5181 if( fsync(fd) )
5182#endif
5183 {
dane18d4952011-02-21 11:46:24 +00005184 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005185 }
drh0e9365c2011-03-02 02:08:13 +00005186 robust_close(0, fd, __LINE__);
danielk1977fee2d252007-08-18 10:59:19 +00005187 }
5188 }
danielk1977d138dd82008-10-15 16:02:48 +00005189#endif
danielk1977fee2d252007-08-18 10:59:19 +00005190 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005191}
5192
danielk197790949c22007-08-17 16:50:38 +00005193/*
5194** Test the existance of or access permissions of file zPath. The
5195** test performed depends on the value of flags:
5196**
5197** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5198** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5199** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5200**
5201** Otherwise return 0.
5202*/
danielk1977861f7452008-06-05 11:39:11 +00005203static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005204 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5205 const char *zPath, /* Path of the file to examine */
5206 int flags, /* What do we want to learn about the zPath file? */
5207 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005208){
rse25c0d1a2007-09-20 08:38:14 +00005209 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005210 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005211 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005212 switch( flags ){
5213 case SQLITE_ACCESS_EXISTS:
5214 amode = F_OK;
5215 break;
5216 case SQLITE_ACCESS_READWRITE:
5217 amode = W_OK|R_OK;
5218 break;
drh50d3f902007-08-27 21:10:36 +00005219 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005220 amode = R_OK;
5221 break;
5222
5223 default:
5224 assert(!"Invalid flags argument");
5225 }
drh99ab3b12011-03-02 15:09:07 +00005226 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005227 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5228 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005229 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005230 *pResOut = 0;
5231 }
5232 }
danielk1977861f7452008-06-05 11:39:11 +00005233 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005234}
5235
danielk1977b4b47412007-08-17 15:53:36 +00005236
5237/*
5238** Turn a relative pathname into a full pathname. The relative path
5239** is stored as a nul-terminated string in the buffer pointed to by
5240** zPath.
5241**
5242** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5243** (in this case, MAX_PATHNAME bytes). The full-path is written to
5244** this buffer before returning.
5245*/
danielk1977adfb9b02007-09-17 07:02:56 +00005246static int unixFullPathname(
5247 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5248 const char *zPath, /* Possibly relative input path */
5249 int nOut, /* Size of output buffer in bytes */
5250 char *zOut /* Output buffer */
5251){
danielk1977843e65f2007-09-01 16:16:15 +00005252
5253 /* It's odd to simulate an io-error here, but really this is just
5254 ** using the io-error infrastructure to test that SQLite handles this
5255 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005256 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005257 */
5258 SimulateIOError( return SQLITE_ERROR );
5259
drh153c62c2007-08-24 03:51:33 +00005260 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005261 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005262
drh3c7f2dc2007-12-06 13:26:20 +00005263 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005264 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005265 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005266 }else{
5267 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005268 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005269 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005270 }
drhea678832008-12-10 19:26:22 +00005271 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005272 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005273 }
5274 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005275}
5276
drh0ccebe72005-06-07 22:22:50 +00005277
drh761df872006-12-21 01:29:22 +00005278#ifndef SQLITE_OMIT_LOAD_EXTENSION
5279/*
5280** Interfaces for opening a shared library, finding entry points
5281** within the shared library, and closing the shared library.
5282*/
5283#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005284static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5285 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005286 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5287}
danielk197795c8a542007-09-01 06:51:27 +00005288
5289/*
5290** SQLite calls this function immediately after a call to unixDlSym() or
5291** unixDlOpen() fails (returns a null pointer). If a more detailed error
5292** message is available, it is written to zBufOut. If no error message
5293** is available, zBufOut is left unmodified and SQLite uses a default
5294** error message.
5295*/
danielk1977397d65f2008-11-19 11:35:39 +00005296static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005297 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005298 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005299 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005300 zErr = dlerror();
5301 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005302 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005303 }
drh6c7d5c52008-11-21 20:32:33 +00005304 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005305}
drh1875f7a2008-12-08 18:19:17 +00005306static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5307 /*
5308 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5309 ** cast into a pointer to a function. And yet the library dlsym() routine
5310 ** returns a void* which is really a pointer to a function. So how do we
5311 ** use dlsym() with -pedantic-errors?
5312 **
5313 ** Variable x below is defined to be a pointer to a function taking
5314 ** parameters void* and const char* and returning a pointer to a function.
5315 ** We initialize x by assigning it a pointer to the dlsym() function.
5316 ** (That assignment requires a cast.) Then we call the function that
5317 ** x points to.
5318 **
5319 ** This work-around is unlikely to work correctly on any system where
5320 ** you really cannot cast a function pointer into void*. But then, on the
5321 ** other hand, dlsym() will not work on such a system either, so we have
5322 ** not really lost anything.
5323 */
5324 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005325 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005326 x = (void(*(*)(void*,const char*))(void))dlsym;
5327 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005328}
danielk1977397d65f2008-11-19 11:35:39 +00005329static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5330 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005331 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005332}
danielk1977b4b47412007-08-17 15:53:36 +00005333#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5334 #define unixDlOpen 0
5335 #define unixDlError 0
5336 #define unixDlSym 0
5337 #define unixDlClose 0
5338#endif
5339
5340/*
danielk197790949c22007-08-17 16:50:38 +00005341** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005342*/
danielk1977397d65f2008-11-19 11:35:39 +00005343static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5344 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005345 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005346
drhbbd42a62004-05-22 17:41:58 +00005347 /* We have to initialize zBuf to prevent valgrind from reporting
5348 ** errors. The reports issued by valgrind are incorrect - we would
5349 ** prefer that the randomness be increased by making use of the
5350 ** uninitialized space in zBuf - but valgrind errors tend to worry
5351 ** some users. Rather than argue, it seems easier just to initialize
5352 ** the whole array and silence valgrind, even if that means less randomness
5353 ** in the random seed.
5354 **
5355 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005356 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005357 ** tests repeatable.
5358 */
danielk1977b4b47412007-08-17 15:53:36 +00005359 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005360#if !defined(SQLITE_TEST)
5361 {
drh842b8642005-01-21 17:53:17 +00005362 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005363 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005364 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005365 time_t t;
5366 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005367 memcpy(zBuf, &t, sizeof(t));
5368 pid = getpid();
5369 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005370 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005371 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005372 }else{
drhe562be52011-03-02 18:01:10 +00005373 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005374 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005375 }
drhbbd42a62004-05-22 17:41:58 +00005376 }
5377#endif
drh72cbd072008-10-14 17:58:38 +00005378 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005379}
5380
danielk1977b4b47412007-08-17 15:53:36 +00005381
drhbbd42a62004-05-22 17:41:58 +00005382/*
5383** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005384** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005385** The return value is the number of microseconds of sleep actually
5386** requested from the underlying operating system, a number which
5387** might be greater than or equal to the argument, but not less
5388** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005389*/
danielk1977397d65f2008-11-19 11:35:39 +00005390static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005391#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005392 struct timespec sp;
5393
5394 sp.tv_sec = microseconds / 1000000;
5395 sp.tv_nsec = (microseconds % 1000000) * 1000;
5396 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005397 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005398 return microseconds;
5399#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005400 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005401 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005402 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005403#else
danielk1977b4b47412007-08-17 15:53:36 +00005404 int seconds = (microseconds+999999)/1000000;
5405 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005406 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005407 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005408#endif
drh88f474a2006-01-02 20:00:12 +00005409}
5410
5411/*
drh6b9d6dd2008-12-03 19:34:47 +00005412** The following variable, if set to a non-zero value, is interpreted as
5413** the number of seconds since 1970 and is used to set the result of
5414** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005415*/
5416#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005417int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005418#endif
5419
5420/*
drhb7e8ea22010-05-03 14:32:30 +00005421** Find the current time (in Universal Coordinated Time). Write into *piNow
5422** the current time and date as a Julian Day number times 86_400_000. In
5423** other words, write into *piNow the number of milliseconds since the Julian
5424** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5425** proleptic Gregorian calendar.
5426**
5427** On success, return 0. Return 1 if the time and date cannot be found.
5428*/
5429static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5430 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5431#if defined(NO_GETTOD)
5432 time_t t;
5433 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005434 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005435#elif OS_VXWORKS
5436 struct timespec sNow;
5437 clock_gettime(CLOCK_REALTIME, &sNow);
5438 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5439#else
5440 struct timeval sNow;
5441 gettimeofday(&sNow, 0);
5442 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5443#endif
5444
5445#ifdef SQLITE_TEST
5446 if( sqlite3_current_time ){
5447 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5448 }
5449#endif
5450 UNUSED_PARAMETER(NotUsed);
5451 return 0;
5452}
5453
5454/*
drhbbd42a62004-05-22 17:41:58 +00005455** Find the current time (in Universal Coordinated Time). Write the
5456** current time and date as a Julian Day number into *prNow and
5457** return 0. Return 1 if the time and date cannot be found.
5458*/
danielk1977397d65f2008-11-19 11:35:39 +00005459static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005460 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005461 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005462 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005463 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005464 return 0;
5465}
danielk1977b4b47412007-08-17 15:53:36 +00005466
drh6b9d6dd2008-12-03 19:34:47 +00005467/*
5468** We added the xGetLastError() method with the intention of providing
5469** better low-level error messages when operating-system problems come up
5470** during SQLite operation. But so far, none of that has been implemented
5471** in the core. So this routine is never called. For now, it is merely
5472** a place-holder.
5473*/
danielk1977397d65f2008-11-19 11:35:39 +00005474static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5475 UNUSED_PARAMETER(NotUsed);
5476 UNUSED_PARAMETER(NotUsed2);
5477 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005478 return 0;
5479}
5480
drhf2424c52010-04-26 00:04:55 +00005481
5482/*
drh734c9862008-11-28 15:37:20 +00005483************************ End of sqlite3_vfs methods ***************************
5484******************************************************************************/
5485
drh715ff302008-12-03 22:32:44 +00005486/******************************************************************************
5487************************** Begin Proxy Locking ********************************
5488**
5489** Proxy locking is a "uber-locking-method" in this sense: It uses the
5490** other locking methods on secondary lock files. Proxy locking is a
5491** meta-layer over top of the primitive locking implemented above. For
5492** this reason, the division that implements of proxy locking is deferred
5493** until late in the file (here) after all of the other I/O methods have
5494** been defined - so that the primitive locking methods are available
5495** as services to help with the implementation of proxy locking.
5496**
5497****
5498**
5499** The default locking schemes in SQLite use byte-range locks on the
5500** database file to coordinate safe, concurrent access by multiple readers
5501** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5502** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5503** as POSIX read & write locks over fixed set of locations (via fsctl),
5504** on AFP and SMB only exclusive byte-range locks are available via fsctl
5505** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5506** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5507** address in the shared range is taken for a SHARED lock, the entire
5508** shared range is taken for an EXCLUSIVE lock):
5509**
5510** PENDING_BYTE 0x40000000
5511** RESERVED_BYTE 0x40000001
5512** SHARED_RANGE 0x40000002 -> 0x40000200
5513**
5514** This works well on the local file system, but shows a nearly 100x
5515** slowdown in read performance on AFP because the AFP client disables
5516** the read cache when byte-range locks are present. Enabling the read
5517** cache exposes a cache coherency problem that is present on all OS X
5518** supported network file systems. NFS and AFP both observe the
5519** close-to-open semantics for ensuring cache coherency
5520** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5521** address the requirements for concurrent database access by multiple
5522** readers and writers
5523** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5524**
5525** To address the performance and cache coherency issues, proxy file locking
5526** changes the way database access is controlled by limiting access to a
5527** single host at a time and moving file locks off of the database file
5528** and onto a proxy file on the local file system.
5529**
5530**
5531** Using proxy locks
5532** -----------------
5533**
5534** C APIs
5535**
5536** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5537** <proxy_path> | ":auto:");
5538** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5539**
5540**
5541** SQL pragmas
5542**
5543** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5544** PRAGMA [database.]lock_proxy_file
5545**
5546** Specifying ":auto:" means that if there is a conch file with a matching
5547** host ID in it, the proxy path in the conch file will be used, otherwise
5548** a proxy path based on the user's temp dir
5549** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5550** actual proxy file name is generated from the name and path of the
5551** database file. For example:
5552**
5553** For database path "/Users/me/foo.db"
5554** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5555**
5556** Once a lock proxy is configured for a database connection, it can not
5557** be removed, however it may be switched to a different proxy path via
5558** the above APIs (assuming the conch file is not being held by another
5559** connection or process).
5560**
5561**
5562** How proxy locking works
5563** -----------------------
5564**
5565** Proxy file locking relies primarily on two new supporting files:
5566**
5567** * conch file to limit access to the database file to a single host
5568** at a time
5569**
5570** * proxy file to act as a proxy for the advisory locks normally
5571** taken on the database
5572**
5573** The conch file - to use a proxy file, sqlite must first "hold the conch"
5574** by taking an sqlite-style shared lock on the conch file, reading the
5575** contents and comparing the host's unique host ID (see below) and lock
5576** proxy path against the values stored in the conch. The conch file is
5577** stored in the same directory as the database file and the file name
5578** is patterned after the database file name as ".<databasename>-conch".
5579** If the conch file does not exist, or it's contents do not match the
5580** host ID and/or proxy path, then the lock is escalated to an exclusive
5581** lock and the conch file contents is updated with the host ID and proxy
5582** path and the lock is downgraded to a shared lock again. If the conch
5583** is held by another process (with a shared lock), the exclusive lock
5584** will fail and SQLITE_BUSY is returned.
5585**
5586** The proxy file - a single-byte file used for all advisory file locks
5587** normally taken on the database file. This allows for safe sharing
5588** of the database file for multiple readers and writers on the same
5589** host (the conch ensures that they all use the same local lock file).
5590**
drh715ff302008-12-03 22:32:44 +00005591** Requesting the lock proxy does not immediately take the conch, it is
5592** only taken when the first request to lock database file is made.
5593** This matches the semantics of the traditional locking behavior, where
5594** opening a connection to a database file does not take a lock on it.
5595** The shared lock and an open file descriptor are maintained until
5596** the connection to the database is closed.
5597**
5598** The proxy file and the lock file are never deleted so they only need
5599** to be created the first time they are used.
5600**
5601** Configuration options
5602** ---------------------
5603**
5604** SQLITE_PREFER_PROXY_LOCKING
5605**
5606** Database files accessed on non-local file systems are
5607** automatically configured for proxy locking, lock files are
5608** named automatically using the same logic as
5609** PRAGMA lock_proxy_file=":auto:"
5610**
5611** SQLITE_PROXY_DEBUG
5612**
5613** Enables the logging of error messages during host id file
5614** retrieval and creation
5615**
drh715ff302008-12-03 22:32:44 +00005616** LOCKPROXYDIR
5617**
5618** Overrides the default directory used for lock proxy files that
5619** are named automatically via the ":auto:" setting
5620**
5621** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5622**
5623** Permissions to use when creating a directory for storing the
5624** lock proxy files, only used when LOCKPROXYDIR is not set.
5625**
5626**
5627** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5628** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5629** force proxy locking to be used for every database file opened, and 0
5630** will force automatic proxy locking to be disabled for all database
5631** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5632** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5633*/
5634
5635/*
5636** Proxy locking is only available on MacOSX
5637*/
drhd2cb50b2009-01-09 21:41:17 +00005638#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005639
drh715ff302008-12-03 22:32:44 +00005640/*
5641** The proxyLockingContext has the path and file structures for the remote
5642** and local proxy files in it
5643*/
5644typedef struct proxyLockingContext proxyLockingContext;
5645struct proxyLockingContext {
5646 unixFile *conchFile; /* Open conch file */
5647 char *conchFilePath; /* Name of the conch file */
5648 unixFile *lockProxy; /* Open proxy lock file */
5649 char *lockProxyPath; /* Name of the proxy lock file */
5650 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005651 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005652 void *oldLockingContext; /* Original lockingcontext to restore on close */
5653 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5654};
5655
drh7ed97b92010-01-20 13:07:21 +00005656/*
5657** The proxy lock file path for the database at dbPath is written into lPath,
5658** which must point to valid, writable memory large enough for a maxLen length
5659** file path.
drh715ff302008-12-03 22:32:44 +00005660*/
drh715ff302008-12-03 22:32:44 +00005661static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5662 int len;
5663 int dbLen;
5664 int i;
5665
5666#ifdef LOCKPROXYDIR
5667 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5668#else
5669# ifdef _CS_DARWIN_USER_TEMP_DIR
5670 {
drh7ed97b92010-01-20 13:07:21 +00005671 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005672 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5673 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005674 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005675 }
drh7ed97b92010-01-20 13:07:21 +00005676 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005677 }
5678# else
5679 len = strlcpy(lPath, "/tmp/", maxLen);
5680# endif
5681#endif
5682
5683 if( lPath[len-1]!='/' ){
5684 len = strlcat(lPath, "/", maxLen);
5685 }
5686
5687 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005688 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005689 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005690 char c = dbPath[i];
5691 lPath[i+len] = (c=='/')?'_':c;
5692 }
5693 lPath[i+len]='\0';
5694 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005695 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005696 return SQLITE_OK;
5697}
5698
drh7ed97b92010-01-20 13:07:21 +00005699/*
5700 ** Creates the lock file and any missing directories in lockPath
5701 */
5702static int proxyCreateLockPath(const char *lockPath){
5703 int i, len;
5704 char buf[MAXPATHLEN];
5705 int start = 0;
5706
5707 assert(lockPath!=NULL);
5708 /* try to create all the intermediate directories */
5709 len = (int)strlen(lockPath);
5710 buf[0] = lockPath[0];
5711 for( i=1; i<len; i++ ){
5712 if( lockPath[i] == '/' && (i - start > 0) ){
5713 /* only mkdir if leaf dir != "." or "/" or ".." */
5714 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5715 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5716 buf[i]='\0';
5717 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5718 int err=errno;
5719 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005720 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005721 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005722 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005723 return err;
5724 }
5725 }
5726 }
5727 start=i+1;
5728 }
5729 buf[i] = lockPath[i];
5730 }
drh308c2a52010-05-14 11:30:18 +00005731 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005732 return 0;
5733}
5734
drh715ff302008-12-03 22:32:44 +00005735/*
5736** Create a new VFS file descriptor (stored in memory obtained from
5737** sqlite3_malloc) and open the file named "path" in the file descriptor.
5738**
5739** The caller is responsible not only for closing the file descriptor
5740** but also for freeing the memory associated with the file descriptor.
5741*/
drh7ed97b92010-01-20 13:07:21 +00005742static int proxyCreateUnixFile(
5743 const char *path, /* path for the new unixFile */
5744 unixFile **ppFile, /* unixFile created and returned by ref */
5745 int islockfile /* if non zero missing dirs will be created */
5746) {
5747 int fd = -1;
5748 int dirfd = -1;
drh715ff302008-12-03 22:32:44 +00005749 unixFile *pNew;
5750 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005751 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005752 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005753 int terrno = 0;
5754 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005755
drh7ed97b92010-01-20 13:07:21 +00005756 /* 1. first try to open/create the file
5757 ** 2. if that fails, and this is a lock file (not-conch), try creating
5758 ** the parent directories and then try again.
5759 ** 3. if that fails, try to open the file read-only
5760 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5761 */
5762 pUnused = findReusableFd(path, openFlags);
5763 if( pUnused ){
5764 fd = pUnused->fd;
5765 }else{
5766 pUnused = sqlite3_malloc(sizeof(*pUnused));
5767 if( !pUnused ){
5768 return SQLITE_NOMEM;
5769 }
5770 }
5771 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005772 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005773 terrno = errno;
5774 if( fd<0 && errno==ENOENT && islockfile ){
5775 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005776 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005777 }
5778 }
5779 }
5780 if( fd<0 ){
5781 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005782 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005783 terrno = errno;
5784 }
5785 if( fd<0 ){
5786 if( islockfile ){
5787 return SQLITE_BUSY;
5788 }
5789 switch (terrno) {
5790 case EACCES:
5791 return SQLITE_PERM;
5792 case EIO:
5793 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5794 default:
drh9978c972010-02-23 17:36:32 +00005795 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005796 }
5797 }
5798
5799 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5800 if( pNew==NULL ){
5801 rc = SQLITE_NOMEM;
5802 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005803 }
5804 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005805 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005806 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005807 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005808 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005809 pUnused->fd = fd;
5810 pUnused->flags = openFlags;
5811 pNew->pUnused = pUnused;
5812
drh77197112011-03-15 19:08:48 +00005813 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005814 if( rc==SQLITE_OK ){
5815 *ppFile = pNew;
5816 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005817 }
drh7ed97b92010-01-20 13:07:21 +00005818end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005819 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005820 sqlite3_free(pNew);
5821 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005822 return rc;
5823}
5824
drh7ed97b92010-01-20 13:07:21 +00005825#ifdef SQLITE_TEST
5826/* simulate multiple hosts by creating unique hostid file paths */
5827int sqlite3_hostid_num = 0;
5828#endif
5829
5830#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5831
drh0ab216a2010-07-02 17:10:40 +00005832/* Not always defined in the headers as it ought to be */
5833extern int gethostuuid(uuid_t id, const struct timespec *wait);
5834
drh7ed97b92010-01-20 13:07:21 +00005835/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5836** bytes of writable memory.
5837*/
5838static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005839 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5840 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005841#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5842 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005843 {
5844 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5845 if( gethostuuid(pHostID, &timeout) ){
5846 int err = errno;
5847 if( pError ){
5848 *pError = err;
5849 }
5850 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005851 }
drh7ed97b92010-01-20 13:07:21 +00005852 }
drhe8b0c9b2010-09-25 14:13:17 +00005853#endif
drh7ed97b92010-01-20 13:07:21 +00005854#ifdef SQLITE_TEST
5855 /* simulate multiple hosts by creating unique hostid file paths */
5856 if( sqlite3_hostid_num != 0){
5857 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5858 }
5859#endif
5860
5861 return SQLITE_OK;
5862}
5863
5864/* The conch file contains the header, host id and lock file path
5865 */
5866#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5867#define PROXY_HEADERLEN 1 /* conch file header length */
5868#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5869#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5870
5871/*
5872** Takes an open conch file, copies the contents to a new path and then moves
5873** it back. The newly created file's file descriptor is assigned to the
5874** conch file structure and finally the original conch file descriptor is
5875** closed. Returns zero if successful.
5876*/
5877static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5878 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5879 unixFile *conchFile = pCtx->conchFile;
5880 char tPath[MAXPATHLEN];
5881 char buf[PROXY_MAXCONCHLEN];
5882 char *cPath = pCtx->conchFilePath;
5883 size_t readLen = 0;
5884 size_t pathLen = 0;
5885 char errmsg[64] = "";
5886 int fd = -1;
5887 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005888 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005889
5890 /* create a new path by replace the trailing '-conch' with '-break' */
5891 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5892 if( pathLen>MAXPATHLEN || pathLen<6 ||
5893 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005894 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005895 goto end_breaklock;
5896 }
5897 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005898 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005899 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005900 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005901 goto end_breaklock;
5902 }
5903 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005904 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5905 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005906 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005907 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005908 goto end_breaklock;
5909 }
drhe562be52011-03-02 18:01:10 +00005910 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005911 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005912 goto end_breaklock;
5913 }
5914 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005915 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005916 goto end_breaklock;
5917 }
5918 rc = 0;
5919 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005920 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005921 conchFile->h = fd;
5922 conchFile->openFlags = O_RDWR | O_CREAT;
5923
5924end_breaklock:
5925 if( rc ){
5926 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005927 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005928 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005929 }
5930 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5931 }
5932 return rc;
5933}
5934
5935/* Take the requested lock on the conch file and break a stale lock if the
5936** host id matches.
5937*/
5938static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5939 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5940 unixFile *conchFile = pCtx->conchFile;
5941 int rc = SQLITE_OK;
5942 int nTries = 0;
5943 struct timespec conchModTime;
5944
5945 do {
5946 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5947 nTries ++;
5948 if( rc==SQLITE_BUSY ){
5949 /* If the lock failed (busy):
5950 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5951 * 2nd try: fail if the mod time changed or host id is different, wait
5952 * 10 sec and try again
5953 * 3rd try: break the lock unless the mod time has changed.
5954 */
5955 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00005956 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00005957 pFile->lastErrno = errno;
5958 return SQLITE_IOERR_LOCK;
5959 }
5960
5961 if( nTries==1 ){
5962 conchModTime = buf.st_mtimespec;
5963 usleep(500000); /* wait 0.5 sec and try the lock again*/
5964 continue;
5965 }
5966
5967 assert( nTries>1 );
5968 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5969 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5970 return SQLITE_BUSY;
5971 }
5972
5973 if( nTries==2 ){
5974 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00005975 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005976 if( len<0 ){
5977 pFile->lastErrno = errno;
5978 return SQLITE_IOERR_LOCK;
5979 }
5980 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5981 /* don't break the lock if the host id doesn't match */
5982 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5983 return SQLITE_BUSY;
5984 }
5985 }else{
5986 /* don't break the lock on short read or a version mismatch */
5987 return SQLITE_BUSY;
5988 }
5989 usleep(10000000); /* wait 10 sec and try the lock again */
5990 continue;
5991 }
5992
5993 assert( nTries==3 );
5994 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5995 rc = SQLITE_OK;
5996 if( lockType==EXCLUSIVE_LOCK ){
5997 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5998 }
5999 if( !rc ){
6000 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6001 }
6002 }
6003 }
6004 } while( rc==SQLITE_BUSY && nTries<3 );
6005
6006 return rc;
6007}
6008
6009/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006010** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6011** lockPath means that the lockPath in the conch file will be used if the
6012** host IDs match, or a new lock path will be generated automatically
6013** and written to the conch file.
6014*/
6015static int proxyTakeConch(unixFile *pFile){
6016 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6017
drh7ed97b92010-01-20 13:07:21 +00006018 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006019 return SQLITE_OK;
6020 }else{
6021 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006022 uuid_t myHostID;
6023 int pError = 0;
6024 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006025 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006026 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006027 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006028 int createConch = 0;
6029 int hostIdMatch = 0;
6030 int readLen = 0;
6031 int tryOldLockPath = 0;
6032 int forceNewLockPath = 0;
6033
drh308c2a52010-05-14 11:30:18 +00006034 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6035 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006036
drh7ed97b92010-01-20 13:07:21 +00006037 rc = proxyGetHostID(myHostID, &pError);
6038 if( (rc&0xff)==SQLITE_IOERR ){
6039 pFile->lastErrno = pError;
6040 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006041 }
drh7ed97b92010-01-20 13:07:21 +00006042 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006043 if( rc!=SQLITE_OK ){
6044 goto end_takeconch;
6045 }
drh7ed97b92010-01-20 13:07:21 +00006046 /* read the existing conch file */
6047 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6048 if( readLen<0 ){
6049 /* I/O error: lastErrno set by seekAndRead */
6050 pFile->lastErrno = conchFile->lastErrno;
6051 rc = SQLITE_IOERR_READ;
6052 goto end_takeconch;
6053 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6054 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6055 /* a short read or version format mismatch means we need to create a new
6056 ** conch file.
6057 */
6058 createConch = 1;
6059 }
6060 /* if the host id matches and the lock path already exists in the conch
6061 ** we'll try to use the path there, if we can't open that path, we'll
6062 ** retry with a new auto-generated path
6063 */
6064 do { /* in case we need to try again for an :auto: named lock file */
6065
6066 if( !createConch && !forceNewLockPath ){
6067 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6068 PROXY_HOSTIDLEN);
6069 /* if the conch has data compare the contents */
6070 if( !pCtx->lockProxyPath ){
6071 /* for auto-named local lock file, just check the host ID and we'll
6072 ** use the local lock file path that's already in there
6073 */
6074 if( hostIdMatch ){
6075 size_t pathLen = (readLen - PROXY_PATHINDEX);
6076
6077 if( pathLen>=MAXPATHLEN ){
6078 pathLen=MAXPATHLEN-1;
6079 }
6080 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6081 lockPath[pathLen] = 0;
6082 tempLockPath = lockPath;
6083 tryOldLockPath = 1;
6084 /* create a copy of the lock path if the conch is taken */
6085 goto end_takeconch;
6086 }
6087 }else if( hostIdMatch
6088 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6089 readLen-PROXY_PATHINDEX)
6090 ){
6091 /* conch host and lock path match */
6092 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006093 }
drh7ed97b92010-01-20 13:07:21 +00006094 }
6095
6096 /* if the conch isn't writable and doesn't match, we can't take it */
6097 if( (conchFile->openFlags&O_RDWR) == 0 ){
6098 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006099 goto end_takeconch;
6100 }
drh7ed97b92010-01-20 13:07:21 +00006101
6102 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006103 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006104 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6105 tempLockPath = lockPath;
6106 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006107 }
drh7ed97b92010-01-20 13:07:21 +00006108
6109 /* update conch with host and path (this will fail if other process
6110 ** has a shared lock already), if the host id matches, use the big
6111 ** stick.
drh715ff302008-12-03 22:32:44 +00006112 */
drh7ed97b92010-01-20 13:07:21 +00006113 futimes(conchFile->h, NULL);
6114 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006115 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006116 /* We are trying for an exclusive lock but another thread in this
6117 ** same process is still holding a shared lock. */
6118 rc = SQLITE_BUSY;
6119 } else {
6120 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006121 }
drh715ff302008-12-03 22:32:44 +00006122 }else{
drh7ed97b92010-01-20 13:07:21 +00006123 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006124 }
drh7ed97b92010-01-20 13:07:21 +00006125 if( rc==SQLITE_OK ){
6126 char writeBuffer[PROXY_MAXCONCHLEN];
6127 int writeSize = 0;
6128
6129 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6130 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6131 if( pCtx->lockProxyPath!=NULL ){
6132 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6133 }else{
6134 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6135 }
6136 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006137 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006138 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6139 fsync(conchFile->h);
6140 /* If we created a new conch file (not just updated the contents of a
6141 ** valid conch file), try to match the permissions of the database
6142 */
6143 if( rc==SQLITE_OK && createConch ){
6144 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006145 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006146 if( err==0 ){
6147 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6148 S_IROTH|S_IWOTH);
6149 /* try to match the database file R/W permissions, ignore failure */
6150#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006151 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006152#else
drhff812312011-02-23 13:33:46 +00006153 do{
drhe562be52011-03-02 18:01:10 +00006154 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006155 }while( rc==(-1) && errno==EINTR );
6156 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006157 int code = errno;
6158 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6159 cmode, code, strerror(code));
6160 } else {
6161 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6162 }
6163 }else{
6164 int code = errno;
6165 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6166 err, code, strerror(code));
6167#endif
6168 }
drh715ff302008-12-03 22:32:44 +00006169 }
6170 }
drh7ed97b92010-01-20 13:07:21 +00006171 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6172
6173 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006174 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006175 if( rc==SQLITE_OK && pFile->openFlags ){
6176 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006177 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006178 }
6179 pFile->h = -1;
drhad4f1e52011-03-04 15:43:57 +00006180 int fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006181 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006182 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006183 if( fd>=0 ){
6184 pFile->h = fd;
6185 }else{
drh9978c972010-02-23 17:36:32 +00006186 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006187 during locking */
6188 }
6189 }
6190 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6191 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6192 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6193 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6194 /* we couldn't create the proxy lock file with the old lock file path
6195 ** so try again via auto-naming
6196 */
6197 forceNewLockPath = 1;
6198 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006199 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006200 }
6201 }
6202 if( rc==SQLITE_OK ){
6203 /* Need to make a copy of path if we extracted the value
6204 ** from the conch file or the path was allocated on the stack
6205 */
6206 if( tempLockPath ){
6207 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6208 if( !pCtx->lockProxyPath ){
6209 rc = SQLITE_NOMEM;
6210 }
6211 }
6212 }
6213 if( rc==SQLITE_OK ){
6214 pCtx->conchHeld = 1;
6215
6216 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6217 afpLockingContext *afpCtx;
6218 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6219 afpCtx->dbPath = pCtx->lockProxyPath;
6220 }
6221 } else {
6222 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6223 }
drh308c2a52010-05-14 11:30:18 +00006224 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6225 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006226 return rc;
drh308c2a52010-05-14 11:30:18 +00006227 } while (1); /* in case we need to retry the :auto: lock file -
6228 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006229 }
6230}
6231
6232/*
6233** If pFile holds a lock on a conch file, then release that lock.
6234*/
6235static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006236 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006237 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6238 unixFile *conchFile; /* Name of the conch file */
6239
6240 pCtx = (proxyLockingContext *)pFile->lockingContext;
6241 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006242 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006243 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006244 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006245 if( pCtx->conchHeld>0 ){
6246 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6247 }
drh715ff302008-12-03 22:32:44 +00006248 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006249 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6250 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006251 return rc;
6252}
6253
6254/*
6255** Given the name of a database file, compute the name of its conch file.
6256** Store the conch filename in memory obtained from sqlite3_malloc().
6257** Make *pConchPath point to the new name. Return SQLITE_OK on success
6258** or SQLITE_NOMEM if unable to obtain memory.
6259**
6260** The caller is responsible for ensuring that the allocated memory
6261** space is eventually freed.
6262**
6263** *pConchPath is set to NULL if a memory allocation error occurs.
6264*/
6265static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6266 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006267 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006268 char *conchPath; /* buffer in which to construct conch name */
6269
6270 /* Allocate space for the conch filename and initialize the name to
6271 ** the name of the original database file. */
6272 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6273 if( conchPath==0 ){
6274 return SQLITE_NOMEM;
6275 }
6276 memcpy(conchPath, dbPath, len+1);
6277
6278 /* now insert a "." before the last / character */
6279 for( i=(len-1); i>=0; i-- ){
6280 if( conchPath[i]=='/' ){
6281 i++;
6282 break;
6283 }
6284 }
6285 conchPath[i]='.';
6286 while ( i<len ){
6287 conchPath[i+1]=dbPath[i];
6288 i++;
6289 }
6290
6291 /* append the "-conch" suffix to the file */
6292 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006293 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006294
6295 return SQLITE_OK;
6296}
6297
6298
6299/* Takes a fully configured proxy locking-style unix file and switches
6300** the local lock file path
6301*/
6302static int switchLockProxyPath(unixFile *pFile, const char *path) {
6303 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6304 char *oldPath = pCtx->lockProxyPath;
6305 int rc = SQLITE_OK;
6306
drh308c2a52010-05-14 11:30:18 +00006307 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006308 return SQLITE_BUSY;
6309 }
6310
6311 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6312 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6313 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6314 return SQLITE_OK;
6315 }else{
6316 unixFile *lockProxy = pCtx->lockProxy;
6317 pCtx->lockProxy=NULL;
6318 pCtx->conchHeld = 0;
6319 if( lockProxy!=NULL ){
6320 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6321 if( rc ) return rc;
6322 sqlite3_free(lockProxy);
6323 }
6324 sqlite3_free(oldPath);
6325 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6326 }
6327
6328 return rc;
6329}
6330
6331/*
6332** pFile is a file that has been opened by a prior xOpen call. dbPath
6333** is a string buffer at least MAXPATHLEN+1 characters in size.
6334**
6335** This routine find the filename associated with pFile and writes it
6336** int dbPath.
6337*/
6338static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006339#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006340 if( pFile->pMethod == &afpIoMethods ){
6341 /* afp style keeps a reference to the db path in the filePath field
6342 ** of the struct */
drhea678832008-12-10 19:26:22 +00006343 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006344 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6345 } else
drh715ff302008-12-03 22:32:44 +00006346#endif
6347 if( pFile->pMethod == &dotlockIoMethods ){
6348 /* dot lock style uses the locking context to store the dot lock
6349 ** file path */
6350 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6351 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6352 }else{
6353 /* all other styles use the locking context to store the db file path */
6354 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006355 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006356 }
6357 return SQLITE_OK;
6358}
6359
6360/*
6361** Takes an already filled in unix file and alters it so all file locking
6362** will be performed on the local proxy lock file. The following fields
6363** are preserved in the locking context so that they can be restored and
6364** the unix structure properly cleaned up at close time:
6365** ->lockingContext
6366** ->pMethod
6367*/
6368static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6369 proxyLockingContext *pCtx;
6370 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6371 char *lockPath=NULL;
6372 int rc = SQLITE_OK;
6373
drh308c2a52010-05-14 11:30:18 +00006374 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006375 return SQLITE_BUSY;
6376 }
6377 proxyGetDbPathForUnixFile(pFile, dbPath);
6378 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6379 lockPath=NULL;
6380 }else{
6381 lockPath=(char *)path;
6382 }
6383
drh308c2a52010-05-14 11:30:18 +00006384 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6385 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006386
6387 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6388 if( pCtx==0 ){
6389 return SQLITE_NOMEM;
6390 }
6391 memset(pCtx, 0, sizeof(*pCtx));
6392
6393 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6394 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006395 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6396 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6397 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6398 ** (c) the file system is read-only, then enable no-locking access.
6399 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6400 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6401 */
6402 struct statfs fsInfo;
6403 struct stat conchInfo;
6404 int goLockless = 0;
6405
drh99ab3b12011-03-02 15:09:07 +00006406 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006407 int err = errno;
6408 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6409 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6410 }
6411 }
6412 if( goLockless ){
6413 pCtx->conchHeld = -1; /* read only FS/ lockless */
6414 rc = SQLITE_OK;
6415 }
6416 }
drh715ff302008-12-03 22:32:44 +00006417 }
6418 if( rc==SQLITE_OK && lockPath ){
6419 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6420 }
6421
6422 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006423 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6424 if( pCtx->dbPath==NULL ){
6425 rc = SQLITE_NOMEM;
6426 }
6427 }
6428 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006429 /* all memory is allocated, proxys are created and assigned,
6430 ** switch the locking context and pMethod then return.
6431 */
drh715ff302008-12-03 22:32:44 +00006432 pCtx->oldLockingContext = pFile->lockingContext;
6433 pFile->lockingContext = pCtx;
6434 pCtx->pOldMethod = pFile->pMethod;
6435 pFile->pMethod = &proxyIoMethods;
6436 }else{
6437 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006438 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006439 sqlite3_free(pCtx->conchFile);
6440 }
drhd56b1212010-08-11 06:14:15 +00006441 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006442 sqlite3_free(pCtx->conchFilePath);
6443 sqlite3_free(pCtx);
6444 }
drh308c2a52010-05-14 11:30:18 +00006445 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6446 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006447 return rc;
6448}
6449
6450
6451/*
6452** This routine handles sqlite3_file_control() calls that are specific
6453** to proxy locking.
6454*/
6455static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6456 switch( op ){
6457 case SQLITE_GET_LOCKPROXYFILE: {
6458 unixFile *pFile = (unixFile*)id;
6459 if( pFile->pMethod == &proxyIoMethods ){
6460 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6461 proxyTakeConch(pFile);
6462 if( pCtx->lockProxyPath ){
6463 *(const char **)pArg = pCtx->lockProxyPath;
6464 }else{
6465 *(const char **)pArg = ":auto: (not held)";
6466 }
6467 } else {
6468 *(const char **)pArg = NULL;
6469 }
6470 return SQLITE_OK;
6471 }
6472 case SQLITE_SET_LOCKPROXYFILE: {
6473 unixFile *pFile = (unixFile*)id;
6474 int rc = SQLITE_OK;
6475 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6476 if( pArg==NULL || (const char *)pArg==0 ){
6477 if( isProxyStyle ){
6478 /* turn off proxy locking - not supported */
6479 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6480 }else{
6481 /* turn off proxy locking - already off - NOOP */
6482 rc = SQLITE_OK;
6483 }
6484 }else{
6485 const char *proxyPath = (const char *)pArg;
6486 if( isProxyStyle ){
6487 proxyLockingContext *pCtx =
6488 (proxyLockingContext*)pFile->lockingContext;
6489 if( !strcmp(pArg, ":auto:")
6490 || (pCtx->lockProxyPath &&
6491 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6492 ){
6493 rc = SQLITE_OK;
6494 }else{
6495 rc = switchLockProxyPath(pFile, proxyPath);
6496 }
6497 }else{
6498 /* turn on proxy file locking */
6499 rc = proxyTransformUnixFile(pFile, proxyPath);
6500 }
6501 }
6502 return rc;
6503 }
6504 default: {
6505 assert( 0 ); /* The call assures that only valid opcodes are sent */
6506 }
6507 }
6508 /*NOTREACHED*/
6509 return SQLITE_ERROR;
6510}
6511
6512/*
6513** Within this division (the proxying locking implementation) the procedures
6514** above this point are all utilities. The lock-related methods of the
6515** proxy-locking sqlite3_io_method object follow.
6516*/
6517
6518
6519/*
6520** This routine checks if there is a RESERVED lock held on the specified
6521** file by this or any other process. If such a lock is held, set *pResOut
6522** to a non-zero value otherwise *pResOut is set to zero. The return value
6523** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6524*/
6525static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6526 unixFile *pFile = (unixFile*)id;
6527 int rc = proxyTakeConch(pFile);
6528 if( rc==SQLITE_OK ){
6529 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006530 if( pCtx->conchHeld>0 ){
6531 unixFile *proxy = pCtx->lockProxy;
6532 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6533 }else{ /* conchHeld < 0 is lockless */
6534 pResOut=0;
6535 }
drh715ff302008-12-03 22:32:44 +00006536 }
6537 return rc;
6538}
6539
6540/*
drh308c2a52010-05-14 11:30:18 +00006541** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006542** of the following:
6543**
6544** (1) SHARED_LOCK
6545** (2) RESERVED_LOCK
6546** (3) PENDING_LOCK
6547** (4) EXCLUSIVE_LOCK
6548**
6549** Sometimes when requesting one lock state, additional lock states
6550** are inserted in between. The locking might fail on one of the later
6551** transitions leaving the lock state different from what it started but
6552** still short of its goal. The following chart shows the allowed
6553** transitions and the inserted intermediate states:
6554**
6555** UNLOCKED -> SHARED
6556** SHARED -> RESERVED
6557** SHARED -> (PENDING) -> EXCLUSIVE
6558** RESERVED -> (PENDING) -> EXCLUSIVE
6559** PENDING -> EXCLUSIVE
6560**
6561** This routine will only increase a lock. Use the sqlite3OsUnlock()
6562** routine to lower a locking level.
6563*/
drh308c2a52010-05-14 11:30:18 +00006564static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006565 unixFile *pFile = (unixFile*)id;
6566 int rc = proxyTakeConch(pFile);
6567 if( rc==SQLITE_OK ){
6568 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006569 if( pCtx->conchHeld>0 ){
6570 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006571 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6572 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006573 }else{
6574 /* conchHeld < 0 is lockless */
6575 }
drh715ff302008-12-03 22:32:44 +00006576 }
6577 return rc;
6578}
6579
6580
6581/*
drh308c2a52010-05-14 11:30:18 +00006582** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006583** must be either NO_LOCK or SHARED_LOCK.
6584**
6585** If the locking level of the file descriptor is already at or below
6586** the requested locking level, this routine is a no-op.
6587*/
drh308c2a52010-05-14 11:30:18 +00006588static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006589 unixFile *pFile = (unixFile*)id;
6590 int rc = proxyTakeConch(pFile);
6591 if( rc==SQLITE_OK ){
6592 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006593 if( pCtx->conchHeld>0 ){
6594 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006595 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6596 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006597 }else{
6598 /* conchHeld < 0 is lockless */
6599 }
drh715ff302008-12-03 22:32:44 +00006600 }
6601 return rc;
6602}
6603
6604/*
6605** Close a file that uses proxy locks.
6606*/
6607static int proxyClose(sqlite3_file *id) {
6608 if( id ){
6609 unixFile *pFile = (unixFile*)id;
6610 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6611 unixFile *lockProxy = pCtx->lockProxy;
6612 unixFile *conchFile = pCtx->conchFile;
6613 int rc = SQLITE_OK;
6614
6615 if( lockProxy ){
6616 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6617 if( rc ) return rc;
6618 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6619 if( rc ) return rc;
6620 sqlite3_free(lockProxy);
6621 pCtx->lockProxy = 0;
6622 }
6623 if( conchFile ){
6624 if( pCtx->conchHeld ){
6625 rc = proxyReleaseConch(pFile);
6626 if( rc ) return rc;
6627 }
6628 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6629 if( rc ) return rc;
6630 sqlite3_free(conchFile);
6631 }
drhd56b1212010-08-11 06:14:15 +00006632 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006633 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006634 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006635 /* restore the original locking context and pMethod then close it */
6636 pFile->lockingContext = pCtx->oldLockingContext;
6637 pFile->pMethod = pCtx->pOldMethod;
6638 sqlite3_free(pCtx);
6639 return pFile->pMethod->xClose(id);
6640 }
6641 return SQLITE_OK;
6642}
6643
6644
6645
drhd2cb50b2009-01-09 21:41:17 +00006646#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006647/*
6648** The proxy locking style is intended for use with AFP filesystems.
6649** And since AFP is only supported on MacOSX, the proxy locking is also
6650** restricted to MacOSX.
6651**
6652**
6653******************* End of the proxy lock implementation **********************
6654******************************************************************************/
6655
drh734c9862008-11-28 15:37:20 +00006656/*
danielk1977e339d652008-06-28 11:23:00 +00006657** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006658**
6659** This routine registers all VFS implementations for unix-like operating
6660** systems. This routine, and the sqlite3_os_end() routine that follows,
6661** should be the only routines in this file that are visible from other
6662** files.
drh6b9d6dd2008-12-03 19:34:47 +00006663**
6664** This routine is called once during SQLite initialization and by a
6665** single thread. The memory allocation and mutex subsystems have not
6666** necessarily been initialized when this routine is called, and so they
6667** should not be used.
drh153c62c2007-08-24 03:51:33 +00006668*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006669int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006670 /*
6671 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006672 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6673 ** to the "finder" function. (pAppData is a pointer to a pointer because
6674 ** silly C90 rules prohibit a void* from being cast to a function pointer
6675 ** and so we have to go through the intermediate pointer to avoid problems
6676 ** when compiling with -pedantic-errors on GCC.)
6677 **
6678 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006679 ** finder-function. The finder-function returns a pointer to the
6680 ** sqlite_io_methods object that implements the desired locking
6681 ** behaviors. See the division above that contains the IOMETHODS
6682 ** macro for addition information on finder-functions.
6683 **
6684 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6685 ** object. But the "autolockIoFinder" available on MacOSX does a little
6686 ** more than that; it looks at the filesystem type that hosts the
6687 ** database file and tries to choose an locking method appropriate for
6688 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006689 */
drh7708e972008-11-29 00:56:52 +00006690 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006691 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006692 sizeof(unixFile), /* szOsFile */ \
6693 MAX_PATHNAME, /* mxPathname */ \
6694 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006695 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006696 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006697 unixOpen, /* xOpen */ \
6698 unixDelete, /* xDelete */ \
6699 unixAccess, /* xAccess */ \
6700 unixFullPathname, /* xFullPathname */ \
6701 unixDlOpen, /* xDlOpen */ \
6702 unixDlError, /* xDlError */ \
6703 unixDlSym, /* xDlSym */ \
6704 unixDlClose, /* xDlClose */ \
6705 unixRandomness, /* xRandomness */ \
6706 unixSleep, /* xSleep */ \
6707 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006708 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006709 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006710 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006711 unixGetSystemCall, /* xGetSystemCall */ \
6712 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006713 }
6714
drh6b9d6dd2008-12-03 19:34:47 +00006715 /*
6716 ** All default VFSes for unix are contained in the following array.
6717 **
6718 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6719 ** by the SQLite core when the VFS is registered. So the following
6720 ** array cannot be const.
6721 */
danielk1977e339d652008-06-28 11:23:00 +00006722 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006723#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006724 UNIXVFS("unix", autolockIoFinder ),
6725#else
6726 UNIXVFS("unix", posixIoFinder ),
6727#endif
6728 UNIXVFS("unix-none", nolockIoFinder ),
6729 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006730 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006731#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006732 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006733#endif
6734#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006735 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006736#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006737 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006738#endif
chw78a13182009-04-07 05:35:03 +00006739#endif
drhd2cb50b2009-01-09 21:41:17 +00006740#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006741 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006742 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006743 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006744#endif
drh153c62c2007-08-24 03:51:33 +00006745 };
drh6b9d6dd2008-12-03 19:34:47 +00006746 unsigned int i; /* Loop counter */
6747
drh2aa5a002011-04-13 13:42:25 +00006748 /* Double-check that the aSyscall[] array has been constructed
6749 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh036ac7f2011-08-08 23:18:05 +00006750 assert( ArraySize(aSyscall)==17 );
drh2aa5a002011-04-13 13:42:25 +00006751
drh6b9d6dd2008-12-03 19:34:47 +00006752 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006753 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006754 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006755 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006756 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006757}
danielk1977e339d652008-06-28 11:23:00 +00006758
6759/*
drh6b9d6dd2008-12-03 19:34:47 +00006760** Shutdown the operating system interface.
6761**
6762** Some operating systems might need to do some cleanup in this routine,
6763** to release dynamically allocated objects. But not on unix.
6764** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006765*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006766int sqlite3_os_end(void){
6767 return SQLITE_OK;
6768}
drhdce8bdb2007-08-16 13:01:44 +00006769
danielk197729bafea2008-06-26 10:41:19 +00006770#endif /* SQLITE_OS_UNIX */