blob: a4193c948ff918e161a2f90772208dabf3a62d3e [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** These #defines should enable >2GB file support on Posix if the
88** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000089** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000090**
91** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
92** on the compiler command line. This is necessary if you are compiling
93** on a recent machine (ex: RedHat 7.2) but you want your code to work
94** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
95** without this option, LFS is enable. But LFS does not exist in the kernel
96** in RedHat 6.0, so the code won't work. Hence, for maximum binary
97** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +000098**
99** The previous paragraph was written in 2005. (This paragraph is written
100** on 2008-11-28.) These days, all Linux kernels support large files, so
101** you should probably leave LFS enabled. But some embedded platforms might
102** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000103*/
104#ifndef SQLITE_DISABLE_LFS
105# define _LARGE_FILE 1
106# ifndef _FILE_OFFSET_BITS
107# define _FILE_OFFSET_BITS 64
108# endif
109# define _LARGEFILE_SOURCE 1
110#endif
drhbbd42a62004-05-22 17:41:58 +0000111
drh9cbe6352005-11-29 03:13:21 +0000112/*
113** standard include files.
114*/
115#include <sys/types.h>
116#include <sys/stat.h>
117#include <fcntl.h>
118#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000119#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000120#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000121#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000122#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000123#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000124#endif
danielk1977e339d652008-06-28 11:23:00 +0000125
drh40bbb0a2008-09-23 10:23:26 +0000126#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000127# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000128# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000129# include <semaphore.h>
130# include <limits.h>
131# else
drh9b35ea62008-11-29 02:20:26 +0000132# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# endif
drhbfe66312006-10-03 17:40:40 +0000135#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000136
drhf8b4d8c2010-03-05 13:53:22 +0000137#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000138# include <sys/mount.h>
139#endif
140
drhdbe4b882011-06-20 18:00:17 +0000141#ifdef HAVE_UTIME
142# include <utime.h>
143#endif
144
drh9cbe6352005-11-29 03:13:21 +0000145/*
drh7ed97b92010-01-20 13:07:21 +0000146** Allowed values of unixFile.fsFlags
147*/
148#define SQLITE_FSFLAGS_IS_MSDOS 0x1
149
150/*
drhf1a221e2006-01-15 17:27:17 +0000151** If we are to be thread-safe, include the pthreads header and define
152** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000153*/
drhd677b3d2007-08-20 22:48:41 +0000154#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000155# include <pthread.h>
156# define SQLITE_UNIX_THREADS 1
157#endif
158
159/*
160** Default permissions when creating a new file
161*/
162#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
163# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
164#endif
165
danielk1977b4b47412007-08-17 15:53:36 +0000166/*
aswiftaebf4132008-11-21 00:10:35 +0000167 ** Default permissions when creating auto proxy dir
168 */
169#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
170# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
171#endif
172
173/*
danielk1977b4b47412007-08-17 15:53:36 +0000174** Maximum supported path-length.
175*/
176#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000177
drh734c9862008-11-28 15:37:20 +0000178/*
drh734c9862008-11-28 15:37:20 +0000179** Only set the lastErrno if the error code is a real error and not
180** a normal expected return code of SQLITE_BUSY or SQLITE_OK
181*/
182#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
183
drhd91c68f2010-05-14 14:52:25 +0000184/* Forward references */
185typedef struct unixShm unixShm; /* Connection shared memory */
186typedef struct unixShmNode unixShmNode; /* Shared memory instance */
187typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
188typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000189
190/*
dane946c392009-08-22 11:39:46 +0000191** Sometimes, after a file handle is closed by SQLite, the file descriptor
192** cannot be closed immediately. In these cases, instances of the following
193** structure are used to store the file descriptor while waiting for an
194** opportunity to either close or reuse it.
195*/
dane946c392009-08-22 11:39:46 +0000196struct UnixUnusedFd {
197 int fd; /* File descriptor to close */
198 int flags; /* Flags this file descriptor was opened with */
199 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
200};
201
202/*
drh9b35ea62008-11-29 02:20:26 +0000203** The unixFile structure is subclass of sqlite3_file specific to the unix
204** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000205*/
drh054889e2005-11-30 03:20:31 +0000206typedef struct unixFile unixFile;
207struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000208 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhd91c68f2010-05-14 14:52:25 +0000209 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000210 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000211 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000212 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000213 int lastErrno; /* The unix errno from last I/O error */
214 void *lockingContext; /* Locking style specific state */
215 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000216 const char *zPath; /* Name of the file */
217 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000218 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000219#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000220 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000221#endif
drh7ed97b92010-01-20 13:07:21 +0000222#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000223 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000224#endif
225#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000226 int isDelete; /* Delete on close if true */
227 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000228#endif
drh8f941bc2009-01-14 23:03:40 +0000229#ifndef NDEBUG
230 /* The next group of variables are used to track whether or not the
231 ** transaction counter in bytes 24-27 of database files are updated
232 ** whenever any part of the database changes. An assertion fault will
233 ** occur if a file is updated without also updating the transaction
234 ** counter. This test is made to avoid new problems similar to the
235 ** one described by ticket #3584.
236 */
237 unsigned char transCntrChng; /* True if the transaction counter changed */
238 unsigned char dbUpdate; /* True if any part of database file changed */
239 unsigned char inNormalWrite; /* True if in a normal write operation */
240#endif
danielk1977967a4a12007-08-20 14:23:44 +0000241#ifdef SQLITE_TEST
242 /* In test mode, increase the size of this structure a bit so that
243 ** it is larger than the struct CrashFile defined in test6.c.
244 */
245 char aPadding[32];
246#endif
drh9cbe6352005-11-29 03:13:21 +0000247};
248
drh0ccebe72005-06-07 22:22:50 +0000249/*
drha7e61d82011-03-12 17:02:57 +0000250** Allowed values for the unixFile.ctrlFlags bitmask:
251*/
drhf0b190d2011-07-26 16:03:07 +0000252#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
253#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
254#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
drh0059eae2011-08-08 23:48:40 +0000255#define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
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
drh90315a22011-08-10 01:52:12 +0000301/* Forward reference */
302static int openDirectory(const char*, int*);
303
drh9a3baf12011-04-25 18:01:27 +0000304/*
drh99ab3b12011-03-02 15:09:07 +0000305** Many system calls are accessed through pointer-to-functions so that
306** they may be overridden at runtime to facilitate fault injection during
307** testing and sandboxing. The following array holds the names and pointers
308** to all overrideable system calls.
309*/
310static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000311 const char *zName; /* Name of the sytem call */
312 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
313 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000314} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000315 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
316#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000317
drh58ad5802011-03-23 22:02:23 +0000318 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000319#define osClose ((int(*)(int))aSyscall[1].pCurrent)
320
drh58ad5802011-03-23 22:02:23 +0000321 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000322#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
323
drh58ad5802011-03-23 22:02:23 +0000324 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000325#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
326
drh58ad5802011-03-23 22:02:23 +0000327 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000328#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
329
330/*
331** The DJGPP compiler environment looks mostly like Unix, but it
332** lacks the fcntl() system call. So redefine fcntl() to be something
333** that always succeeds. This means that locking does not occur under
334** DJGPP. But it is DOS - what did you expect?
335*/
336#ifdef __DJGPP__
337 { "fstat", 0, 0 },
338#define osFstat(a,b,c) 0
339#else
drh58ad5802011-03-23 22:02:23 +0000340 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000341#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
342#endif
343
drh58ad5802011-03-23 22:02:23 +0000344 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000345#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
346
drh58ad5802011-03-23 22:02:23 +0000347 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000349
drh58ad5802011-03-23 22:02:23 +0000350 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000351#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
352
drhd4a80312011-04-15 14:33:20 +0000353#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000354 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000355#else
drh58ad5802011-03-23 22:02:23 +0000356 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000357#endif
358#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
359
360#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000361 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000362#else
drh58ad5802011-03-23 22:02:23 +0000363 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000364#endif
365#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000368#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
369
drhd4a80312011-04-15 14:33:20 +0000370#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000371 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000372#else
drh58ad5802011-03-23 22:02:23 +0000373 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000374#endif
375#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
376 aSyscall[12].pCurrent)
377
378#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000379 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000380#else
drh58ad5802011-03-23 22:02:23 +0000381 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000382#endif
383#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
384 aSyscall[13].pCurrent)
385
drha6c47492011-04-11 18:35:09 +0000386#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000387 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000388#else
389 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000390#endif
drh2aa5a002011-04-13 13:42:25 +0000391#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
393#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000394 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000395#else
drh58ad5802011-03-23 22:02:23 +0000396 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000397#endif
dan0fd7d862011-03-29 10:04:23 +0000398#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000399
drh036ac7f2011-08-08 23:18:05 +0000400 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
401#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
402
drh90315a22011-08-10 01:52:12 +0000403 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
404#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
405
drhe562be52011-03-02 18:01:10 +0000406}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000407
408/*
409** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000410** "unix" VFSes. Return SQLITE_OK opon successfully updating the
411** system call pointer, or SQLITE_NOTFOUND if there is no configurable
412** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000413*/
414static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000415 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
416 const char *zName, /* Name of system call to override */
417 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000418){
drh58ad5802011-03-23 22:02:23 +0000419 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000420 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000421
422 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000423 if( zName==0 ){
424 /* If no zName is given, restore all system calls to their default
425 ** settings and return NULL
426 */
dan51438a72011-04-02 17:00:47 +0000427 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000428 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
429 if( aSyscall[i].pDefault ){
430 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000431 }
432 }
433 }else{
434 /* If zName is specified, operate on only the one system call
435 ** specified.
436 */
437 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
438 if( strcmp(zName, aSyscall[i].zName)==0 ){
439 if( aSyscall[i].pDefault==0 ){
440 aSyscall[i].pDefault = aSyscall[i].pCurrent;
441 }
drh1df30962011-03-02 19:06:42 +0000442 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000443 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
444 aSyscall[i].pCurrent = pNewFunc;
445 break;
446 }
447 }
448 }
449 return rc;
450}
451
drh1df30962011-03-02 19:06:42 +0000452/*
453** Return the value of a system call. Return NULL if zName is not a
454** recognized system call name. NULL is also returned if the system call
455** is currently undefined.
456*/
drh58ad5802011-03-23 22:02:23 +0000457static sqlite3_syscall_ptr unixGetSystemCall(
458 sqlite3_vfs *pNotUsed,
459 const char *zName
460){
461 unsigned int i;
462
463 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000464 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
465 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
466 }
467 return 0;
468}
469
470/*
471** Return the name of the first system call after zName. If zName==NULL
472** then return the name of the first system call. Return NULL if zName
473** is the last system call or if zName is not the name of a valid
474** system call.
475*/
476static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000477 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000478
479 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000480 if( zName ){
481 for(i=0; i<ArraySize(aSyscall)-1; i++){
482 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000483 }
484 }
dan0fd7d862011-03-29 10:04:23 +0000485 for(i++; i<ArraySize(aSyscall); i++){
486 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000487 }
488 return 0;
489}
490
drhad4f1e52011-03-04 15:43:57 +0000491/*
492** Retry open() calls that fail due to EINTR
493*/
494static int robust_open(const char *z, int f, int m){
495 int rc;
496 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
497 return rc;
498}
danielk197713adf8a2004-06-03 16:08:41 +0000499
drh107886a2008-11-21 22:21:50 +0000500/*
dan9359c7b2009-08-21 08:29:10 +0000501** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000502** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000503** vxworksFileId objects used by this file, all of which may be
504** shared by multiple threads.
505**
506** Function unixMutexHeld() is used to assert() that the global mutex
507** is held when required. This function is only used as part of assert()
508** statements. e.g.
509**
510** unixEnterMutex()
511** assert( unixMutexHeld() );
512** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000513*/
514static void unixEnterMutex(void){
515 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
516}
517static void unixLeaveMutex(void){
518 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
519}
dan9359c7b2009-08-21 08:29:10 +0000520#ifdef SQLITE_DEBUG
521static int unixMutexHeld(void) {
522 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
523}
524#endif
drh107886a2008-11-21 22:21:50 +0000525
drh734c9862008-11-28 15:37:20 +0000526
527#ifdef SQLITE_DEBUG
528/*
529** Helper function for printing out trace information from debugging
530** binaries. This returns the string represetation of the supplied
531** integer lock-type.
532*/
drh308c2a52010-05-14 11:30:18 +0000533static const char *azFileLock(int eFileLock){
534 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000535 case NO_LOCK: return "NONE";
536 case SHARED_LOCK: return "SHARED";
537 case RESERVED_LOCK: return "RESERVED";
538 case PENDING_LOCK: return "PENDING";
539 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000540 }
541 return "ERROR";
542}
543#endif
544
545#ifdef SQLITE_LOCK_TRACE
546/*
547** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000548**
drh734c9862008-11-28 15:37:20 +0000549** This routine is used for troubleshooting locks on multithreaded
550** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
551** command-line option on the compiler. This code is normally
552** turned off.
553*/
554static int lockTrace(int fd, int op, struct flock *p){
555 char *zOpName, *zType;
556 int s;
557 int savedErrno;
558 if( op==F_GETLK ){
559 zOpName = "GETLK";
560 }else if( op==F_SETLK ){
561 zOpName = "SETLK";
562 }else{
drh99ab3b12011-03-02 15:09:07 +0000563 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000564 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
565 return s;
566 }
567 if( p->l_type==F_RDLCK ){
568 zType = "RDLCK";
569 }else if( p->l_type==F_WRLCK ){
570 zType = "WRLCK";
571 }else if( p->l_type==F_UNLCK ){
572 zType = "UNLCK";
573 }else{
574 assert( 0 );
575 }
576 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000577 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000578 savedErrno = errno;
579 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
580 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
581 (int)p->l_pid, s);
582 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
583 struct flock l2;
584 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000585 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000586 if( l2.l_type==F_RDLCK ){
587 zType = "RDLCK";
588 }else if( l2.l_type==F_WRLCK ){
589 zType = "WRLCK";
590 }else if( l2.l_type==F_UNLCK ){
591 zType = "UNLCK";
592 }else{
593 assert( 0 );
594 }
595 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
596 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
597 }
598 errno = savedErrno;
599 return s;
600}
drh99ab3b12011-03-02 15:09:07 +0000601#undef osFcntl
602#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000603#endif /* SQLITE_LOCK_TRACE */
604
drhff812312011-02-23 13:33:46 +0000605/*
606** Retry ftruncate() calls that fail due to EINTR
607*/
drhff812312011-02-23 13:33:46 +0000608static int robust_ftruncate(int h, sqlite3_int64 sz){
609 int rc;
drh99ab3b12011-03-02 15:09:07 +0000610 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000611 return rc;
612}
drh734c9862008-11-28 15:37:20 +0000613
614/*
615** This routine translates a standard POSIX errno code into something
616** useful to the clients of the sqlite3 functions. Specifically, it is
617** intended to translate a variety of "try again" errors into SQLITE_BUSY
618** and a variety of "please close the file descriptor NOW" errors into
619** SQLITE_IOERR
620**
621** Errors during initialization of locks, or file system support for locks,
622** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
623*/
624static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
625 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000626#if 0
627 /* At one point this code was not commented out. In theory, this branch
628 ** should never be hit, as this function should only be called after
629 ** a locking-related function (i.e. fcntl()) has returned non-zero with
630 ** the value of errno as the first argument. Since a system call has failed,
631 ** errno should be non-zero.
632 **
633 ** Despite this, if errno really is zero, we still don't want to return
634 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
635 ** propagated back to the caller. Commenting this branch out means errno==0
636 ** will be handled by the "default:" case below.
637 */
drh734c9862008-11-28 15:37:20 +0000638 case 0:
639 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000640#endif
641
drh734c9862008-11-28 15:37:20 +0000642 case EAGAIN:
643 case ETIMEDOUT:
644 case EBUSY:
645 case EINTR:
646 case ENOLCK:
647 /* random NFS retry error, unless during file system support
648 * introspection, in which it actually means what it says */
649 return SQLITE_BUSY;
650
651 case EACCES:
652 /* EACCES is like EAGAIN during locking operations, but not any other time*/
653 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
654 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
655 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
656 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
657 return SQLITE_BUSY;
658 }
659 /* else fall through */
660 case EPERM:
661 return SQLITE_PERM;
662
danea83bc62011-04-01 11:56:32 +0000663 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
664 ** this module never makes such a call. And the code in SQLite itself
665 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
666 ** this case is also commented out. If the system does set errno to EDEADLK,
667 ** the default SQLITE_IOERR_XXX code will be returned. */
668#if 0
drh734c9862008-11-28 15:37:20 +0000669 case EDEADLK:
670 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000671#endif
drh734c9862008-11-28 15:37:20 +0000672
673#if EOPNOTSUPP!=ENOTSUP
674 case EOPNOTSUPP:
675 /* something went terribly awry, unless during file system support
676 * introspection, in which it actually means what it says */
677#endif
678#ifdef ENOTSUP
679 case ENOTSUP:
680 /* invalid fd, unless during file system support introspection, in which
681 * it actually means what it says */
682#endif
683 case EIO:
684 case EBADF:
685 case EINVAL:
686 case ENOTCONN:
687 case ENODEV:
688 case ENXIO:
689 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000690#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000691 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000692#endif
drh734c9862008-11-28 15:37:20 +0000693 case ENOSYS:
694 /* these should force the client to close the file and reconnect */
695
696 default:
697 return sqliteIOErr;
698 }
699}
700
701
702
703/******************************************************************************
704****************** Begin Unique File ID Utility Used By VxWorks ***************
705**
706** On most versions of unix, we can get a unique ID for a file by concatenating
707** the device number and the inode number. But this does not work on VxWorks.
708** On VxWorks, a unique file id must be based on the canonical filename.
709**
710** A pointer to an instance of the following structure can be used as a
711** unique file ID in VxWorks. Each instance of this structure contains
712** a copy of the canonical filename. There is also a reference count.
713** The structure is reclaimed when the number of pointers to it drops to
714** zero.
715**
716** There are never very many files open at one time and lookups are not
717** a performance-critical path, so it is sufficient to put these
718** structures on a linked list.
719*/
720struct vxworksFileId {
721 struct vxworksFileId *pNext; /* Next in a list of them all */
722 int nRef; /* Number of references to this one */
723 int nName; /* Length of the zCanonicalName[] string */
724 char *zCanonicalName; /* Canonical filename */
725};
726
727#if OS_VXWORKS
728/*
drh9b35ea62008-11-29 02:20:26 +0000729** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000730** variable:
731*/
732static struct vxworksFileId *vxworksFileList = 0;
733
734/*
735** Simplify a filename into its canonical form
736** by making the following changes:
737**
738** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000739** * convert /./ into just /
740** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000741**
742** Changes are made in-place. Return the new name length.
743**
744** The original filename is in z[0..n-1]. Return the number of
745** characters in the simplified name.
746*/
747static int vxworksSimplifyName(char *z, int n){
748 int i, j;
749 while( n>1 && z[n-1]=='/' ){ n--; }
750 for(i=j=0; i<n; i++){
751 if( z[i]=='/' ){
752 if( z[i+1]=='/' ) continue;
753 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
754 i += 1;
755 continue;
756 }
757 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
758 while( j>0 && z[j-1]!='/' ){ j--; }
759 if( j>0 ){ j--; }
760 i += 2;
761 continue;
762 }
763 }
764 z[j++] = z[i];
765 }
766 z[j] = 0;
767 return j;
768}
769
770/*
771** Find a unique file ID for the given absolute pathname. Return
772** a pointer to the vxworksFileId object. This pointer is the unique
773** file ID.
774**
775** The nRef field of the vxworksFileId object is incremented before
776** the object is returned. A new vxworksFileId object is created
777** and added to the global list if necessary.
778**
779** If a memory allocation error occurs, return NULL.
780*/
781static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
782 struct vxworksFileId *pNew; /* search key and new file ID */
783 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
784 int n; /* Length of zAbsoluteName string */
785
786 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000787 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000788 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
789 if( pNew==0 ) return 0;
790 pNew->zCanonicalName = (char*)&pNew[1];
791 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
792 n = vxworksSimplifyName(pNew->zCanonicalName, n);
793
794 /* Search for an existing entry that matching the canonical name.
795 ** If found, increment the reference count and return a pointer to
796 ** the existing file ID.
797 */
798 unixEnterMutex();
799 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
800 if( pCandidate->nName==n
801 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
802 ){
803 sqlite3_free(pNew);
804 pCandidate->nRef++;
805 unixLeaveMutex();
806 return pCandidate;
807 }
808 }
809
810 /* No match was found. We will make a new file ID */
811 pNew->nRef = 1;
812 pNew->nName = n;
813 pNew->pNext = vxworksFileList;
814 vxworksFileList = pNew;
815 unixLeaveMutex();
816 return pNew;
817}
818
819/*
820** Decrement the reference count on a vxworksFileId object. Free
821** the object when the reference count reaches zero.
822*/
823static void vxworksReleaseFileId(struct vxworksFileId *pId){
824 unixEnterMutex();
825 assert( pId->nRef>0 );
826 pId->nRef--;
827 if( pId->nRef==0 ){
828 struct vxworksFileId **pp;
829 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
830 assert( *pp==pId );
831 *pp = pId->pNext;
832 sqlite3_free(pId);
833 }
834 unixLeaveMutex();
835}
836#endif /* OS_VXWORKS */
837/*************** End of Unique File ID Utility Used By VxWorks ****************
838******************************************************************************/
839
840
841/******************************************************************************
842*************************** Posix Advisory Locking ****************************
843**
drh9b35ea62008-11-29 02:20:26 +0000844** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000845** section 6.5.2.2 lines 483 through 490 specify that when a process
846** sets or clears a lock, that operation overrides any prior locks set
847** by the same process. It does not explicitly say so, but this implies
848** that it overrides locks set by the same process using a different
849** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000850**
851** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000852** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
853**
854** Suppose ./file1 and ./file2 are really the same file (because
855** one is a hard or symbolic link to the other) then if you set
856** an exclusive lock on fd1, then try to get an exclusive lock
857** on fd2, it works. I would have expected the second lock to
858** fail since there was already a lock on the file due to fd1.
859** But not so. Since both locks came from the same process, the
860** second overrides the first, even though they were on different
861** file descriptors opened on different file names.
862**
drh734c9862008-11-28 15:37:20 +0000863** This means that we cannot use POSIX locks to synchronize file access
864** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000865** to synchronize access for threads in separate processes, but not
866** threads within the same process.
867**
868** To work around the problem, SQLite has to manage file locks internally
869** on its own. Whenever a new database is opened, we have to find the
870** specific inode of the database file (the inode is determined by the
871** st_dev and st_ino fields of the stat structure that fstat() fills in)
872** and check for locks already existing on that inode. When locks are
873** created or removed, we have to look at our own internal record of the
874** locks to see if another thread has previously set a lock on that same
875** inode.
876**
drh9b35ea62008-11-29 02:20:26 +0000877** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
878** For VxWorks, we have to use the alternative unique ID system based on
879** canonical filename and implemented in the previous division.)
880**
danielk1977ad94b582007-08-20 06:44:22 +0000881** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000882** descriptor. It is now a structure that holds the integer file
883** descriptor and a pointer to a structure that describes the internal
884** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000885** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000886** point to the same locking structure. The locking structure keeps
887** a reference count (so we will know when to delete it) and a "cnt"
888** field that tells us its internal lock status. cnt==0 means the
889** file is unlocked. cnt==-1 means the file has an exclusive lock.
890** cnt>0 means there are cnt shared locks on the file.
891**
892** Any attempt to lock or unlock a file first checks the locking
893** structure. The fcntl() system call is only invoked to set a
894** POSIX lock if the internal lock structure transitions between
895** a locked and an unlocked state.
896**
drh734c9862008-11-28 15:37:20 +0000897** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000898**
899** If you close a file descriptor that points to a file that has locks,
900** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000901** released. To work around this problem, each unixInodeInfo object
902** maintains a count of the number of pending locks on tha inode.
903** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000904** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000905** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000906** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000907** be closed and that list is walked (and cleared) when the last lock
908** clears.
909**
drh9b35ea62008-11-29 02:20:26 +0000910** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000911**
drh9b35ea62008-11-29 02:20:26 +0000912** Many older versions of linux use the LinuxThreads library which is
913** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000914** A cannot be modified or overridden by a different thread B.
915** Only thread A can modify the lock. Locking behavior is correct
916** if the appliation uses the newer Native Posix Thread Library (NPTL)
917** on linux - with NPTL a lock created by thread A can override locks
918** in thread B. But there is no way to know at compile-time which
919** threading library is being used. So there is no way to know at
920** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000921** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000922** current process.
drh5fdae772004-06-29 03:29:00 +0000923**
drh8af6c222010-05-14 12:43:01 +0000924** SQLite used to support LinuxThreads. But support for LinuxThreads
925** was dropped beginning with version 3.7.0. SQLite will still work with
926** LinuxThreads provided that (1) there is no more than one connection
927** per database file in the same process and (2) database connections
928** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000929*/
930
931/*
932** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000933** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000934*/
935struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000936 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000937#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000938 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000939#else
drh107886a2008-11-21 22:21:50 +0000940 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000941#endif
942};
943
944/*
drhbbd42a62004-05-22 17:41:58 +0000945** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000946** inode. Or, on LinuxThreads, there is one of these structures for
947** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000948**
danielk1977ad94b582007-08-20 06:44:22 +0000949** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000950** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000951** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000952*/
drh8af6c222010-05-14 12:43:01 +0000953struct unixInodeInfo {
954 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000955 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000956 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
957 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000958 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000959 unixShmNode *pShmNode; /* Shared memory associated with this inode */
960 int nLock; /* Number of outstanding file locks */
961 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
962 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
963 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000964#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000965 unsigned long long sharedByte; /* for AFP simulated shared lock */
966#endif
drh6c7d5c52008-11-21 20:32:33 +0000967#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000968 sem_t *pSem; /* Named POSIX semaphore */
969 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000970#endif
drhbbd42a62004-05-22 17:41:58 +0000971};
972
drhda0e7682008-07-30 15:27:54 +0000973/*
drh8af6c222010-05-14 12:43:01 +0000974** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000975*/
drhd91c68f2010-05-14 14:52:25 +0000976static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000977
drh5fdae772004-06-29 03:29:00 +0000978/*
dane18d4952011-02-21 11:46:24 +0000979**
980** This function - unixLogError_x(), is only ever called via the macro
981** unixLogError().
982**
983** It is invoked after an error occurs in an OS function and errno has been
984** set. It logs a message using sqlite3_log() containing the current value of
985** errno and, if possible, the human-readable equivalent from strerror() or
986** strerror_r().
987**
988** The first argument passed to the macro should be the error code that
989** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
990** The two subsequent arguments should be the name of the OS function that
991** failed (e.g. "unlink", "open") and the the associated file-system path,
992** if any.
993*/
drh0e9365c2011-03-02 02:08:13 +0000994#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
995static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +0000996 int errcode, /* SQLite error code */
997 const char *zFunc, /* Name of OS function that failed */
998 const char *zPath, /* File path associated with error */
999 int iLine /* Source line number where error occurred */
1000){
1001 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001002 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001003
1004 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1005 ** the strerror() function to obtain the human-readable error message
1006 ** equivalent to errno. Otherwise, use strerror_r().
1007 */
1008#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1009 char aErr[80];
1010 memset(aErr, 0, sizeof(aErr));
1011 zErr = aErr;
1012
1013 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1014 ** assume that the system provides the the GNU version of strerror_r() that
1015 ** returns a pointer to a buffer containing the error message. That pointer
1016 ** may point to aErr[], or it may point to some static storage somewhere.
1017 ** Otherwise, assume that the system provides the POSIX version of
1018 ** strerror_r(), which always writes an error message into aErr[].
1019 **
1020 ** If the code incorrectly assumes that it is the POSIX version that is
1021 ** available, the error message will often be an empty string. Not a
1022 ** huge problem. Incorrectly concluding that the GNU version is available
1023 ** could lead to a segfault though.
1024 */
1025#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1026 zErr =
1027# endif
drh0e9365c2011-03-02 02:08:13 +00001028 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001029
1030#elif SQLITE_THREADSAFE
1031 /* This is a threadsafe build, but strerror_r() is not available. */
1032 zErr = "";
1033#else
1034 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001035 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001036#endif
1037
1038 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001039 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001040 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001041 "os_unix.c:%d: (%d) %s(%s) - %s",
1042 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001043 );
1044
1045 return errcode;
1046}
1047
drh0e9365c2011-03-02 02:08:13 +00001048/*
1049** Close a file descriptor.
1050**
1051** We assume that close() almost always works, since it is only in a
1052** very sick application or on a very sick platform that it might fail.
1053** If it does fail, simply leak the file descriptor, but do log the
1054** error.
1055**
1056** Note that it is not safe to retry close() after EINTR since the
1057** file descriptor might have already been reused by another thread.
1058** So we don't even try to recover from an EINTR. Just log the error
1059** and move on.
1060*/
1061static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001062 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001063 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1064 pFile ? pFile->zPath : 0, lineno);
1065 }
1066}
dane18d4952011-02-21 11:46:24 +00001067
1068/*
danb0ac3e32010-06-16 10:55:42 +00001069** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001070*/
drh0e9365c2011-03-02 02:08:13 +00001071static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001072 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001073 UnixUnusedFd *p;
1074 UnixUnusedFd *pNext;
1075 for(p=pInode->pUnused; p; p=pNext){
1076 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001077 robust_close(pFile, p->fd, __LINE__);
1078 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001079 }
drh0e9365c2011-03-02 02:08:13 +00001080 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001081}
1082
1083/*
drh8af6c222010-05-14 12:43:01 +00001084** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001085**
1086** The mutex entered using the unixEnterMutex() function must be held
1087** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001088*/
danb0ac3e32010-06-16 10:55:42 +00001089static void releaseInodeInfo(unixFile *pFile){
1090 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001091 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001092 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001093 pInode->nRef--;
1094 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001095 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001096 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001097 if( pInode->pPrev ){
1098 assert( pInode->pPrev->pNext==pInode );
1099 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001100 }else{
drh8af6c222010-05-14 12:43:01 +00001101 assert( inodeList==pInode );
1102 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001103 }
drh8af6c222010-05-14 12:43:01 +00001104 if( pInode->pNext ){
1105 assert( pInode->pNext->pPrev==pInode );
1106 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001107 }
drh8af6c222010-05-14 12:43:01 +00001108 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001109 }
drhbbd42a62004-05-22 17:41:58 +00001110 }
1111}
1112
1113/*
drh8af6c222010-05-14 12:43:01 +00001114** Given a file descriptor, locate the unixInodeInfo object that
1115** describes that file descriptor. Create a new one if necessary. The
1116** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001117**
dan9359c7b2009-08-21 08:29:10 +00001118** The mutex entered using the unixEnterMutex() function must be held
1119** when this function is called.
1120**
drh6c7d5c52008-11-21 20:32:33 +00001121** Return an appropriate error code.
1122*/
drh8af6c222010-05-14 12:43:01 +00001123static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001124 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001125 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001126){
1127 int rc; /* System call return code */
1128 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001129 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1130 struct stat statbuf; /* Low-level file information */
1131 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001132
dan9359c7b2009-08-21 08:29:10 +00001133 assert( unixMutexHeld() );
1134
drh6c7d5c52008-11-21 20:32:33 +00001135 /* Get low-level information about the file that we can used to
1136 ** create a unique name for the file.
1137 */
1138 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001139 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001140 if( rc!=0 ){
1141 pFile->lastErrno = errno;
1142#ifdef EOVERFLOW
1143 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1144#endif
1145 return SQLITE_IOERR;
1146 }
1147
drheb0d74f2009-02-03 15:27:02 +00001148#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001149 /* On OS X on an msdos filesystem, the inode number is reported
1150 ** incorrectly for zero-size files. See ticket #3260. To work
1151 ** around this problem (we consider it a bug in OS X, not SQLite)
1152 ** we always increase the file size to 1 by writing a single byte
1153 ** prior to accessing the inode number. The one byte written is
1154 ** an ASCII 'S' character which also happens to be the first byte
1155 ** in the header of every SQLite database. In this way, if there
1156 ** is a race condition such that another thread has already populated
1157 ** the first page of the database, no damage is done.
1158 */
drh7ed97b92010-01-20 13:07:21 +00001159 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001160 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001161 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001162 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001163 return SQLITE_IOERR;
1164 }
drh99ab3b12011-03-02 15:09:07 +00001165 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001166 if( rc!=0 ){
1167 pFile->lastErrno = errno;
1168 return SQLITE_IOERR;
1169 }
1170 }
drheb0d74f2009-02-03 15:27:02 +00001171#endif
drh6c7d5c52008-11-21 20:32:33 +00001172
drh8af6c222010-05-14 12:43:01 +00001173 memset(&fileId, 0, sizeof(fileId));
1174 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001175#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001176 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001177#else
drh8af6c222010-05-14 12:43:01 +00001178 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001179#endif
drh8af6c222010-05-14 12:43:01 +00001180 pInode = inodeList;
1181 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1182 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001183 }
drh8af6c222010-05-14 12:43:01 +00001184 if( pInode==0 ){
1185 pInode = sqlite3_malloc( sizeof(*pInode) );
1186 if( pInode==0 ){
1187 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001188 }
drh8af6c222010-05-14 12:43:01 +00001189 memset(pInode, 0, sizeof(*pInode));
1190 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1191 pInode->nRef = 1;
1192 pInode->pNext = inodeList;
1193 pInode->pPrev = 0;
1194 if( inodeList ) inodeList->pPrev = pInode;
1195 inodeList = pInode;
1196 }else{
1197 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001198 }
drh8af6c222010-05-14 12:43:01 +00001199 *ppInode = pInode;
1200 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001201}
drh6c7d5c52008-11-21 20:32:33 +00001202
aswift5b1a2562008-08-22 00:22:35 +00001203
1204/*
danielk197713adf8a2004-06-03 16:08:41 +00001205** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001206** file by this or any other process. If such a lock is held, set *pResOut
1207** to a non-zero value otherwise *pResOut is set to zero. The return value
1208** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001209*/
danielk1977861f7452008-06-05 11:39:11 +00001210static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001211 int rc = SQLITE_OK;
1212 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001213 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001214
danielk1977861f7452008-06-05 11:39:11 +00001215 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1216
drh054889e2005-11-30 03:20:31 +00001217 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001218 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001219
1220 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001221 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001222 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001223 }
1224
drh2ac3ee92004-06-07 16:27:46 +00001225 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001226 */
danielk197709480a92009-02-09 05:32:32 +00001227#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001228 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001229 struct flock lock;
1230 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001231 lock.l_start = RESERVED_BYTE;
1232 lock.l_len = 1;
1233 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001234 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1235 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1236 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001237 } else if( lock.l_type!=F_UNLCK ){
1238 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001239 }
1240 }
danielk197709480a92009-02-09 05:32:32 +00001241#endif
danielk197713adf8a2004-06-03 16:08:41 +00001242
drh6c7d5c52008-11-21 20:32:33 +00001243 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001244 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001245
aswift5b1a2562008-08-22 00:22:35 +00001246 *pResOut = reserved;
1247 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001248}
1249
1250/*
drha7e61d82011-03-12 17:02:57 +00001251** Attempt to set a system-lock on the file pFile. The lock is
1252** described by pLock.
1253**
drh77197112011-03-15 19:08:48 +00001254** If the pFile was opened read/write from unix-excl, then the only lock
1255** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001256** the first time any lock is attempted. All subsequent system locking
1257** operations become no-ops. Locking operations still happen internally,
1258** in order to coordinate access between separate database connections
1259** within this process, but all of that is handled in memory and the
1260** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001261**
1262** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1263** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1264** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001265**
1266** Zero is returned if the call completes successfully, or -1 if a call
1267** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001268*/
1269static int unixFileLock(unixFile *pFile, struct flock *pLock){
1270 int rc;
drh3cb93392011-03-12 18:10:44 +00001271 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001272 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001273 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001274 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1275 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1276 ){
drh3cb93392011-03-12 18:10:44 +00001277 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001278 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001279 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001280 lock.l_whence = SEEK_SET;
1281 lock.l_start = SHARED_FIRST;
1282 lock.l_len = SHARED_SIZE;
1283 lock.l_type = F_WRLCK;
1284 rc = osFcntl(pFile->h, F_SETLK, &lock);
1285 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001286 pInode->bProcessLock = 1;
1287 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001288 }else{
1289 rc = 0;
1290 }
1291 }else{
1292 rc = osFcntl(pFile->h, F_SETLK, pLock);
1293 }
1294 return rc;
1295}
1296
1297/*
drh308c2a52010-05-14 11:30:18 +00001298** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001299** of the following:
1300**
drh2ac3ee92004-06-07 16:27:46 +00001301** (1) SHARED_LOCK
1302** (2) RESERVED_LOCK
1303** (3) PENDING_LOCK
1304** (4) EXCLUSIVE_LOCK
1305**
drhb3e04342004-06-08 00:47:47 +00001306** Sometimes when requesting one lock state, additional lock states
1307** are inserted in between. The locking might fail on one of the later
1308** transitions leaving the lock state different from what it started but
1309** still short of its goal. The following chart shows the allowed
1310** transitions and the inserted intermediate states:
1311**
1312** UNLOCKED -> SHARED
1313** SHARED -> RESERVED
1314** SHARED -> (PENDING) -> EXCLUSIVE
1315** RESERVED -> (PENDING) -> EXCLUSIVE
1316** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001317**
drha6abd042004-06-09 17:37:22 +00001318** This routine will only increase a lock. Use the sqlite3OsUnlock()
1319** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001320*/
drh308c2a52010-05-14 11:30:18 +00001321static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001322 /* The following describes the implementation of the various locks and
1323 ** lock transitions in terms of the POSIX advisory shared and exclusive
1324 ** lock primitives (called read-locks and write-locks below, to avoid
1325 ** confusion with SQLite lock names). The algorithms are complicated
1326 ** slightly in order to be compatible with windows systems simultaneously
1327 ** accessing the same database file, in case that is ever required.
1328 **
1329 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1330 ** byte', each single bytes at well known offsets, and the 'shared byte
1331 ** range', a range of 510 bytes at a well known offset.
1332 **
1333 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1334 ** byte'. If this is successful, a random byte from the 'shared byte
1335 ** range' is read-locked and the lock on the 'pending byte' released.
1336 **
danielk197790ba3bd2004-06-25 08:32:25 +00001337 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1338 ** A RESERVED lock is implemented by grabbing a write-lock on the
1339 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001340 **
1341 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001342 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1343 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1344 ** obtained, but existing SHARED locks are allowed to persist. A process
1345 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1346 ** This property is used by the algorithm for rolling back a journal file
1347 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001348 **
danielk197790ba3bd2004-06-25 08:32:25 +00001349 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1350 ** implemented by obtaining a write-lock on the entire 'shared byte
1351 ** range'. Since all other locks require a read-lock on one of the bytes
1352 ** within this range, this ensures that no other locks are held on the
1353 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001354 **
1355 ** The reason a single byte cannot be used instead of the 'shared byte
1356 ** range' is that some versions of windows do not support read-locks. By
1357 ** locking a random byte from a range, concurrent SHARED locks may exist
1358 ** even if the locking primitive used is always a write-lock.
1359 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001360 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001361 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001362 unixInodeInfo *pInode = pFile->pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001363 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001364 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001365
drh054889e2005-11-30 03:20:31 +00001366 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001367 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1368 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00001369 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001370
1371 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001372 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001373 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001374 */
drh308c2a52010-05-14 11:30:18 +00001375 if( pFile->eFileLock>=eFileLock ){
1376 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1377 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001378 return SQLITE_OK;
1379 }
1380
drh0c2694b2009-09-03 16:23:44 +00001381 /* Make sure the locking sequence is correct.
1382 ** (1) We never move from unlocked to anything higher than shared lock.
1383 ** (2) SQLite never explicitly requests a pendig lock.
1384 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001385 */
drh308c2a52010-05-14 11:30:18 +00001386 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1387 assert( eFileLock!=PENDING_LOCK );
1388 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001389
drh8af6c222010-05-14 12:43:01 +00001390 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001391 */
drh6c7d5c52008-11-21 20:32:33 +00001392 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001393 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001394
danielk1977ad94b582007-08-20 06:44:22 +00001395 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001396 ** handle that precludes the requested lock, return BUSY.
1397 */
drh8af6c222010-05-14 12:43:01 +00001398 if( (pFile->eFileLock!=pInode->eFileLock &&
1399 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001400 ){
1401 rc = SQLITE_BUSY;
1402 goto end_lock;
1403 }
1404
1405 /* If a SHARED lock is requested, and some thread using this PID already
1406 ** has a SHARED or RESERVED lock, then increment reference counts and
1407 ** return SQLITE_OK.
1408 */
drh308c2a52010-05-14 11:30:18 +00001409 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001410 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001411 assert( eFileLock==SHARED_LOCK );
1412 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001413 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001414 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001415 pInode->nShared++;
1416 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001417 goto end_lock;
1418 }
1419
danielk19779a1d0ab2004-06-01 14:09:28 +00001420
drh3cde3bb2004-06-12 02:17:14 +00001421 /* A PENDING lock is needed before acquiring a SHARED lock and before
1422 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1423 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001424 */
drh0c2694b2009-09-03 16:23:44 +00001425 lock.l_len = 1L;
1426 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001427 if( eFileLock==SHARED_LOCK
1428 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001429 ){
drh308c2a52010-05-14 11:30:18 +00001430 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001431 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001432 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001433 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001434 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001435 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001436 pFile->lastErrno = tErrno;
1437 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001438 goto end_lock;
1439 }
drh3cde3bb2004-06-12 02:17:14 +00001440 }
1441
1442
1443 /* If control gets to this point, then actually go ahead and make
1444 ** operating system calls for the specified lock.
1445 */
drh308c2a52010-05-14 11:30:18 +00001446 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001447 assert( pInode->nShared==0 );
1448 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001449 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001450
drh2ac3ee92004-06-07 16:27:46 +00001451 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001452 lock.l_start = SHARED_FIRST;
1453 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001454 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001455 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001456 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001457 }
dan661d71a2011-03-30 19:08:03 +00001458
drh2ac3ee92004-06-07 16:27:46 +00001459 /* Drop the temporary PENDING lock */
1460 lock.l_start = PENDING_BYTE;
1461 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001462 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001463 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1464 /* This could happen with a network mount */
1465 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001466 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001467 }
dan661d71a2011-03-30 19:08:03 +00001468
1469 if( rc ){
1470 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001471 pFile->lastErrno = tErrno;
1472 }
dan661d71a2011-03-30 19:08:03 +00001473 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001474 }else{
drh308c2a52010-05-14 11:30:18 +00001475 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001476 pInode->nLock++;
1477 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001478 }
drh8af6c222010-05-14 12:43:01 +00001479 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001480 /* We are trying for an exclusive lock but another thread in this
1481 ** same process is still holding a shared lock. */
1482 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001483 }else{
drh3cde3bb2004-06-12 02:17:14 +00001484 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001485 ** assumed that there is a SHARED or greater lock on the file
1486 ** already.
1487 */
drh308c2a52010-05-14 11:30:18 +00001488 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001489 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001490
1491 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1492 if( eFileLock==RESERVED_LOCK ){
1493 lock.l_start = RESERVED_BYTE;
1494 lock.l_len = 1L;
1495 }else{
1496 lock.l_start = SHARED_FIRST;
1497 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 }
dan661d71a2011-03-30 19:08:03 +00001499
1500 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001501 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001502 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001503 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001504 pFile->lastErrno = tErrno;
1505 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001506 }
drhbbd42a62004-05-22 17:41:58 +00001507 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001508
drh8f941bc2009-01-14 23:03:40 +00001509
1510#ifndef NDEBUG
1511 /* Set up the transaction-counter change checking flags when
1512 ** transitioning from a SHARED to a RESERVED lock. The change
1513 ** from SHARED to RESERVED marks the beginning of a normal
1514 ** write operation (not a hot journal rollback).
1515 */
1516 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001517 && pFile->eFileLock<=SHARED_LOCK
1518 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001519 ){
1520 pFile->transCntrChng = 0;
1521 pFile->dbUpdate = 0;
1522 pFile->inNormalWrite = 1;
1523 }
1524#endif
1525
1526
danielk1977ecb2a962004-06-02 06:30:16 +00001527 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001528 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001529 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001530 }else if( eFileLock==EXCLUSIVE_LOCK ){
1531 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001532 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001533 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001534
1535end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001536 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001537 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1538 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001539 return rc;
1540}
1541
1542/*
dan08da86a2009-08-21 17:18:03 +00001543** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001544** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001545*/
1546static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001547 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001548 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001549 p->pNext = pInode->pUnused;
1550 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001551 pFile->h = -1;
1552 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001553}
1554
1555/*
drh308c2a52010-05-14 11:30:18 +00001556** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001557** must be either NO_LOCK or SHARED_LOCK.
1558**
1559** If the locking level of the file descriptor is already at or below
1560** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001561**
1562** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1563** the byte range is divided into 2 parts and the first part is unlocked then
1564** set to a read lock, then the other part is simply unlocked. This works
1565** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1566** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001567*/
drha7e61d82011-03-12 17:02:57 +00001568static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001569 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001570 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001571 struct flock lock;
1572 int rc = SQLITE_OK;
1573 int h;
drha6abd042004-06-09 17:37:22 +00001574
drh054889e2005-11-30 03:20:31 +00001575 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001576 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001577 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001578 getpid()));
drha6abd042004-06-09 17:37:22 +00001579
drh308c2a52010-05-14 11:30:18 +00001580 assert( eFileLock<=SHARED_LOCK );
1581 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001582 return SQLITE_OK;
1583 }
drh6c7d5c52008-11-21 20:32:33 +00001584 unixEnterMutex();
drh1aa5af12008-03-07 19:51:14 +00001585 h = pFile->h;
drh8af6c222010-05-14 12:43:01 +00001586 pInode = pFile->pInode;
1587 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001588 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001589 assert( pInode->eFileLock==pFile->eFileLock );
drh1aa5af12008-03-07 19:51:14 +00001590 SimulateIOErrorBenign(1);
1591 SimulateIOError( h=(-1) )
1592 SimulateIOErrorBenign(0);
drh8f941bc2009-01-14 23:03:40 +00001593
1594#ifndef NDEBUG
1595 /* When reducing a lock such that other processes can start
1596 ** reading the database file again, make sure that the
1597 ** transaction counter was updated if any part of the database
1598 ** file changed. If the transaction counter is not updated,
1599 ** other connections to the same file might not realize that
1600 ** the file has changed and hence might not know to flush their
1601 ** cache. The use of a stale cache can lead to database corruption.
1602 */
dan7c246102010-04-12 19:00:29 +00001603#if 0
drh8f941bc2009-01-14 23:03:40 +00001604 assert( pFile->inNormalWrite==0
1605 || pFile->dbUpdate==0
1606 || pFile->transCntrChng==1 );
dan7c246102010-04-12 19:00:29 +00001607#endif
drh8f941bc2009-01-14 23:03:40 +00001608 pFile->inNormalWrite = 0;
1609#endif
1610
drh7ed97b92010-01-20 13:07:21 +00001611 /* downgrading to a shared lock on NFS involves clearing the write lock
1612 ** before establishing the readlock - to avoid a race condition we downgrade
1613 ** the lock in 2 blocks, so that part of the range will be covered by a
1614 ** write lock until the rest is covered by a read lock:
1615 ** 1: [WWWWW]
1616 ** 2: [....W]
1617 ** 3: [RRRRW]
1618 ** 4: [RRRR.]
1619 */
drh308c2a52010-05-14 11:30:18 +00001620 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001621
1622#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001623 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001624 assert( handleNFSUnlock==0 );
1625#endif
1626#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001627 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001628 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001629 off_t divSize = SHARED_SIZE - 1;
1630
1631 lock.l_type = F_UNLCK;
1632 lock.l_whence = SEEK_SET;
1633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001635 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001636 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001637 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001638 if( IS_LOCK_ERROR(rc) ){
1639 pFile->lastErrno = tErrno;
1640 }
1641 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001642 }
drh7ed97b92010-01-20 13:07:21 +00001643 lock.l_type = F_RDLCK;
1644 lock.l_whence = SEEK_SET;
1645 lock.l_start = SHARED_FIRST;
1646 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001647 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001648 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001649 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1650 if( IS_LOCK_ERROR(rc) ){
1651 pFile->lastErrno = tErrno;
1652 }
1653 goto end_unlock;
1654 }
1655 lock.l_type = F_UNLCK;
1656 lock.l_whence = SEEK_SET;
1657 lock.l_start = SHARED_FIRST+divSize;
1658 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001659 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001660 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001661 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001662 if( IS_LOCK_ERROR(rc) ){
1663 pFile->lastErrno = tErrno;
1664 }
1665 goto end_unlock;
1666 }
drh30f776f2011-02-25 03:25:07 +00001667 }else
1668#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1669 {
drh7ed97b92010-01-20 13:07:21 +00001670 lock.l_type = F_RDLCK;
1671 lock.l_whence = SEEK_SET;
1672 lock.l_start = SHARED_FIRST;
1673 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001674 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001675 /* In theory, the call to unixFileLock() cannot fail because another
1676 ** process is holding an incompatible lock. If it does, this
1677 ** indicates that the other process is not following the locking
1678 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1679 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1680 ** an assert to fail). */
1681 rc = SQLITE_IOERR_RDLOCK;
1682 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001683 goto end_unlock;
1684 }
drh9c105bb2004-10-02 20:38:28 +00001685 }
1686 }
drhbbd42a62004-05-22 17:41:58 +00001687 lock.l_type = F_UNLCK;
1688 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001689 lock.l_start = PENDING_BYTE;
1690 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001691 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001692 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001693 }else{
danea83bc62011-04-01 11:56:32 +00001694 rc = SQLITE_IOERR_UNLOCK;
1695 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001696 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001697 }
drhbbd42a62004-05-22 17:41:58 +00001698 }
drh308c2a52010-05-14 11:30:18 +00001699 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001700 /* Decrement the shared lock counter. Release the lock using an
1701 ** OS call only when all threads in this same process have released
1702 ** the lock.
1703 */
drh8af6c222010-05-14 12:43:01 +00001704 pInode->nShared--;
1705 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001706 lock.l_type = F_UNLCK;
1707 lock.l_whence = SEEK_SET;
1708 lock.l_start = lock.l_len = 0L;
drh1aa5af12008-03-07 19:51:14 +00001709 SimulateIOErrorBenign(1);
1710 SimulateIOError( h=(-1) )
1711 SimulateIOErrorBenign(0);
dan661d71a2011-03-30 19:08:03 +00001712 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001713 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001714 }else{
danea83bc62011-04-01 11:56:32 +00001715 rc = SQLITE_IOERR_UNLOCK;
1716 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001717 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001718 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001719 }
drha6abd042004-06-09 17:37:22 +00001720 }
1721
drhbbd42a62004-05-22 17:41:58 +00001722 /* Decrement the count of locks against this same file. When the
1723 ** count reaches zero, close any other file descriptors whose close
1724 ** was deferred because of outstanding locks.
1725 */
drh8af6c222010-05-14 12:43:01 +00001726 pInode->nLock--;
1727 assert( pInode->nLock>=0 );
1728 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001729 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001730 }
1731 }
aswift5b1a2562008-08-22 00:22:35 +00001732
1733end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001735 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001736 return rc;
drhbbd42a62004-05-22 17:41:58 +00001737}
1738
1739/*
drh308c2a52010-05-14 11:30:18 +00001740** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001741** must be either NO_LOCK or SHARED_LOCK.
1742**
1743** If the locking level of the file descriptor is already at or below
1744** the requested locking level, this routine is a no-op.
1745*/
drh308c2a52010-05-14 11:30:18 +00001746static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001747 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001748}
1749
1750/*
danielk1977e339d652008-06-28 11:23:00 +00001751** This function performs the parts of the "close file" operation
1752** common to all locking schemes. It closes the directory and file
1753** handles, if they are valid, and sets all fields of the unixFile
1754** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001755**
1756** It is *not* necessary to hold the mutex when this routine is called,
1757** even on VxWorks. A mutex will be acquired on VxWorks by the
1758** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001759*/
1760static int closeUnixFile(sqlite3_file *id){
1761 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001762 if( pFile->h>=0 ){
1763 robust_close(pFile, pFile->h, __LINE__);
1764 pFile->h = -1;
1765 }
1766#if OS_VXWORKS
1767 if( pFile->pId ){
1768 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001769 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001770 }
1771 vxworksReleaseFileId(pFile->pId);
1772 pFile->pId = 0;
1773 }
1774#endif
1775 OSTRACE(("CLOSE %-3d\n", pFile->h));
1776 OpenCounter(-1);
1777 sqlite3_free(pFile->pUnused);
1778 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001779 return SQLITE_OK;
1780}
1781
1782/*
danielk1977e3026632004-06-22 11:29:02 +00001783** Close a file.
1784*/
danielk197762079062007-08-15 17:08:46 +00001785static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001786 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001787 unixFile *pFile = (unixFile *)id;
1788 unixUnlock(id, NO_LOCK);
1789 unixEnterMutex();
1790
1791 /* unixFile.pInode is always valid here. Otherwise, a different close
1792 ** routine (e.g. nolockClose()) would be called instead.
1793 */
1794 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1795 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1796 /* If there are outstanding locks, do not actually close the file just
1797 ** yet because that would clear those locks. Instead, add the file
1798 ** descriptor to pInode->pUnused list. It will be automatically closed
1799 ** when the last lock is cleared.
1800 */
1801 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001802 }
dan661d71a2011-03-30 19:08:03 +00001803 releaseInodeInfo(pFile);
1804 rc = closeUnixFile(id);
1805 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001806 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001807}
1808
drh734c9862008-11-28 15:37:20 +00001809/************** End of the posix advisory lock implementation *****************
1810******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001811
drh734c9862008-11-28 15:37:20 +00001812/******************************************************************************
1813****************************** No-op Locking **********************************
1814**
1815** Of the various locking implementations available, this is by far the
1816** simplest: locking is ignored. No attempt is made to lock the database
1817** file for reading or writing.
1818**
1819** This locking mode is appropriate for use on read-only databases
1820** (ex: databases that are burned into CD-ROM, for example.) It can
1821** also be used if the application employs some external mechanism to
1822** prevent simultaneous access of the same database by two or more
1823** database connections. But there is a serious risk of database
1824** corruption if this locking mode is used in situations where multiple
1825** database connections are accessing the same database file at the same
1826** time and one or more of those connections are writing.
1827*/
drhbfe66312006-10-03 17:40:40 +00001828
drh734c9862008-11-28 15:37:20 +00001829static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1830 UNUSED_PARAMETER(NotUsed);
1831 *pResOut = 0;
1832 return SQLITE_OK;
1833}
drh734c9862008-11-28 15:37:20 +00001834static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1835 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1836 return SQLITE_OK;
1837}
drh734c9862008-11-28 15:37:20 +00001838static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1839 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1840 return SQLITE_OK;
1841}
1842
1843/*
drh9b35ea62008-11-29 02:20:26 +00001844** Close the file.
drh734c9862008-11-28 15:37:20 +00001845*/
1846static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001847 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001848}
1849
1850/******************* End of the no-op lock implementation *********************
1851******************************************************************************/
1852
1853/******************************************************************************
1854************************* Begin dot-file Locking ******************************
1855**
drh0c2694b2009-09-03 16:23:44 +00001856** The dotfile locking implementation uses the existance of separate lock
drh734c9862008-11-28 15:37:20 +00001857** files in order to control access to the database. This works on just
1858** about every filesystem imaginable. But there are serious downsides:
1859**
1860** (1) There is zero concurrency. A single reader blocks all other
1861** connections from reading or writing the database.
1862**
1863** (2) An application crash or power loss can leave stale lock files
1864** sitting around that need to be cleared manually.
1865**
1866** Nevertheless, a dotlock is an appropriate locking mode for use if no
1867** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001868**
1869** Dotfile locking works by creating a file in the same directory as the
1870** database and with the same name but with a ".lock" extension added.
1871** The existance of a lock file implies an EXCLUSIVE lock. All other lock
1872** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001873*/
1874
1875/*
1876** The file suffix added to the data base filename in order to create the
1877** lock file.
1878*/
1879#define DOTLOCK_SUFFIX ".lock"
1880
drh7708e972008-11-29 00:56:52 +00001881/*
1882** This routine checks if there is a RESERVED lock held on the specified
1883** file by this or any other process. If such a lock is held, set *pResOut
1884** to a non-zero value otherwise *pResOut is set to zero. The return value
1885** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1886**
1887** In dotfile locking, either a lock exists or it does not. So in this
1888** variation of CheckReservedLock(), *pResOut is set to true if any lock
1889** is held on the file and false if the file is unlocked.
1890*/
drh734c9862008-11-28 15:37:20 +00001891static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1892 int rc = SQLITE_OK;
1893 int reserved = 0;
1894 unixFile *pFile = (unixFile*)id;
1895
1896 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1897
1898 assert( pFile );
1899
1900 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001901 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001902 /* Either this connection or some other connection in the same process
1903 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001904 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001905 }else{
1906 /* The lock is held if and only if the lockfile exists */
1907 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001908 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001909 }
drh308c2a52010-05-14 11:30:18 +00001910 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001911 *pResOut = reserved;
1912 return rc;
1913}
1914
drh7708e972008-11-29 00:56:52 +00001915/*
drh308c2a52010-05-14 11:30:18 +00001916** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001917** of the following:
1918**
1919** (1) SHARED_LOCK
1920** (2) RESERVED_LOCK
1921** (3) PENDING_LOCK
1922** (4) EXCLUSIVE_LOCK
1923**
1924** Sometimes when requesting one lock state, additional lock states
1925** are inserted in between. The locking might fail on one of the later
1926** transitions leaving the lock state different from what it started but
1927** still short of its goal. The following chart shows the allowed
1928** transitions and the inserted intermediate states:
1929**
1930** UNLOCKED -> SHARED
1931** SHARED -> RESERVED
1932** SHARED -> (PENDING) -> EXCLUSIVE
1933** RESERVED -> (PENDING) -> EXCLUSIVE
1934** PENDING -> EXCLUSIVE
1935**
1936** This routine will only increase a lock. Use the sqlite3OsUnlock()
1937** routine to lower a locking level.
1938**
1939** With dotfile locking, we really only support state (4): EXCLUSIVE.
1940** But we track the other locking levels internally.
1941*/
drh308c2a52010-05-14 11:30:18 +00001942static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001943 unixFile *pFile = (unixFile*)id;
1944 int fd;
1945 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001946 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001947
drh7708e972008-11-29 00:56:52 +00001948
1949 /* If we have any lock, then the lock file already exists. All we have
1950 ** to do is adjust our internal record of the lock level.
1951 */
drh308c2a52010-05-14 11:30:18 +00001952 if( pFile->eFileLock > NO_LOCK ){
1953 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001954 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001955#ifdef HAVE_UTIME
1956 utime(zLockFile, NULL);
1957#else
drh734c9862008-11-28 15:37:20 +00001958 utimes(zLockFile, NULL);
1959#endif
drh7708e972008-11-29 00:56:52 +00001960 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001961 }
1962
1963 /* grab an exclusive lock */
drhad4f1e52011-03-04 15:43:57 +00001964 fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
drh734c9862008-11-28 15:37:20 +00001965 if( fd<0 ){
1966 /* failed to open/create the file, someone else may have stolen the lock */
1967 int tErrno = errno;
1968 if( EEXIST == tErrno ){
1969 rc = SQLITE_BUSY;
1970 } else {
1971 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1972 if( IS_LOCK_ERROR(rc) ){
1973 pFile->lastErrno = tErrno;
1974 }
1975 }
drh7708e972008-11-29 00:56:52 +00001976 return rc;
drh734c9862008-11-28 15:37:20 +00001977 }
drh0e9365c2011-03-02 02:08:13 +00001978 robust_close(pFile, fd, __LINE__);
drh734c9862008-11-28 15:37:20 +00001979
1980 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001981 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001982 return rc;
1983}
1984
drh7708e972008-11-29 00:56:52 +00001985/*
drh308c2a52010-05-14 11:30:18 +00001986** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001987** must be either NO_LOCK or SHARED_LOCK.
1988**
1989** If the locking level of the file descriptor is already at or below
1990** the requested locking level, this routine is a no-op.
1991**
1992** When the locking level reaches NO_LOCK, delete the lock file.
1993*/
drh308c2a52010-05-14 11:30:18 +00001994static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001995 unixFile *pFile = (unixFile*)id;
1996 char *zLockFile = (char *)pFile->lockingContext;
1997
1998 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001999 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2000 pFile->eFileLock, getpid()));
2001 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002002
2003 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002004 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002005 return SQLITE_OK;
2006 }
drh7708e972008-11-29 00:56:52 +00002007
2008 /* To downgrade to shared, simply update our internal notion of the
2009 ** lock state. No need to mess with the file on disk.
2010 */
drh308c2a52010-05-14 11:30:18 +00002011 if( eFileLock==SHARED_LOCK ){
2012 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002013 return SQLITE_OK;
2014 }
2015
drh7708e972008-11-29 00:56:52 +00002016 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002017 assert( eFileLock==NO_LOCK );
drh036ac7f2011-08-08 23:18:05 +00002018 if( osUnlink(zLockFile) ){
drh0d588bb2009-06-17 13:09:38 +00002019 int rc = 0;
2020 int tErrno = errno;
drh734c9862008-11-28 15:37:20 +00002021 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002022 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002023 }
2024 if( IS_LOCK_ERROR(rc) ){
2025 pFile->lastErrno = tErrno;
2026 }
2027 return rc;
2028 }
drh308c2a52010-05-14 11:30:18 +00002029 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002030 return SQLITE_OK;
2031}
2032
2033/*
drh9b35ea62008-11-29 02:20:26 +00002034** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002035*/
2036static int dotlockClose(sqlite3_file *id) {
2037 int rc;
2038 if( id ){
2039 unixFile *pFile = (unixFile*)id;
2040 dotlockUnlock(id, NO_LOCK);
2041 sqlite3_free(pFile->lockingContext);
2042 }
drh734c9862008-11-28 15:37:20 +00002043 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002044 return rc;
2045}
2046/****************** End of the dot-file lock implementation *******************
2047******************************************************************************/
2048
2049/******************************************************************************
2050************************** Begin flock Locking ********************************
2051**
2052** Use the flock() system call to do file locking.
2053**
drh6b9d6dd2008-12-03 19:34:47 +00002054** flock() locking is like dot-file locking in that the various
2055** fine-grain locking levels supported by SQLite are collapsed into
2056** a single exclusive lock. In other words, SHARED, RESERVED, and
2057** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2058** still works when you do this, but concurrency is reduced since
2059** only a single process can be reading the database at a time.
2060**
drh734c9862008-11-28 15:37:20 +00002061** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2062** compiling for VXWORKS.
2063*/
2064#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002065
drh6b9d6dd2008-12-03 19:34:47 +00002066/*
drhff812312011-02-23 13:33:46 +00002067** Retry flock() calls that fail with EINTR
2068*/
2069#ifdef EINTR
2070static int robust_flock(int fd, int op){
2071 int rc;
2072 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2073 return rc;
2074}
2075#else
drh5c819272011-02-23 14:00:12 +00002076# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002077#endif
2078
2079
2080/*
drh6b9d6dd2008-12-03 19:34:47 +00002081** This routine checks if there is a RESERVED lock held on the specified
2082** file by this or any other process. If such a lock is held, set *pResOut
2083** to a non-zero value otherwise *pResOut is set to zero. The return value
2084** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2085*/
drh734c9862008-11-28 15:37:20 +00002086static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2087 int rc = SQLITE_OK;
2088 int reserved = 0;
2089 unixFile *pFile = (unixFile*)id;
2090
2091 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2092
2093 assert( pFile );
2094
2095 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002096 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002097 reserved = 1;
2098 }
2099
2100 /* Otherwise see if some other process holds it. */
2101 if( !reserved ){
2102 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002103 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002104 if( !lrc ){
2105 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002106 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002107 if ( lrc ) {
2108 int tErrno = errno;
2109 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002110 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002111 if( IS_LOCK_ERROR(lrc) ){
2112 pFile->lastErrno = tErrno;
2113 rc = lrc;
2114 }
2115 }
2116 } else {
2117 int tErrno = errno;
2118 reserved = 1;
2119 /* someone else might have it reserved */
2120 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2121 if( IS_LOCK_ERROR(lrc) ){
2122 pFile->lastErrno = tErrno;
2123 rc = lrc;
2124 }
2125 }
2126 }
drh308c2a52010-05-14 11:30:18 +00002127 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002128
2129#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2130 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2131 rc = SQLITE_OK;
2132 reserved=1;
2133 }
2134#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2135 *pResOut = reserved;
2136 return rc;
2137}
2138
drh6b9d6dd2008-12-03 19:34:47 +00002139/*
drh308c2a52010-05-14 11:30:18 +00002140** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002141** of the following:
2142**
2143** (1) SHARED_LOCK
2144** (2) RESERVED_LOCK
2145** (3) PENDING_LOCK
2146** (4) EXCLUSIVE_LOCK
2147**
2148** Sometimes when requesting one lock state, additional lock states
2149** are inserted in between. The locking might fail on one of the later
2150** transitions leaving the lock state different from what it started but
2151** still short of its goal. The following chart shows the allowed
2152** transitions and the inserted intermediate states:
2153**
2154** UNLOCKED -> SHARED
2155** SHARED -> RESERVED
2156** SHARED -> (PENDING) -> EXCLUSIVE
2157** RESERVED -> (PENDING) -> EXCLUSIVE
2158** PENDING -> EXCLUSIVE
2159**
2160** flock() only really support EXCLUSIVE locks. We track intermediate
2161** lock states in the sqlite3_file structure, but all locks SHARED or
2162** above are really EXCLUSIVE locks and exclude all other processes from
2163** access the file.
2164**
2165** This routine will only increase a lock. Use the sqlite3OsUnlock()
2166** routine to lower a locking level.
2167*/
drh308c2a52010-05-14 11:30:18 +00002168static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002169 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002170 unixFile *pFile = (unixFile*)id;
2171
2172 assert( pFile );
2173
2174 /* if we already have a lock, it is exclusive.
2175 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002176 if (pFile->eFileLock > NO_LOCK) {
2177 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002178 return SQLITE_OK;
2179 }
2180
2181 /* grab an exclusive lock */
2182
drhff812312011-02-23 13:33:46 +00002183 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002184 int tErrno = errno;
2185 /* didn't get, must be busy */
2186 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2187 if( IS_LOCK_ERROR(rc) ){
2188 pFile->lastErrno = tErrno;
2189 }
2190 } else {
2191 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002192 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002193 }
drh308c2a52010-05-14 11:30:18 +00002194 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2195 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002196#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2197 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2198 rc = SQLITE_BUSY;
2199 }
2200#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2201 return rc;
2202}
2203
drh6b9d6dd2008-12-03 19:34:47 +00002204
2205/*
drh308c2a52010-05-14 11:30:18 +00002206** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002207** must be either NO_LOCK or SHARED_LOCK.
2208**
2209** If the locking level of the file descriptor is already at or below
2210** the requested locking level, this routine is a no-op.
2211*/
drh308c2a52010-05-14 11:30:18 +00002212static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002213 unixFile *pFile = (unixFile*)id;
2214
2215 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002216 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2217 pFile->eFileLock, getpid()));
2218 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002219
2220 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002221 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002222 return SQLITE_OK;
2223 }
2224
2225 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002226 if (eFileLock==SHARED_LOCK) {
2227 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002228 return SQLITE_OK;
2229 }
2230
2231 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002232 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002233#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002234 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002235#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002236 return SQLITE_IOERR_UNLOCK;
2237 }else{
drh308c2a52010-05-14 11:30:18 +00002238 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002239 return SQLITE_OK;
2240 }
2241}
2242
2243/*
2244** Close a file.
2245*/
2246static int flockClose(sqlite3_file *id) {
2247 if( id ){
2248 flockUnlock(id, NO_LOCK);
2249 }
2250 return closeUnixFile(id);
2251}
2252
2253#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2254
2255/******************* End of the flock lock implementation *********************
2256******************************************************************************/
2257
2258/******************************************************************************
2259************************ Begin Named Semaphore Locking ************************
2260**
2261** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002262**
2263** Semaphore locking is like dot-lock and flock in that it really only
2264** supports EXCLUSIVE locking. Only a single process can read or write
2265** the database file at a time. This reduces potential concurrency, but
2266** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002267*/
2268#if OS_VXWORKS
2269
drh6b9d6dd2008-12-03 19:34:47 +00002270/*
2271** This routine checks if there is a RESERVED lock held on the specified
2272** file by this or any other process. If such a lock is held, set *pResOut
2273** to a non-zero value otherwise *pResOut is set to zero. The return value
2274** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2275*/
drh734c9862008-11-28 15:37:20 +00002276static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2277 int rc = SQLITE_OK;
2278 int reserved = 0;
2279 unixFile *pFile = (unixFile*)id;
2280
2281 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2282
2283 assert( pFile );
2284
2285 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002286 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002287 reserved = 1;
2288 }
2289
2290 /* Otherwise see if some other process holds it. */
2291 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002292 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002293 struct stat statBuf;
2294
2295 if( sem_trywait(pSem)==-1 ){
2296 int tErrno = errno;
2297 if( EAGAIN != tErrno ){
2298 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2299 pFile->lastErrno = tErrno;
2300 } else {
2301 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002302 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002303 }
2304 }else{
2305 /* we could have it if we want it */
2306 sem_post(pSem);
2307 }
2308 }
drh308c2a52010-05-14 11:30:18 +00002309 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002310
2311 *pResOut = reserved;
2312 return rc;
2313}
2314
drh6b9d6dd2008-12-03 19:34:47 +00002315/*
drh308c2a52010-05-14 11:30:18 +00002316** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002317** of the following:
2318**
2319** (1) SHARED_LOCK
2320** (2) RESERVED_LOCK
2321** (3) PENDING_LOCK
2322** (4) EXCLUSIVE_LOCK
2323**
2324** Sometimes when requesting one lock state, additional lock states
2325** are inserted in between. The locking might fail on one of the later
2326** transitions leaving the lock state different from what it started but
2327** still short of its goal. The following chart shows the allowed
2328** transitions and the inserted intermediate states:
2329**
2330** UNLOCKED -> SHARED
2331** SHARED -> RESERVED
2332** SHARED -> (PENDING) -> EXCLUSIVE
2333** RESERVED -> (PENDING) -> EXCLUSIVE
2334** PENDING -> EXCLUSIVE
2335**
2336** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2337** lock states in the sqlite3_file structure, but all locks SHARED or
2338** above are really EXCLUSIVE locks and exclude all other processes from
2339** access the file.
2340**
2341** This routine will only increase a lock. Use the sqlite3OsUnlock()
2342** routine to lower a locking level.
2343*/
drh308c2a52010-05-14 11:30:18 +00002344static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002345 unixFile *pFile = (unixFile*)id;
2346 int fd;
drh8af6c222010-05-14 12:43:01 +00002347 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002348 int rc = SQLITE_OK;
2349
2350 /* if we already have a lock, it is exclusive.
2351 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002352 if (pFile->eFileLock > NO_LOCK) {
2353 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002354 rc = SQLITE_OK;
2355 goto sem_end_lock;
2356 }
2357
2358 /* lock semaphore now but bail out when already locked. */
2359 if( sem_trywait(pSem)==-1 ){
2360 rc = SQLITE_BUSY;
2361 goto sem_end_lock;
2362 }
2363
2364 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002365 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002366
2367 sem_end_lock:
2368 return rc;
2369}
2370
drh6b9d6dd2008-12-03 19:34:47 +00002371/*
drh308c2a52010-05-14 11:30:18 +00002372** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002373** must be either NO_LOCK or SHARED_LOCK.
2374**
2375** If the locking level of the file descriptor is already at or below
2376** the requested locking level, this routine is a no-op.
2377*/
drh308c2a52010-05-14 11:30:18 +00002378static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002379 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002380 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002381
2382 assert( pFile );
2383 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002384 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2385 pFile->eFileLock, getpid()));
2386 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002387
2388 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002389 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002390 return SQLITE_OK;
2391 }
2392
2393 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002394 if (eFileLock==SHARED_LOCK) {
2395 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002396 return SQLITE_OK;
2397 }
2398
2399 /* no, really unlock. */
2400 if ( sem_post(pSem)==-1 ) {
2401 int rc, tErrno = errno;
2402 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2403 if( IS_LOCK_ERROR(rc) ){
2404 pFile->lastErrno = tErrno;
2405 }
2406 return rc;
2407 }
drh308c2a52010-05-14 11:30:18 +00002408 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002409 return SQLITE_OK;
2410}
2411
2412/*
2413 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002414 */
drh734c9862008-11-28 15:37:20 +00002415static int semClose(sqlite3_file *id) {
2416 if( id ){
2417 unixFile *pFile = (unixFile*)id;
2418 semUnlock(id, NO_LOCK);
2419 assert( pFile );
2420 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002421 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002422 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002423 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002424 }
2425 return SQLITE_OK;
2426}
2427
2428#endif /* OS_VXWORKS */
2429/*
2430** Named semaphore locking is only available on VxWorks.
2431**
2432*************** End of the named semaphore lock implementation ****************
2433******************************************************************************/
2434
2435
2436/******************************************************************************
2437*************************** Begin AFP Locking *********************************
2438**
2439** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2440** on Apple Macintosh computers - both OS9 and OSX.
2441**
2442** Third-party implementations of AFP are available. But this code here
2443** only works on OSX.
2444*/
2445
drhd2cb50b2009-01-09 21:41:17 +00002446#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002447/*
2448** The afpLockingContext structure contains all afp lock specific state
2449*/
drhbfe66312006-10-03 17:40:40 +00002450typedef struct afpLockingContext afpLockingContext;
2451struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002452 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002453 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002454};
2455
2456struct ByteRangeLockPB2
2457{
2458 unsigned long long offset; /* offset to first byte to lock */
2459 unsigned long long length; /* nbr of bytes to lock */
2460 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2461 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2462 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2463 int fd; /* file desc to assoc this lock with */
2464};
2465
drhfd131da2007-08-07 17:13:03 +00002466#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002467
drh6b9d6dd2008-12-03 19:34:47 +00002468/*
2469** This is a utility for setting or clearing a bit-range lock on an
2470** AFP filesystem.
2471**
2472** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2473*/
2474static int afpSetLock(
2475 const char *path, /* Name of the file to be locked or unlocked */
2476 unixFile *pFile, /* Open file descriptor on path */
2477 unsigned long long offset, /* First byte to be locked */
2478 unsigned long long length, /* Number of bytes to lock */
2479 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002480){
drh6b9d6dd2008-12-03 19:34:47 +00002481 struct ByteRangeLockPB2 pb;
2482 int err;
drhbfe66312006-10-03 17:40:40 +00002483
2484 pb.unLockFlag = setLockFlag ? 0 : 1;
2485 pb.startEndFlag = 0;
2486 pb.offset = offset;
2487 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002488 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002489
drh308c2a52010-05-14 11:30:18 +00002490 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002491 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002492 offset, length));
drhbfe66312006-10-03 17:40:40 +00002493 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2494 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002495 int rc;
2496 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002497 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2498 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002499#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2500 rc = SQLITE_BUSY;
2501#else
drh734c9862008-11-28 15:37:20 +00002502 rc = sqliteErrorFromPosixError(tErrno,
2503 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002504#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002505 if( IS_LOCK_ERROR(rc) ){
2506 pFile->lastErrno = tErrno;
2507 }
2508 return rc;
drhbfe66312006-10-03 17:40:40 +00002509 } else {
aswift5b1a2562008-08-22 00:22:35 +00002510 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002511 }
2512}
2513
drh6b9d6dd2008-12-03 19:34:47 +00002514/*
2515** This routine checks if there is a RESERVED lock held on the specified
2516** file by this or any other process. If such a lock is held, set *pResOut
2517** to a non-zero value otherwise *pResOut is set to zero. The return value
2518** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2519*/
danielk1977e339d652008-06-28 11:23:00 +00002520static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002521 int rc = SQLITE_OK;
2522 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002523 unixFile *pFile = (unixFile*)id;
2524
aswift5b1a2562008-08-22 00:22:35 +00002525 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2526
2527 assert( pFile );
drhbfe66312006-10-03 17:40:40 +00002528 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002529 if( context->reserved ){
2530 *pResOut = 1;
2531 return SQLITE_OK;
2532 }
drh8af6c222010-05-14 12:43:01 +00002533 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002534
2535 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002536 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002537 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002538 }
2539
2540 /* Otherwise see if some other process holds it.
2541 */
aswift5b1a2562008-08-22 00:22:35 +00002542 if( !reserved ){
2543 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002544 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002545 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002546 /* if we succeeded in taking the reserved lock, unlock it to restore
2547 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002548 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002549 } else {
2550 /* if we failed to get the lock then someone else must have it */
2551 reserved = 1;
2552 }
2553 if( IS_LOCK_ERROR(lrc) ){
2554 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002555 }
2556 }
drhbfe66312006-10-03 17:40:40 +00002557
drh7ed97b92010-01-20 13:07:21 +00002558 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002559 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002560
2561 *pResOut = reserved;
2562 return rc;
drhbfe66312006-10-03 17:40:40 +00002563}
2564
drh6b9d6dd2008-12-03 19:34:47 +00002565/*
drh308c2a52010-05-14 11:30:18 +00002566** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002567** of the following:
2568**
2569** (1) SHARED_LOCK
2570** (2) RESERVED_LOCK
2571** (3) PENDING_LOCK
2572** (4) EXCLUSIVE_LOCK
2573**
2574** Sometimes when requesting one lock state, additional lock states
2575** are inserted in between. The locking might fail on one of the later
2576** transitions leaving the lock state different from what it started but
2577** still short of its goal. The following chart shows the allowed
2578** transitions and the inserted intermediate states:
2579**
2580** UNLOCKED -> SHARED
2581** SHARED -> RESERVED
2582** SHARED -> (PENDING) -> EXCLUSIVE
2583** RESERVED -> (PENDING) -> EXCLUSIVE
2584** PENDING -> EXCLUSIVE
2585**
2586** This routine will only increase a lock. Use the sqlite3OsUnlock()
2587** routine to lower a locking level.
2588*/
drh308c2a52010-05-14 11:30:18 +00002589static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002590 int rc = SQLITE_OK;
2591 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002592 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002593 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002594
2595 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002596 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2597 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002598 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002599
drhbfe66312006-10-03 17:40:40 +00002600 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002601 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002602 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002603 */
drh308c2a52010-05-14 11:30:18 +00002604 if( pFile->eFileLock>=eFileLock ){
2605 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2606 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002607 return SQLITE_OK;
2608 }
2609
2610 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002611 ** (1) We never move from unlocked to anything higher than shared lock.
2612 ** (2) SQLite never explicitly requests a pendig lock.
2613 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002614 */
drh308c2a52010-05-14 11:30:18 +00002615 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2616 assert( eFileLock!=PENDING_LOCK );
2617 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002618
drh8af6c222010-05-14 12:43:01 +00002619 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002620 */
drh6c7d5c52008-11-21 20:32:33 +00002621 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002622 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002623
2624 /* If some thread using this PID has a lock via a different unixFile*
2625 ** handle that precludes the requested lock, return BUSY.
2626 */
drh8af6c222010-05-14 12:43:01 +00002627 if( (pFile->eFileLock!=pInode->eFileLock &&
2628 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002629 ){
2630 rc = SQLITE_BUSY;
2631 goto afp_end_lock;
2632 }
2633
2634 /* If a SHARED lock is requested, and some thread using this PID already
2635 ** has a SHARED or RESERVED lock, then increment reference counts and
2636 ** return SQLITE_OK.
2637 */
drh308c2a52010-05-14 11:30:18 +00002638 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002639 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002640 assert( eFileLock==SHARED_LOCK );
2641 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002642 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002643 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002644 pInode->nShared++;
2645 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002646 goto afp_end_lock;
2647 }
drhbfe66312006-10-03 17:40:40 +00002648
2649 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002650 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2651 ** be released.
2652 */
drh308c2a52010-05-14 11:30:18 +00002653 if( eFileLock==SHARED_LOCK
2654 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002655 ){
2656 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002657 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002658 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002659 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002660 goto afp_end_lock;
2661 }
2662 }
2663
2664 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002665 ** operating system calls for the specified lock.
2666 */
drh308c2a52010-05-14 11:30:18 +00002667 if( eFileLock==SHARED_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002668 int lrc1, lrc2, lrc1Errno;
2669 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002670
drh8af6c222010-05-14 12:43:01 +00002671 assert( pInode->nShared==0 );
2672 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002673
2674 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002675 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002676 /* note that the quality of the randomness doesn't matter that much */
2677 lk = random();
drh8af6c222010-05-14 12:43:01 +00002678 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002679 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002680 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002681 if( IS_LOCK_ERROR(lrc1) ){
2682 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002683 }
aswift5b1a2562008-08-22 00:22:35 +00002684 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002685 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002686
aswift5b1a2562008-08-22 00:22:35 +00002687 if( IS_LOCK_ERROR(lrc1) ) {
2688 pFile->lastErrno = lrc1Errno;
2689 rc = lrc1;
2690 goto afp_end_lock;
2691 } else if( IS_LOCK_ERROR(lrc2) ){
2692 rc = lrc2;
2693 goto afp_end_lock;
2694 } else if( lrc1 != SQLITE_OK ) {
2695 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002696 } else {
drh308c2a52010-05-14 11:30:18 +00002697 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002698 pInode->nLock++;
2699 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002700 }
drh8af6c222010-05-14 12:43:01 +00002701 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002702 /* We are trying for an exclusive lock but another thread in this
2703 ** same process is still holding a shared lock. */
2704 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002705 }else{
2706 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2707 ** assumed that there is a SHARED or greater lock on the file
2708 ** already.
2709 */
2710 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002711 assert( 0!=pFile->eFileLock );
2712 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002713 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002714 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002715 if( !failed ){
2716 context->reserved = 1;
2717 }
drhbfe66312006-10-03 17:40:40 +00002718 }
drh308c2a52010-05-14 11:30:18 +00002719 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002720 /* Acquire an EXCLUSIVE lock */
2721
2722 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002723 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002724 */
drh6b9d6dd2008-12-03 19:34:47 +00002725 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002726 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002727 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002728 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002729 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002730 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002731 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002732 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002733 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2734 ** a critical I/O error
2735 */
2736 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2737 SQLITE_IOERR_LOCK;
2738 goto afp_end_lock;
2739 }
2740 }else{
aswift5b1a2562008-08-22 00:22:35 +00002741 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002742 }
2743 }
aswift5b1a2562008-08-22 00:22:35 +00002744 if( failed ){
2745 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002746 }
2747 }
2748
2749 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002750 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002751 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002752 }else if( eFileLock==EXCLUSIVE_LOCK ){
2753 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002754 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002755 }
2756
2757afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002758 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002759 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2760 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002761 return rc;
2762}
2763
2764/*
drh308c2a52010-05-14 11:30:18 +00002765** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002766** must be either NO_LOCK or SHARED_LOCK.
2767**
2768** If the locking level of the file descriptor is already at or below
2769** the requested locking level, this routine is a no-op.
2770*/
drh308c2a52010-05-14 11:30:18 +00002771static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002772 int rc = SQLITE_OK;
2773 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002774 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002775 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2776 int skipShared = 0;
2777#ifdef SQLITE_TEST
2778 int h = pFile->h;
2779#endif
drhbfe66312006-10-03 17:40:40 +00002780
2781 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002782 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002783 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002784 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002785
drh308c2a52010-05-14 11:30:18 +00002786 assert( eFileLock<=SHARED_LOCK );
2787 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002788 return SQLITE_OK;
2789 }
drh6c7d5c52008-11-21 20:32:33 +00002790 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002791 pInode = pFile->pInode;
2792 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002793 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002794 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002795 SimulateIOErrorBenign(1);
2796 SimulateIOError( h=(-1) )
2797 SimulateIOErrorBenign(0);
2798
2799#ifndef NDEBUG
2800 /* When reducing a lock such that other processes can start
2801 ** reading the database file again, make sure that the
2802 ** transaction counter was updated if any part of the database
2803 ** file changed. If the transaction counter is not updated,
2804 ** other connections to the same file might not realize that
2805 ** the file has changed and hence might not know to flush their
2806 ** cache. The use of a stale cache can lead to database corruption.
2807 */
2808 assert( pFile->inNormalWrite==0
2809 || pFile->dbUpdate==0
2810 || pFile->transCntrChng==1 );
2811 pFile->inNormalWrite = 0;
2812#endif
aswiftaebf4132008-11-21 00:10:35 +00002813
drh308c2a52010-05-14 11:30:18 +00002814 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002815 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002816 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002817 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002818 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002819 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2820 } else {
2821 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002822 }
2823 }
drh308c2a52010-05-14 11:30:18 +00002824 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002825 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002826 }
drh308c2a52010-05-14 11:30:18 +00002827 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002828 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2829 if( !rc ){
2830 context->reserved = 0;
2831 }
aswiftaebf4132008-11-21 00:10:35 +00002832 }
drh8af6c222010-05-14 12:43:01 +00002833 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2834 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002835 }
aswiftaebf4132008-11-21 00:10:35 +00002836 }
drh308c2a52010-05-14 11:30:18 +00002837 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002838
drh7ed97b92010-01-20 13:07:21 +00002839 /* Decrement the shared lock counter. Release the lock using an
2840 ** OS call only when all threads in this same process have released
2841 ** the lock.
2842 */
drh8af6c222010-05-14 12:43:01 +00002843 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2844 pInode->nShared--;
2845 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002846 SimulateIOErrorBenign(1);
2847 SimulateIOError( h=(-1) )
2848 SimulateIOErrorBenign(0);
2849 if( !skipShared ){
2850 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2851 }
2852 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002853 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002854 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002855 }
2856 }
2857 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002858 pInode->nLock--;
2859 assert( pInode->nLock>=0 );
2860 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002861 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002862 }
2863 }
drhbfe66312006-10-03 17:40:40 +00002864 }
drh7ed97b92010-01-20 13:07:21 +00002865
drh6c7d5c52008-11-21 20:32:33 +00002866 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002867 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002868 return rc;
2869}
2870
2871/*
drh339eb0b2008-03-07 15:34:11 +00002872** Close a file & cleanup AFP specific locking context
2873*/
danielk1977e339d652008-06-28 11:23:00 +00002874static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002875 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002876 if( id ){
2877 unixFile *pFile = (unixFile*)id;
2878 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002879 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002880 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002881 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002882 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002883 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002884 ** the last lock is cleared.
2885 */
dan08da86a2009-08-21 17:18:03 +00002886 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002887 }
danb0ac3e32010-06-16 10:55:42 +00002888 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002889 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002890 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002891 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002892 }
drh7ed97b92010-01-20 13:07:21 +00002893 return rc;
drhbfe66312006-10-03 17:40:40 +00002894}
2895
drhd2cb50b2009-01-09 21:41:17 +00002896#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002897/*
2898** The code above is the AFP lock implementation. The code is specific
2899** to MacOSX and does not work on other unix platforms. No alternative
2900** is available. If you don't compile for a mac, then the "unix-afp"
2901** VFS is not available.
2902**
2903********************* End of the AFP lock implementation **********************
2904******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002905
drh7ed97b92010-01-20 13:07:21 +00002906/******************************************************************************
2907*************************** Begin NFS Locking ********************************/
2908
2909#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2910/*
drh308c2a52010-05-14 11:30:18 +00002911 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002912 ** must be either NO_LOCK or SHARED_LOCK.
2913 **
2914 ** If the locking level of the file descriptor is already at or below
2915 ** the requested locking level, this routine is a no-op.
2916 */
drh308c2a52010-05-14 11:30:18 +00002917static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002918 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002919}
2920
2921#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2922/*
2923** The code above is the NFS lock implementation. The code is specific
2924** to MacOSX and does not work on other unix platforms. No alternative
2925** is available.
2926**
2927********************* End of the NFS lock implementation **********************
2928******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002929
2930/******************************************************************************
2931**************** Non-locking sqlite3_file methods *****************************
2932**
2933** The next division contains implementations for all methods of the
2934** sqlite3_file object other than the locking methods. The locking
2935** methods were defined in divisions above (one locking method per
2936** division). Those methods that are common to all locking modes
2937** are gather together into this division.
2938*/
drhbfe66312006-10-03 17:40:40 +00002939
2940/*
drh734c9862008-11-28 15:37:20 +00002941** Seek to the offset passed as the second argument, then read cnt
2942** bytes into pBuf. Return the number of bytes actually read.
2943**
2944** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2945** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2946** one system to another. Since SQLite does not define USE_PREAD
2947** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2948** See tickets #2741 and #2681.
2949**
2950** To avoid stomping the errno value on a failed read the lastErrno value
2951** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002952*/
drh734c9862008-11-28 15:37:20 +00002953static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2954 int got;
drh7ed97b92010-01-20 13:07:21 +00002955#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002956 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002957#endif
drh734c9862008-11-28 15:37:20 +00002958 TIMER_START;
2959#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00002960 do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002961 SimulateIOError( got = -1 );
2962#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00002963 do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00002964 SimulateIOError( got = -1 );
2965#else
2966 newOffset = lseek(id->h, offset, SEEK_SET);
2967 SimulateIOError( newOffset-- );
2968 if( newOffset!=offset ){
2969 if( newOffset == -1 ){
2970 ((unixFile*)id)->lastErrno = errno;
2971 }else{
2972 ((unixFile*)id)->lastErrno = 0;
2973 }
2974 return -1;
2975 }
drhe562be52011-03-02 18:01:10 +00002976 do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00002977#endif
2978 TIMER_END;
2979 if( got<0 ){
2980 ((unixFile*)id)->lastErrno = errno;
2981 }
drh308c2a52010-05-14 11:30:18 +00002982 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00002983 return got;
drhbfe66312006-10-03 17:40:40 +00002984}
2985
2986/*
drh734c9862008-11-28 15:37:20 +00002987** Read data from a file into a buffer. Return SQLITE_OK if all
2988** bytes were read successfully and SQLITE_IOERR if anything goes
2989** wrong.
drh339eb0b2008-03-07 15:34:11 +00002990*/
drh734c9862008-11-28 15:37:20 +00002991static int unixRead(
2992 sqlite3_file *id,
2993 void *pBuf,
2994 int amt,
2995 sqlite3_int64 offset
2996){
dan08da86a2009-08-21 17:18:03 +00002997 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00002998 int got;
2999 assert( id );
drh08c6d442009-02-09 17:34:07 +00003000
dan08da86a2009-08-21 17:18:03 +00003001 /* If this is a database file (not a journal, master-journal or temp
3002 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003003#if 0
dane946c392009-08-22 11:39:46 +00003004 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003005 || offset>=PENDING_BYTE+512
3006 || offset+amt<=PENDING_BYTE
3007 );
dan7c246102010-04-12 19:00:29 +00003008#endif
drh08c6d442009-02-09 17:34:07 +00003009
dan08da86a2009-08-21 17:18:03 +00003010 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003011 if( got==amt ){
3012 return SQLITE_OK;
3013 }else if( got<0 ){
3014 /* lastErrno set by seekAndRead */
3015 return SQLITE_IOERR_READ;
3016 }else{
dan08da86a2009-08-21 17:18:03 +00003017 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003018 /* Unread parts of the buffer must be zero-filled */
3019 memset(&((char*)pBuf)[got], 0, amt-got);
3020 return SQLITE_IOERR_SHORT_READ;
3021 }
3022}
3023
3024/*
3025** Seek to the offset in id->offset then read cnt bytes into pBuf.
3026** Return the number of bytes actually read. Update the offset.
3027**
3028** To avoid stomping the errno value on a failed write the lastErrno value
3029** is set before returning.
3030*/
3031static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3032 int got;
drh7ed97b92010-01-20 13:07:21 +00003033#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003034 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003035#endif
drh734c9862008-11-28 15:37:20 +00003036 TIMER_START;
3037#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003038 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003039#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003040 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003041#else
drhbd1e50c2011-08-19 14:54:12 +00003042 do{
3043 newOffset = lseek(id->h, offset, SEEK_SET);
3044 SimulateIOError( newOffset-- );
3045 if( newOffset!=offset ){
3046 if( newOffset == -1 ){
3047 ((unixFile*)id)->lastErrno = errno;
3048 }else{
3049 ((unixFile*)id)->lastErrno = 0;
3050 }
3051 return -1;
drh734c9862008-11-28 15:37:20 +00003052 }
drhbd1e50c2011-08-19 14:54:12 +00003053 got = osWrite(id->h, pBuf, cnt);
3054 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003055#endif
3056 TIMER_END;
3057 if( got<0 ){
3058 ((unixFile*)id)->lastErrno = errno;
3059 }
3060
drh308c2a52010-05-14 11:30:18 +00003061 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003062 return got;
3063}
3064
3065
3066/*
3067** Write data from a buffer into a file. Return SQLITE_OK on success
3068** or some other error code on failure.
3069*/
3070static int unixWrite(
3071 sqlite3_file *id,
3072 const void *pBuf,
3073 int amt,
3074 sqlite3_int64 offset
3075){
dan08da86a2009-08-21 17:18:03 +00003076 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003077 int wrote = 0;
3078 assert( id );
3079 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003080
dan08da86a2009-08-21 17:18:03 +00003081 /* If this is a database file (not a journal, master-journal or temp
3082 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003083#if 0
dane946c392009-08-22 11:39:46 +00003084 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003085 || offset>=PENDING_BYTE+512
3086 || offset+amt<=PENDING_BYTE
3087 );
dan7c246102010-04-12 19:00:29 +00003088#endif
drh08c6d442009-02-09 17:34:07 +00003089
drh8f941bc2009-01-14 23:03:40 +00003090#ifndef NDEBUG
3091 /* If we are doing a normal write to a database file (as opposed to
3092 ** doing a hot-journal rollback or a write to some file other than a
3093 ** normal database file) then record the fact that the database
3094 ** has changed. If the transaction counter is modified, record that
3095 ** fact too.
3096 */
dan08da86a2009-08-21 17:18:03 +00003097 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003098 pFile->dbUpdate = 1; /* The database has been modified */
3099 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003100 int rc;
drh8f941bc2009-01-14 23:03:40 +00003101 char oldCntr[4];
3102 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003103 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003104 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003105 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003106 pFile->transCntrChng = 1; /* The transaction counter has changed */
3107 }
3108 }
3109 }
3110#endif
3111
dan08da86a2009-08-21 17:18:03 +00003112 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003113 amt -= wrote;
3114 offset += wrote;
3115 pBuf = &((char*)pBuf)[wrote];
3116 }
3117 SimulateIOError(( wrote=(-1), amt=1 ));
3118 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003119
drh734c9862008-11-28 15:37:20 +00003120 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003121 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003122 /* lastErrno set by seekAndWrite */
3123 return SQLITE_IOERR_WRITE;
3124 }else{
dan08da86a2009-08-21 17:18:03 +00003125 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003126 return SQLITE_FULL;
3127 }
3128 }
dan6e09d692010-07-27 18:34:15 +00003129
drh734c9862008-11-28 15:37:20 +00003130 return SQLITE_OK;
3131}
3132
3133#ifdef SQLITE_TEST
3134/*
3135** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003136** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003137*/
3138int sqlite3_sync_count = 0;
3139int sqlite3_fullsync_count = 0;
3140#endif
3141
3142/*
drh89240432009-03-25 01:06:01 +00003143** We do not trust systems to provide a working fdatasync(). Some do.
3144** Others do no. To be safe, we will stick with the (slower) fsync().
3145** If you know that your system does support fdatasync() correctly,
3146** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003147*/
drh89240432009-03-25 01:06:01 +00003148#if !defined(fdatasync) && !defined(__linux__)
drh734c9862008-11-28 15:37:20 +00003149# define fdatasync fsync
3150#endif
3151
3152/*
3153** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3154** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3155** only available on Mac OS X. But that could change.
3156*/
3157#ifdef F_FULLFSYNC
3158# define HAVE_FULLFSYNC 1
3159#else
3160# define HAVE_FULLFSYNC 0
3161#endif
3162
3163
3164/*
3165** The fsync() system call does not work as advertised on many
3166** unix systems. The following procedure is an attempt to make
3167** it work better.
3168**
3169** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3170** for testing when we want to run through the test suite quickly.
3171** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3172** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3173** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003174**
3175** SQLite sets the dataOnly flag if the size of the file is unchanged.
3176** The idea behind dataOnly is that it should only write the file content
3177** to disk, not the inode. We only set dataOnly if the file size is
3178** unchanged since the file size is part of the inode. However,
3179** Ted Ts'o tells us that fdatasync() will also write the inode if the
3180** file size has changed. The only real difference between fdatasync()
3181** and fsync(), Ted tells us, is that fdatasync() will not flush the
3182** inode if the mtime or owner or other inode attributes have changed.
3183** We only care about the file size, not the other file attributes, so
3184** as far as SQLite is concerned, an fdatasync() is always adequate.
3185** So, we always use fdatasync() if it is available, regardless of
3186** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003187*/
3188static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003189 int rc;
drh734c9862008-11-28 15:37:20 +00003190
3191 /* The following "ifdef/elif/else/" block has the same structure as
3192 ** the one below. It is replicated here solely to avoid cluttering
3193 ** up the real code with the UNUSED_PARAMETER() macros.
3194 */
3195#ifdef SQLITE_NO_SYNC
3196 UNUSED_PARAMETER(fd);
3197 UNUSED_PARAMETER(fullSync);
3198 UNUSED_PARAMETER(dataOnly);
3199#elif HAVE_FULLFSYNC
3200 UNUSED_PARAMETER(dataOnly);
3201#else
3202 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003203 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003204#endif
3205
3206 /* Record the number of times that we do a normal fsync() and
3207 ** FULLSYNC. This is used during testing to verify that this procedure
3208 ** gets called with the correct arguments.
3209 */
3210#ifdef SQLITE_TEST
3211 if( fullSync ) sqlite3_fullsync_count++;
3212 sqlite3_sync_count++;
3213#endif
3214
3215 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3216 ** no-op
3217 */
3218#ifdef SQLITE_NO_SYNC
3219 rc = SQLITE_OK;
3220#elif HAVE_FULLFSYNC
3221 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003222 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003223 }else{
3224 rc = 1;
3225 }
3226 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003227 ** It shouldn't be possible for fullfsync to fail on the local
3228 ** file system (on OSX), so failure indicates that FULLFSYNC
3229 ** isn't supported for this file system. So, attempt an fsync
3230 ** and (for now) ignore the overhead of a superfluous fcntl call.
3231 ** It'd be better to detect fullfsync support once and avoid
3232 ** the fcntl call every time sync is called.
3233 */
drh734c9862008-11-28 15:37:20 +00003234 if( rc ) rc = fsync(fd);
3235
drh7ed97b92010-01-20 13:07:21 +00003236#elif defined(__APPLE__)
3237 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3238 ** so currently we default to the macro that redefines fdatasync to fsync
3239 */
3240 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003241#else
drh0b647ff2009-03-21 14:41:04 +00003242 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003243#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003244 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003245 rc = fsync(fd);
3246 }
drh0b647ff2009-03-21 14:41:04 +00003247#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003248#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3249
3250 if( OS_VXWORKS && rc!= -1 ){
3251 rc = 0;
3252 }
chw97185482008-11-17 08:05:31 +00003253 return rc;
drhbfe66312006-10-03 17:40:40 +00003254}
3255
drh734c9862008-11-28 15:37:20 +00003256/*
drh0059eae2011-08-08 23:48:40 +00003257** Open a file descriptor to the directory containing file zFilename.
3258** If successful, *pFd is set to the opened file descriptor and
3259** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3260** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3261** value.
3262**
drh90315a22011-08-10 01:52:12 +00003263** The directory file descriptor is used for only one thing - to
3264** fsync() a directory to make sure file creation and deletion events
3265** are flushed to disk. Such fsyncs are not needed on newer
3266** journaling filesystems, but are required on older filesystems.
3267**
3268** This routine can be overridden using the xSetSysCall interface.
3269** The ability to override this routine was added in support of the
3270** chromium sandbox. Opening a directory is a security risk (we are
3271** told) so making it overrideable allows the chromium sandbox to
3272** replace this routine with a harmless no-op. To make this routine
3273** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3274** *pFd set to a negative number.
3275**
drh0059eae2011-08-08 23:48:40 +00003276** If SQLITE_OK is returned, the caller is responsible for closing
3277** the file descriptor *pFd using close().
3278*/
3279static int openDirectory(const char *zFilename, int *pFd){
3280 int ii;
3281 int fd = -1;
3282 char zDirname[MAX_PATHNAME+1];
3283
3284 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3285 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3286 if( ii>0 ){
3287 zDirname[ii] = '\0';
3288 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3289 if( fd>=0 ){
3290#ifdef FD_CLOEXEC
3291 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3292#endif
3293 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3294 }
3295 }
3296 *pFd = fd;
3297 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3298}
3299
3300/*
drh734c9862008-11-28 15:37:20 +00003301** Make sure all writes to a particular file are committed to disk.
3302**
3303** If dataOnly==0 then both the file itself and its metadata (file
3304** size, access time, etc) are synced. If dataOnly!=0 then only the
3305** file data is synced.
3306**
3307** Under Unix, also make sure that the directory entry for the file
3308** has been created by fsync-ing the directory that contains the file.
3309** If we do not do this and we encounter a power failure, the directory
3310** entry for the journal might not exist after we reboot. The next
3311** SQLite to access the file will not know that the journal exists (because
3312** the directory entry for the journal was never created) and the transaction
3313** will not roll back - possibly leading to database corruption.
3314*/
3315static int unixSync(sqlite3_file *id, int flags){
3316 int rc;
3317 unixFile *pFile = (unixFile*)id;
3318
3319 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3320 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3321
3322 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3323 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3324 || (flags&0x0F)==SQLITE_SYNC_FULL
3325 );
3326
3327 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3328 ** line is to test that doing so does not cause any problems.
3329 */
3330 SimulateDiskfullError( return SQLITE_FULL );
3331
3332 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003333 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003334 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3335 SimulateIOError( rc=1 );
3336 if( rc ){
3337 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003338 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003339 }
drh0059eae2011-08-08 23:48:40 +00003340
3341 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003342 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3343 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003344 */
3345 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3346 int dirfd;
3347 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003348 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003349 rc = osOpenDirectory(pFile->zPath, &dirfd);
3350 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003351 full_fsync(dirfd, 0, 0);
3352 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003353 }else if( rc==SQLITE_CANTOPEN ){
3354 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003355 }
drh0059eae2011-08-08 23:48:40 +00003356 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003357 }
3358 return rc;
3359}
3360
3361/*
3362** Truncate an open file to a specified size
3363*/
3364static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003365 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003366 int rc;
dan6e09d692010-07-27 18:34:15 +00003367 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003368 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003369
3370 /* If the user has configured a chunk-size for this file, truncate the
3371 ** file so that it consists of an integer number of chunks (i.e. the
3372 ** actual file size after the operation may be larger than the requested
3373 ** size).
3374 */
3375 if( pFile->szChunk ){
3376 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3377 }
3378
drhff812312011-02-23 13:33:46 +00003379 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003380 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003381 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003382 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003383 }else{
drh3313b142009-11-06 04:13:18 +00003384#ifndef NDEBUG
3385 /* If we are doing a normal write to a database file (as opposed to
3386 ** doing a hot-journal rollback or a write to some file other than a
3387 ** normal database file) and we truncate the file to zero length,
3388 ** that effectively updates the change counter. This might happen
3389 ** when restoring a database using the backup API from a zero-length
3390 ** source.
3391 */
dan6e09d692010-07-27 18:34:15 +00003392 if( pFile->inNormalWrite && nByte==0 ){
3393 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003394 }
3395#endif
3396
drh734c9862008-11-28 15:37:20 +00003397 return SQLITE_OK;
3398 }
3399}
3400
3401/*
3402** Determine the current size of a file in bytes
3403*/
3404static int unixFileSize(sqlite3_file *id, i64 *pSize){
3405 int rc;
3406 struct stat buf;
3407 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003408 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003409 SimulateIOError( rc=1 );
3410 if( rc!=0 ){
3411 ((unixFile*)id)->lastErrno = errno;
3412 return SQLITE_IOERR_FSTAT;
3413 }
3414 *pSize = buf.st_size;
3415
drh8af6c222010-05-14 12:43:01 +00003416 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003417 ** writes a single byte into that file in order to work around a bug
3418 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3419 ** layers, we need to report this file size as zero even though it is
3420 ** really 1. Ticket #3260.
3421 */
3422 if( *pSize==1 ) *pSize = 0;
3423
3424
3425 return SQLITE_OK;
3426}
3427
drhd2cb50b2009-01-09 21:41:17 +00003428#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003429/*
3430** Handler for proxy-locking file-control verbs. Defined below in the
3431** proxying locking division.
3432*/
3433static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003434#endif
drh715ff302008-12-03 22:32:44 +00003435
dan502019c2010-07-28 14:26:17 +00003436/*
3437** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3438** file-control operation.
3439**
3440** If the user has configured a chunk-size for this file, it could be
3441** that the file needs to be extended at this point. Otherwise, the
3442** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3443*/
3444static int fcntlSizeHint(unixFile *pFile, i64 nByte){
drh7d2dc712011-07-25 23:25:47 +00003445 { /* preserve indentation of removed "if" */
dan502019c2010-07-28 14:26:17 +00003446 i64 nSize; /* Required file size */
drh7d2dc712011-07-25 23:25:47 +00003447 i64 szChunk; /* Chunk size */
dan502019c2010-07-28 14:26:17 +00003448 struct stat buf; /* Used to hold return values of fstat() */
3449
drh99ab3b12011-03-02 15:09:07 +00003450 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003451
drh7d2dc712011-07-25 23:25:47 +00003452 szChunk = pFile->szChunk;
3453 if( szChunk==0 ){
3454 nSize = nByte;
3455 }else{
3456 nSize = ((nByte+szChunk-1) / szChunk) * szChunk;
3457 }
dan502019c2010-07-28 14:26:17 +00003458 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003459
dan502019c2010-07-28 14:26:17 +00003460#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003461 /* The code below is handling the return value of osFallocate()
3462 ** correctly. posix_fallocate() is defined to "returns zero on success,
3463 ** or an error number on failure". See the manpage for details. */
3464 int err;
drhff812312011-02-23 13:33:46 +00003465 do{
dan661d71a2011-03-30 19:08:03 +00003466 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3467 }while( err==EINTR );
3468 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003469#else
3470 /* If the OS does not have posix_fallocate(), fake it. First use
3471 ** ftruncate() to set the file size, then write a single byte to
3472 ** the last byte in each block within the extended region. This
3473 ** is the same technique used by glibc to implement posix_fallocate()
3474 ** on systems that do not have a real fallocate() system call.
3475 */
3476 int nBlk = buf.st_blksize; /* File-system block size */
3477 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003478
drhff812312011-02-23 13:33:46 +00003479 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003480 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003481 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003482 }
3483 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003484 while( iWrite<nSize ){
3485 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3486 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003487 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003488 }
dan502019c2010-07-28 14:26:17 +00003489#endif
3490 }
3491 }
3492
3493 return SQLITE_OK;
3494}
danielk1977ad94b582007-08-20 06:44:22 +00003495
danielk1977e3026632004-06-22 11:29:02 +00003496/*
drh9e33c2c2007-08-31 18:34:59 +00003497** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003498*/
drhcc6bb3e2007-08-31 16:11:35 +00003499static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003500 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003501 switch( op ){
3502 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003503 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003504 return SQLITE_OK;
3505 }
drh7708e972008-11-29 00:56:52 +00003506 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003507 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003508 return SQLITE_OK;
3509 }
dan6e09d692010-07-27 18:34:15 +00003510 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003511 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003512 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003513 }
drh9ff27ec2010-05-19 19:26:05 +00003514 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003515 int rc;
3516 SimulateIOErrorBenign(1);
3517 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3518 SimulateIOErrorBenign(0);
3519 return rc;
drhf0b190d2011-07-26 16:03:07 +00003520 }
3521 case SQLITE_FCNTL_PERSIST_WAL: {
3522 int bPersist = *(int*)pArg;
3523 if( bPersist<0 ){
drh253cea52011-07-26 16:23:25 +00003524 *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
drhf0b190d2011-07-26 16:03:07 +00003525 }else if( bPersist==0 ){
3526 pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
3527 }else{
3528 pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
3529 }
3530 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003531 }
drh8f941bc2009-01-14 23:03:40 +00003532#ifndef NDEBUG
3533 /* The pager calls this method to signal that it has done
3534 ** a rollback and that the database is therefore unchanged and
3535 ** it hence it is OK for the transaction change counter to be
3536 ** unchanged.
3537 */
3538 case SQLITE_FCNTL_DB_UNCHANGED: {
3539 ((unixFile*)id)->dbUpdate = 0;
3540 return SQLITE_OK;
3541 }
3542#endif
drhd2cb50b2009-01-09 21:41:17 +00003543#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003544 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003545 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003546 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003547 }
drhd2cb50b2009-01-09 21:41:17 +00003548#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003549 case SQLITE_FCNTL_SYNC_OMITTED: {
3550 return SQLITE_OK; /* A no-op */
3551 }
drh9e33c2c2007-08-31 18:34:59 +00003552 }
drh0b52b7d2011-01-26 19:46:22 +00003553 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003554}
3555
3556/*
danielk1977a3d4c882007-03-23 10:08:38 +00003557** Return the sector size in bytes of the underlying block device for
3558** the specified file. This is almost always 512 bytes, but may be
3559** larger for some devices.
3560**
3561** SQLite code assumes this function cannot fail. It also assumes that
3562** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003563** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003564** same for both.
3565*/
danielk1977397d65f2008-11-19 11:35:39 +00003566static int unixSectorSize(sqlite3_file *NotUsed){
3567 UNUSED_PARAMETER(NotUsed);
drh3ceeb752007-03-29 18:19:52 +00003568 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003569}
3570
danielk197790949c22007-08-17 16:50:38 +00003571/*
danielk1977397d65f2008-11-19 11:35:39 +00003572** Return the device characteristics for the file. This is always 0 for unix.
danielk197790949c22007-08-17 16:50:38 +00003573*/
danielk1977397d65f2008-11-19 11:35:39 +00003574static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3575 UNUSED_PARAMETER(NotUsed);
danielk197762079062007-08-15 17:08:46 +00003576 return 0;
3577}
3578
drhd9e5c4f2010-05-12 18:01:39 +00003579#ifndef SQLITE_OMIT_WAL
3580
3581
3582/*
drhd91c68f2010-05-14 14:52:25 +00003583** Object used to represent an shared memory buffer.
3584**
3585** When multiple threads all reference the same wal-index, each thread
3586** has its own unixShm object, but they all point to a single instance
3587** of this unixShmNode object. In other words, each wal-index is opened
3588** only once per process.
3589**
3590** Each unixShmNode object is connected to a single unixInodeInfo object.
3591** We could coalesce this object into unixInodeInfo, but that would mean
3592** every open file that does not use shared memory (in other words, most
3593** open files) would have to carry around this extra information. So
3594** the unixInodeInfo object contains a pointer to this unixShmNode object
3595** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003596**
3597** unixMutexHeld() must be true when creating or destroying
3598** this object or while reading or writing the following fields:
3599**
3600** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003601**
3602** The following fields are read-only after the object is created:
3603**
3604** fid
3605** zFilename
3606**
drhd91c68f2010-05-14 14:52:25 +00003607** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003608** unixMutexHeld() is true when reading or writing any other field
3609** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003610*/
drhd91c68f2010-05-14 14:52:25 +00003611struct unixShmNode {
3612 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003613 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003614 char *zFilename; /* Name of the mmapped file */
3615 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003616 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003617 u16 nRegion; /* Size of array apRegion */
3618 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003619 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003620 int nRef; /* Number of unixShm objects pointing to this */
3621 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003622#ifdef SQLITE_DEBUG
3623 u8 exclMask; /* Mask of exclusive locks held */
3624 u8 sharedMask; /* Mask of shared locks held */
3625 u8 nextShmId; /* Next available unixShm.id value */
3626#endif
3627};
3628
3629/*
drhd9e5c4f2010-05-12 18:01:39 +00003630** Structure used internally by this VFS to record the state of an
3631** open shared memory connection.
3632**
drhd91c68f2010-05-14 14:52:25 +00003633** The following fields are initialized when this object is created and
3634** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003635**
drhd91c68f2010-05-14 14:52:25 +00003636** unixShm.pFile
3637** unixShm.id
3638**
3639** All other fields are read/write. The unixShm.pFile->mutex must be held
3640** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003641*/
3642struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003643 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3644 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003645 u8 hasMutex; /* True if holding the unixShmNode mutex */
drh73b64e42010-05-30 19:55:15 +00003646 u16 sharedMask; /* Mask of shared locks held */
3647 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003648#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003649 u8 id; /* Id of this connection within its unixShmNode */
drhd9e5c4f2010-05-12 18:01:39 +00003650#endif
3651};
3652
3653/*
drhd9e5c4f2010-05-12 18:01:39 +00003654** Constants used for locking
3655*/
drhbd9676c2010-06-23 17:58:38 +00003656#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003657#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003658
drhd9e5c4f2010-05-12 18:01:39 +00003659/*
drh73b64e42010-05-30 19:55:15 +00003660** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003661**
3662** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3663** otherwise.
3664*/
3665static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003666 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3667 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003668 int ofst, /* First byte of the locking range */
3669 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003670){
3671 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003672 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003673
drhd91c68f2010-05-14 14:52:25 +00003674 /* Access to the unixShmNode object is serialized by the caller */
3675 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003676
drh73b64e42010-05-30 19:55:15 +00003677 /* Shared locks never span more than one byte */
3678 assert( n==1 || lockType!=F_RDLCK );
3679
3680 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003681 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003682
drh3cb93392011-03-12 18:10:44 +00003683 if( pShmNode->h>=0 ){
3684 /* Initialize the locking parameters */
3685 memset(&f, 0, sizeof(f));
3686 f.l_type = lockType;
3687 f.l_whence = SEEK_SET;
3688 f.l_start = ofst;
3689 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003690
drh3cb93392011-03-12 18:10:44 +00003691 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3692 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3693 }
drhd9e5c4f2010-05-12 18:01:39 +00003694
3695 /* Update the global lock state and do debug tracing */
3696#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003697 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003698 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003699 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003700 if( rc==SQLITE_OK ){
3701 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003702 OSTRACE(("unlock %d ok", ofst));
3703 pShmNode->exclMask &= ~mask;
3704 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003705 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003706 OSTRACE(("read-lock %d ok", ofst));
3707 pShmNode->exclMask &= ~mask;
3708 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003709 }else{
3710 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003711 OSTRACE(("write-lock %d ok", ofst));
3712 pShmNode->exclMask |= mask;
3713 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003714 }
3715 }else{
3716 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003717 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003718 }else if( lockType==F_RDLCK ){
3719 OSTRACE(("read-lock failed"));
3720 }else{
3721 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003722 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003723 }
3724 }
drh20e1f082010-05-31 16:10:12 +00003725 OSTRACE((" - afterwards %03x,%03x\n",
3726 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003727 }
drhd9e5c4f2010-05-12 18:01:39 +00003728#endif
3729
3730 return rc;
3731}
3732
drhd9e5c4f2010-05-12 18:01:39 +00003733
3734/*
drhd91c68f2010-05-14 14:52:25 +00003735** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003736**
3737** This is not a VFS shared-memory method; it is a utility function called
3738** by VFS shared-memory methods.
3739*/
drhd91c68f2010-05-14 14:52:25 +00003740static void unixShmPurge(unixFile *pFd){
3741 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003742 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003743 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003744 int i;
drhd91c68f2010-05-14 14:52:25 +00003745 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003746 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003747 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003748 if( p->h>=0 ){
3749 munmap(p->apRegion[i], p->szRegion);
3750 }else{
3751 sqlite3_free(p->apRegion[i]);
3752 }
dan13a3cb82010-06-11 19:04:21 +00003753 }
dan18801912010-06-14 14:07:50 +00003754 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003755 if( p->h>=0 ){
3756 robust_close(pFd, p->h, __LINE__);
3757 p->h = -1;
3758 }
drhd91c68f2010-05-14 14:52:25 +00003759 p->pInode->pShmNode = 0;
3760 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003761 }
3762}
3763
3764/*
danda9fe0c2010-07-13 18:44:03 +00003765** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003766** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003767**
drh7234c6d2010-06-19 15:10:09 +00003768** The file used to implement shared-memory is in the same directory
3769** as the open database file and has the same name as the open database
3770** file with the "-shm" suffix added. For example, if the database file
3771** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003772** for shared memory will be called "/home/user1/config.db-shm".
3773**
3774** Another approach to is to use files in /dev/shm or /dev/tmp or an
3775** some other tmpfs mount. But if a file in a different directory
3776** from the database file is used, then differing access permissions
3777** or a chroot() might cause two different processes on the same
3778** database to end up using different files for shared memory -
3779** meaning that their memory would not really be shared - resulting
3780** in database corruption. Nevertheless, this tmpfs file usage
3781** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3782** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3783** option results in an incompatible build of SQLite; builds of SQLite
3784** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3785** same database file at the same time, database corruption will likely
3786** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3787** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003788**
3789** When opening a new shared-memory file, if no other instances of that
3790** file are currently open, in this process or in other processes, then
3791** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003792**
3793** If the original database file (pDbFd) is using the "unix-excl" VFS
3794** that means that an exclusive lock is held on the database file and
3795** that no other processes are able to read or write the database. In
3796** that case, we do not really need shared memory. No shared memory
3797** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003798*/
danda9fe0c2010-07-13 18:44:03 +00003799static int unixOpenSharedMemory(unixFile *pDbFd){
3800 struct unixShm *p = 0; /* The connection to be opened */
3801 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3802 int rc; /* Result code */
3803 unixInodeInfo *pInode; /* The inode of fd */
3804 char *zShmFilename; /* Name of the file used for SHM */
3805 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003806
danda9fe0c2010-07-13 18:44:03 +00003807 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003808 p = sqlite3_malloc( sizeof(*p) );
3809 if( p==0 ) return SQLITE_NOMEM;
3810 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003811 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003812
danda9fe0c2010-07-13 18:44:03 +00003813 /* Check to see if a unixShmNode object already exists. Reuse an existing
3814 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003815 */
3816 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003817 pInode = pDbFd->pInode;
3818 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003819 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003820 struct stat sStat; /* fstat() info for database file */
3821
3822 /* Call fstat() to figure out the permissions on the database file. If
3823 ** a new *-shm file is created, an attempt will be made to create it
3824 ** with the same permissions. The actual permissions the file is created
3825 ** with are subject to the current umask setting.
3826 */
drh3cb93392011-03-12 18:10:44 +00003827 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003828 rc = SQLITE_IOERR_FSTAT;
3829 goto shm_open_err;
3830 }
3831
drha4ced192010-07-15 18:32:40 +00003832#ifdef SQLITE_SHM_DIRECTORY
3833 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3834#else
drh7234c6d2010-06-19 15:10:09 +00003835 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003836#endif
drh7234c6d2010-06-19 15:10:09 +00003837 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003838 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003839 rc = SQLITE_NOMEM;
3840 goto shm_open_err;
3841 }
drhd91c68f2010-05-14 14:52:25 +00003842 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003843 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003844#ifdef SQLITE_SHM_DIRECTORY
3845 sqlite3_snprintf(nShmFilename, zShmFilename,
3846 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3847 (u32)sStat.st_ino, (u32)sStat.st_dev);
3848#else
drh7234c6d2010-06-19 15:10:09 +00003849 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003850 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003851#endif
drhd91c68f2010-05-14 14:52:25 +00003852 pShmNode->h = -1;
3853 pDbFd->pInode->pShmNode = pShmNode;
3854 pShmNode->pInode = pDbFd->pInode;
3855 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3856 if( pShmNode->mutex==0 ){
3857 rc = SQLITE_NOMEM;
3858 goto shm_open_err;
3859 }
drhd9e5c4f2010-05-12 18:01:39 +00003860
drh3cb93392011-03-12 18:10:44 +00003861 if( pInode->bProcessLock==0 ){
drh66dfec8b2011-06-01 20:01:49 +00003862 pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
3863 (sStat.st_mode & 0777));
drh3cb93392011-03-12 18:10:44 +00003864 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003865 const char *zRO;
3866 zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
drhfd019ef2011-06-01 20:13:36 +00003867 if( zRO && sqlite3GetBoolean(zRO) ){
drh66dfec8b2011-06-01 20:01:49 +00003868 pShmNode->h = robust_open(zShmFilename, O_RDONLY,
3869 (sStat.st_mode & 0777));
3870 pShmNode->isReadonly = 1;
3871 }
3872 if( pShmNode->h<0 ){
3873 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3874 goto shm_open_err;
3875 }
drhd9e5c4f2010-05-12 18:01:39 +00003876 }
drh3cb93392011-03-12 18:10:44 +00003877
3878 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003879 ** If not, truncate the file to zero length.
3880 */
3881 rc = SQLITE_OK;
3882 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3883 if( robust_ftruncate(pShmNode->h, 0) ){
3884 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003885 }
3886 }
drh66dfec8b2011-06-01 20:01:49 +00003887 if( rc==SQLITE_OK ){
3888 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3889 }
3890 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003891 }
drhd9e5c4f2010-05-12 18:01:39 +00003892 }
3893
drhd91c68f2010-05-14 14:52:25 +00003894 /* Make the new connection a child of the unixShmNode */
3895 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003896#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003897 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003898#endif
drhd91c68f2010-05-14 14:52:25 +00003899 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003900 pDbFd->pShm = p;
3901 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003902
3903 /* The reference count on pShmNode has already been incremented under
3904 ** the cover of the unixEnterMutex() mutex and the pointer from the
3905 ** new (struct unixShm) object to the pShmNode has been set. All that is
3906 ** left to do is to link the new object into the linked list starting
3907 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3908 ** mutex.
3909 */
3910 sqlite3_mutex_enter(pShmNode->mutex);
3911 p->pNext = pShmNode->pFirst;
3912 pShmNode->pFirst = p;
3913 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003914 return SQLITE_OK;
3915
3916 /* Jump here on any error */
3917shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003918 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003919 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003920 unixLeaveMutex();
3921 return rc;
3922}
3923
3924/*
danda9fe0c2010-07-13 18:44:03 +00003925** This function is called to obtain a pointer to region iRegion of the
3926** shared-memory associated with the database file fd. Shared-memory regions
3927** are numbered starting from zero. Each shared-memory region is szRegion
3928** bytes in size.
3929**
3930** If an error occurs, an error code is returned and *pp is set to NULL.
3931**
3932** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3933** region has not been allocated (by any client, including one running in a
3934** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3935** bExtend is non-zero and the requested shared-memory region has not yet
3936** been allocated, it is allocated by this function.
3937**
3938** If the shared-memory region has already been allocated or is allocated by
3939** this call as described above, then it is mapped into this processes
3940** address space (if it is not already), *pp is set to point to the mapped
3941** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003942*/
danda9fe0c2010-07-13 18:44:03 +00003943static int unixShmMap(
3944 sqlite3_file *fd, /* Handle open on database file */
3945 int iRegion, /* Region to retrieve */
3946 int szRegion, /* Size of regions */
3947 int bExtend, /* True to extend file if necessary */
3948 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003949){
danda9fe0c2010-07-13 18:44:03 +00003950 unixFile *pDbFd = (unixFile*)fd;
3951 unixShm *p;
3952 unixShmNode *pShmNode;
3953 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003954
danda9fe0c2010-07-13 18:44:03 +00003955 /* If the shared-memory file has not yet been opened, open it now. */
3956 if( pDbFd->pShm==0 ){
3957 rc = unixOpenSharedMemory(pDbFd);
3958 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003959 }
drhd9e5c4f2010-05-12 18:01:39 +00003960
danda9fe0c2010-07-13 18:44:03 +00003961 p = pDbFd->pShm;
3962 pShmNode = p->pShmNode;
3963 sqlite3_mutex_enter(pShmNode->mutex);
3964 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003965 assert( pShmNode->pInode==pDbFd->pInode );
3966 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3967 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003968
3969 if( pShmNode->nRegion<=iRegion ){
3970 char **apNew; /* New apRegion[] array */
3971 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3972 struct stat sStat; /* Used by fstat() */
3973
3974 pShmNode->szRegion = szRegion;
3975
drh3cb93392011-03-12 18:10:44 +00003976 if( pShmNode->h>=0 ){
3977 /* The requested region is not mapped into this processes address space.
3978 ** Check to see if it has been allocated (i.e. if the wal-index file is
3979 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00003980 */
drh3cb93392011-03-12 18:10:44 +00003981 if( osFstat(pShmNode->h, &sStat) ){
3982 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00003983 goto shmpage_out;
3984 }
drh3cb93392011-03-12 18:10:44 +00003985
3986 if( sStat.st_size<nByte ){
3987 /* The requested memory region does not exist. If bExtend is set to
3988 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3989 **
3990 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3991 ** the requested memory region.
3992 */
3993 if( !bExtend ) goto shmpage_out;
3994 if( robust_ftruncate(pShmNode->h, nByte) ){
3995 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
3996 pShmNode->zFilename);
3997 goto shmpage_out;
3998 }
3999 }
danda9fe0c2010-07-13 18:44:03 +00004000 }
4001
4002 /* Map the requested memory region into this processes address space. */
4003 apNew = (char **)sqlite3_realloc(
4004 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4005 );
4006 if( !apNew ){
4007 rc = SQLITE_IOERR_NOMEM;
4008 goto shmpage_out;
4009 }
4010 pShmNode->apRegion = apNew;
4011 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004012 void *pMem;
4013 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004014 pMem = mmap(0, szRegion,
4015 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004016 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4017 );
4018 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004019 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004020 goto shmpage_out;
4021 }
4022 }else{
4023 pMem = sqlite3_malloc(szRegion);
4024 if( pMem==0 ){
4025 rc = SQLITE_NOMEM;
4026 goto shmpage_out;
4027 }
4028 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004029 }
4030 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4031 pShmNode->nRegion++;
4032 }
4033 }
4034
4035shmpage_out:
4036 if( pShmNode->nRegion>iRegion ){
4037 *pp = pShmNode->apRegion[iRegion];
4038 }else{
4039 *pp = 0;
4040 }
drh66dfec8b2011-06-01 20:01:49 +00004041 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004042 sqlite3_mutex_leave(pShmNode->mutex);
4043 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004044}
4045
4046/*
drhd9e5c4f2010-05-12 18:01:39 +00004047** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004048**
4049** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4050** different here than in posix. In xShmLock(), one can go from unlocked
4051** to shared and back or from unlocked to exclusive and back. But one may
4052** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004053*/
4054static int unixShmLock(
4055 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004056 int ofst, /* First lock to acquire or release */
4057 int n, /* Number of locks to acquire or release */
4058 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004059){
drh73b64e42010-05-30 19:55:15 +00004060 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4061 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4062 unixShm *pX; /* For looping over all siblings */
4063 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4064 int rc = SQLITE_OK; /* Result code */
4065 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004066
drhd91c68f2010-05-14 14:52:25 +00004067 assert( pShmNode==pDbFd->pInode->pShmNode );
4068 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004069 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004070 assert( n>=1 );
4071 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4072 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4073 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4074 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4075 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004076 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4077 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004078
drhc99597c2010-05-31 01:41:15 +00004079 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004080 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004081 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004082 if( flags & SQLITE_SHM_UNLOCK ){
4083 u16 allMask = 0; /* Mask of locks held by siblings */
4084
4085 /* See if any siblings hold this same lock */
4086 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4087 if( pX==p ) continue;
4088 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4089 allMask |= pX->sharedMask;
4090 }
4091
4092 /* Unlock the system-level locks */
4093 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004094 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004095 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004096 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004097 }
drh73b64e42010-05-30 19:55:15 +00004098
4099 /* Undo the local locks */
4100 if( rc==SQLITE_OK ){
4101 p->exclMask &= ~mask;
4102 p->sharedMask &= ~mask;
4103 }
4104 }else if( flags & SQLITE_SHM_SHARED ){
4105 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4106
4107 /* Find out which shared locks are already held by sibling connections.
4108 ** If any sibling already holds an exclusive lock, go ahead and return
4109 ** SQLITE_BUSY.
4110 */
4111 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004112 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004113 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004114 break;
4115 }
4116 allShared |= pX->sharedMask;
4117 }
4118
4119 /* Get shared locks at the system level, if necessary */
4120 if( rc==SQLITE_OK ){
4121 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004122 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004123 }else{
drh73b64e42010-05-30 19:55:15 +00004124 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004125 }
drhd9e5c4f2010-05-12 18:01:39 +00004126 }
drh73b64e42010-05-30 19:55:15 +00004127
4128 /* Get the local shared locks */
4129 if( rc==SQLITE_OK ){
4130 p->sharedMask |= mask;
4131 }
4132 }else{
4133 /* Make sure no sibling connections hold locks that will block this
4134 ** lock. If any do, return SQLITE_BUSY right away.
4135 */
4136 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004137 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4138 rc = SQLITE_BUSY;
4139 break;
4140 }
4141 }
4142
4143 /* Get the exclusive locks at the system level. Then if successful
4144 ** also mark the local connection as being locked.
4145 */
4146 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004147 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004148 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004149 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004150 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004151 }
drhd9e5c4f2010-05-12 18:01:39 +00004152 }
4153 }
drhd91c68f2010-05-14 14:52:25 +00004154 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004155 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4156 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004157 return rc;
4158}
4159
drh286a2882010-05-20 23:51:06 +00004160/*
4161** Implement a memory barrier or memory fence on shared memory.
4162**
4163** All loads and stores begun before the barrier must complete before
4164** any load or store begun after the barrier.
4165*/
4166static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004167 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004168){
drhff828942010-06-26 21:34:06 +00004169 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004170 unixEnterMutex();
4171 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004172}
4173
dan18801912010-06-14 14:07:50 +00004174/*
danda9fe0c2010-07-13 18:44:03 +00004175** Close a connection to shared-memory. Delete the underlying
4176** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004177**
4178** If there is no shared memory associated with the connection then this
4179** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004180*/
danda9fe0c2010-07-13 18:44:03 +00004181static int unixShmUnmap(
4182 sqlite3_file *fd, /* The underlying database file */
4183 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004184){
danda9fe0c2010-07-13 18:44:03 +00004185 unixShm *p; /* The connection to be closed */
4186 unixShmNode *pShmNode; /* The underlying shared-memory file */
4187 unixShm **pp; /* For looping over sibling connections */
4188 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004189
danda9fe0c2010-07-13 18:44:03 +00004190 pDbFd = (unixFile*)fd;
4191 p = pDbFd->pShm;
4192 if( p==0 ) return SQLITE_OK;
4193 pShmNode = p->pShmNode;
4194
4195 assert( pShmNode==pDbFd->pInode->pShmNode );
4196 assert( pShmNode->pInode==pDbFd->pInode );
4197
4198 /* Remove connection p from the set of connections associated
4199 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004200 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004201 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4202 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004203
danda9fe0c2010-07-13 18:44:03 +00004204 /* Free the connection p */
4205 sqlite3_free(p);
4206 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004207 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004208
4209 /* If pShmNode->nRef has reached 0, then close the underlying
4210 ** shared-memory file, too */
4211 unixEnterMutex();
4212 assert( pShmNode->nRef>0 );
4213 pShmNode->nRef--;
4214 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004215 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004216 unixShmPurge(pDbFd);
4217 }
4218 unixLeaveMutex();
4219
4220 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004221}
drh286a2882010-05-20 23:51:06 +00004222
danda9fe0c2010-07-13 18:44:03 +00004223
drhd9e5c4f2010-05-12 18:01:39 +00004224#else
drh6b017cc2010-06-14 18:01:46 +00004225# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004226# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004227# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004228# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004229#endif /* #ifndef SQLITE_OMIT_WAL */
4230
drh734c9862008-11-28 15:37:20 +00004231/*
4232** Here ends the implementation of all sqlite3_file methods.
4233**
4234********************** End sqlite3_file Methods *******************************
4235******************************************************************************/
4236
4237/*
drh6b9d6dd2008-12-03 19:34:47 +00004238** This division contains definitions of sqlite3_io_methods objects that
4239** implement various file locking strategies. It also contains definitions
4240** of "finder" functions. A finder-function is used to locate the appropriate
4241** sqlite3_io_methods object for a particular database file. The pAppData
4242** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4243** the correct finder-function for that VFS.
4244**
4245** Most finder functions return a pointer to a fixed sqlite3_io_methods
4246** object. The only interesting finder-function is autolockIoFinder, which
4247** looks at the filesystem type and tries to guess the best locking
4248** strategy from that.
4249**
drh1875f7a2008-12-08 18:19:17 +00004250** For finder-funtion F, two objects are created:
4251**
4252** (1) The real finder-function named "FImpt()".
4253**
dane946c392009-08-22 11:39:46 +00004254** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004255**
4256**
4257** A pointer to the F pointer is used as the pAppData value for VFS
4258** objects. We have to do this instead of letting pAppData point
4259** directly at the finder-function since C90 rules prevent a void*
4260** from be cast into a function pointer.
4261**
drh6b9d6dd2008-12-03 19:34:47 +00004262**
drh7708e972008-11-29 00:56:52 +00004263** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004264**
drh7708e972008-11-29 00:56:52 +00004265** * A constant sqlite3_io_methods object call METHOD that has locking
4266** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4267**
4268** * An I/O method finder function called FINDER that returns a pointer
4269** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004270*/
drhd9e5c4f2010-05-12 18:01:39 +00004271#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004272static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004273 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004274 CLOSE, /* xClose */ \
4275 unixRead, /* xRead */ \
4276 unixWrite, /* xWrite */ \
4277 unixTruncate, /* xTruncate */ \
4278 unixSync, /* xSync */ \
4279 unixFileSize, /* xFileSize */ \
4280 LOCK, /* xLock */ \
4281 UNLOCK, /* xUnlock */ \
4282 CKLOCK, /* xCheckReservedLock */ \
4283 unixFileControl, /* xFileControl */ \
4284 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004285 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004286 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004287 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004288 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004289 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004290}; \
drh0c2694b2009-09-03 16:23:44 +00004291static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4292 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004293 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004294} \
drh0c2694b2009-09-03 16:23:44 +00004295static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004296 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004297
4298/*
4299** Here are all of the sqlite3_io_methods objects for each of the
4300** locking strategies. Functions that return pointers to these methods
4301** are also created.
4302*/
4303IOMETHODS(
4304 posixIoFinder, /* Finder function name */
4305 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004306 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004307 unixClose, /* xClose method */
4308 unixLock, /* xLock method */
4309 unixUnlock, /* xUnlock method */
4310 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004311)
drh7708e972008-11-29 00:56:52 +00004312IOMETHODS(
4313 nolockIoFinder, /* Finder function name */
4314 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004315 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004316 nolockClose, /* xClose method */
4317 nolockLock, /* xLock method */
4318 nolockUnlock, /* xUnlock method */
4319 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004320)
drh7708e972008-11-29 00:56:52 +00004321IOMETHODS(
4322 dotlockIoFinder, /* Finder function name */
4323 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004324 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004325 dotlockClose, /* xClose method */
4326 dotlockLock, /* xLock method */
4327 dotlockUnlock, /* xUnlock method */
4328 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004329)
drh7708e972008-11-29 00:56:52 +00004330
chw78a13182009-04-07 05:35:03 +00004331#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004332IOMETHODS(
4333 flockIoFinder, /* Finder function name */
4334 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004335 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004336 flockClose, /* xClose method */
4337 flockLock, /* xLock method */
4338 flockUnlock, /* xUnlock method */
4339 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004340)
drh7708e972008-11-29 00:56:52 +00004341#endif
4342
drh6c7d5c52008-11-21 20:32:33 +00004343#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004344IOMETHODS(
4345 semIoFinder, /* Finder function name */
4346 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004347 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004348 semClose, /* xClose method */
4349 semLock, /* xLock method */
4350 semUnlock, /* xUnlock method */
4351 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004352)
aswiftaebf4132008-11-21 00:10:35 +00004353#endif
drh7708e972008-11-29 00:56:52 +00004354
drhd2cb50b2009-01-09 21:41:17 +00004355#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004356IOMETHODS(
4357 afpIoFinder, /* Finder function name */
4358 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004359 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004360 afpClose, /* xClose method */
4361 afpLock, /* xLock method */
4362 afpUnlock, /* xUnlock method */
4363 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004364)
drh715ff302008-12-03 22:32:44 +00004365#endif
4366
4367/*
4368** The proxy locking method is a "super-method" in the sense that it
4369** opens secondary file descriptors for the conch and lock files and
4370** it uses proxy, dot-file, AFP, and flock() locking methods on those
4371** secondary files. For this reason, the division that implements
4372** proxy locking is located much further down in the file. But we need
4373** to go ahead and define the sqlite3_io_methods and finder function
4374** for proxy locking here. So we forward declare the I/O methods.
4375*/
drhd2cb50b2009-01-09 21:41:17 +00004376#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004377static int proxyClose(sqlite3_file*);
4378static int proxyLock(sqlite3_file*, int);
4379static int proxyUnlock(sqlite3_file*, int);
4380static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004381IOMETHODS(
4382 proxyIoFinder, /* Finder function name */
4383 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004384 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004385 proxyClose, /* xClose method */
4386 proxyLock, /* xLock method */
4387 proxyUnlock, /* xUnlock method */
4388 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004389)
aswiftaebf4132008-11-21 00:10:35 +00004390#endif
drh7708e972008-11-29 00:56:52 +00004391
drh7ed97b92010-01-20 13:07:21 +00004392/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4393#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4394IOMETHODS(
4395 nfsIoFinder, /* Finder function name */
4396 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004397 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004398 unixClose, /* xClose method */
4399 unixLock, /* xLock method */
4400 nfsUnlock, /* xUnlock method */
4401 unixCheckReservedLock /* xCheckReservedLock method */
4402)
4403#endif
drh7708e972008-11-29 00:56:52 +00004404
drhd2cb50b2009-01-09 21:41:17 +00004405#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004406/*
drh6b9d6dd2008-12-03 19:34:47 +00004407** This "finder" function attempts to determine the best locking strategy
4408** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004409** object that implements that strategy.
4410**
4411** This is for MacOSX only.
4412*/
drh1875f7a2008-12-08 18:19:17 +00004413static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004414 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004415 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004416){
4417 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004418 const char *zFilesystem; /* Filesystem type name */
4419 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004420 } aMap[] = {
4421 { "hfs", &posixIoMethods },
4422 { "ufs", &posixIoMethods },
4423 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004424 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004425 { "webdav", &nolockIoMethods },
4426 { 0, 0 }
4427 };
4428 int i;
4429 struct statfs fsInfo;
4430 struct flock lockInfo;
4431
4432 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004433 /* If filePath==NULL that means we are dealing with a transient file
4434 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004435 return &nolockIoMethods;
4436 }
4437 if( statfs(filePath, &fsInfo) != -1 ){
4438 if( fsInfo.f_flags & MNT_RDONLY ){
4439 return &nolockIoMethods;
4440 }
4441 for(i=0; aMap[i].zFilesystem; i++){
4442 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4443 return aMap[i].pMethods;
4444 }
4445 }
4446 }
4447
4448 /* Default case. Handles, amongst others, "nfs".
4449 ** Test byte-range lock using fcntl(). If the call succeeds,
4450 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004451 */
drh7708e972008-11-29 00:56:52 +00004452 lockInfo.l_len = 1;
4453 lockInfo.l_start = 0;
4454 lockInfo.l_whence = SEEK_SET;
4455 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004456 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004457 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4458 return &nfsIoMethods;
4459 } else {
4460 return &posixIoMethods;
4461 }
drh7708e972008-11-29 00:56:52 +00004462 }else{
4463 return &dotlockIoMethods;
4464 }
4465}
drh0c2694b2009-09-03 16:23:44 +00004466static const sqlite3_io_methods
4467 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004468
drhd2cb50b2009-01-09 21:41:17 +00004469#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004470
chw78a13182009-04-07 05:35:03 +00004471#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4472/*
4473** This "finder" function attempts to determine the best locking strategy
4474** for the database file "filePath". It then returns the sqlite3_io_methods
4475** object that implements that strategy.
4476**
4477** This is for VXWorks only.
4478*/
4479static const sqlite3_io_methods *autolockIoFinderImpl(
4480 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004481 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004482){
4483 struct flock lockInfo;
4484
4485 if( !filePath ){
4486 /* If filePath==NULL that means we are dealing with a transient file
4487 ** that does not need to be locked. */
4488 return &nolockIoMethods;
4489 }
4490
4491 /* Test if fcntl() is supported and use POSIX style locks.
4492 ** Otherwise fall back to the named semaphore method.
4493 */
4494 lockInfo.l_len = 1;
4495 lockInfo.l_start = 0;
4496 lockInfo.l_whence = SEEK_SET;
4497 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004498 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004499 return &posixIoMethods;
4500 }else{
4501 return &semIoMethods;
4502 }
4503}
drh0c2694b2009-09-03 16:23:44 +00004504static const sqlite3_io_methods
4505 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004506
4507#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4508
drh7708e972008-11-29 00:56:52 +00004509/*
4510** An abstract type for a pointer to a IO method finder function:
4511*/
drh0c2694b2009-09-03 16:23:44 +00004512typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004513
aswiftaebf4132008-11-21 00:10:35 +00004514
drh734c9862008-11-28 15:37:20 +00004515/****************************************************************************
4516**************************** sqlite3_vfs methods ****************************
4517**
4518** This division contains the implementation of methods on the
4519** sqlite3_vfs object.
4520*/
4521
danielk1977a3d4c882007-03-23 10:08:38 +00004522/*
danielk1977e339d652008-06-28 11:23:00 +00004523** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004524*/
4525static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004526 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004527 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004528 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004529 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004530 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004531 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004532 int isDelete, /* Delete on close if true */
4533 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004534){
drh7708e972008-11-29 00:56:52 +00004535 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004536 unixFile *pNew = (unixFile *)pId;
4537 int rc = SQLITE_OK;
4538
drh8af6c222010-05-14 12:43:01 +00004539 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004540
dane946c392009-08-22 11:39:46 +00004541 /* Parameter isDelete is only used on vxworks. Express this explicitly
4542 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004543 */
drh7708e972008-11-29 00:56:52 +00004544 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004545
dan00157392010-10-05 11:33:15 +00004546 /* Usually the path zFilename should not be a relative pathname. The
4547 ** exception is when opening the proxy "conch" file in builds that
4548 ** include the special Apple locking styles.
4549 */
dan00157392010-10-05 11:33:15 +00004550#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004551 assert( zFilename==0 || zFilename[0]=='/'
4552 || pVfs->pAppData==(void*)&autolockIoFinder );
4553#else
4554 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004555#endif
dan00157392010-10-05 11:33:15 +00004556
drh308c2a52010-05-14 11:30:18 +00004557 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004558 pNew->h = h;
drhd9e5c4f2010-05-12 18:01:39 +00004559 pNew->zPath = zFilename;
drha7e61d82011-03-12 17:02:57 +00004560 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
4561 pNew->ctrlFlags = UNIXFILE_EXCL;
4562 }else{
4563 pNew->ctrlFlags = 0;
4564 }
drh77197112011-03-15 19:08:48 +00004565 if( isReadOnly ){
4566 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4567 }
drh0059eae2011-08-08 23:48:40 +00004568 if( syncDir ){
4569 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4570 }
drh339eb0b2008-03-07 15:34:11 +00004571
drh6c7d5c52008-11-21 20:32:33 +00004572#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004573 pNew->pId = vxworksFindFileId(zFilename);
4574 if( pNew->pId==0 ){
4575 noLock = 1;
4576 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004577 }
4578#endif
4579
drhda0e7682008-07-30 15:27:54 +00004580 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004581 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004582 }else{
drh0c2694b2009-09-03 16:23:44 +00004583 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004584#if SQLITE_ENABLE_LOCKING_STYLE
4585 /* Cache zFilename in the locking context (AFP and dotlock override) for
4586 ** proxyLock activation is possible (remote proxy is based on db name)
4587 ** zFilename remains valid until file is closed, to support */
4588 pNew->lockingContext = (void*)zFilename;
4589#endif
drhda0e7682008-07-30 15:27:54 +00004590 }
danielk1977e339d652008-06-28 11:23:00 +00004591
drh7ed97b92010-01-20 13:07:21 +00004592 if( pLockingStyle == &posixIoMethods
4593#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4594 || pLockingStyle == &nfsIoMethods
4595#endif
4596 ){
drh7708e972008-11-29 00:56:52 +00004597 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004598 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004599 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004600 /* If an error occured in findInodeInfo(), close the file descriptor
4601 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004602 ** in two scenarios:
4603 **
4604 ** (a) A call to fstat() failed.
4605 ** (b) A malloc failed.
4606 **
4607 ** Scenario (b) may only occur if the process is holding no other
4608 ** file descriptors open on the same file. If there were other file
4609 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004610 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004611 ** handle h - as it is guaranteed that no posix locks will be released
4612 ** by doing so.
4613 **
4614 ** If scenario (a) caused the error then things are not so safe. The
4615 ** implicit assumption here is that if fstat() fails, things are in
4616 ** such bad shape that dropping a lock or two doesn't matter much.
4617 */
drh0e9365c2011-03-02 02:08:13 +00004618 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004619 h = -1;
4620 }
drh7708e972008-11-29 00:56:52 +00004621 unixLeaveMutex();
4622 }
danielk1977e339d652008-06-28 11:23:00 +00004623
drhd2cb50b2009-01-09 21:41:17 +00004624#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004625 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004626 /* AFP locking uses the file path so it needs to be included in
4627 ** the afpLockingContext.
4628 */
4629 afpLockingContext *pCtx;
4630 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4631 if( pCtx==0 ){
4632 rc = SQLITE_NOMEM;
4633 }else{
4634 /* NB: zFilename exists and remains valid until the file is closed
4635 ** according to requirement F11141. So we do not need to make a
4636 ** copy of the filename. */
4637 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004638 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004639 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004640 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004641 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004642 if( rc!=SQLITE_OK ){
4643 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004644 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004645 h = -1;
4646 }
drh7708e972008-11-29 00:56:52 +00004647 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004648 }
drh7708e972008-11-29 00:56:52 +00004649 }
4650#endif
danielk1977e339d652008-06-28 11:23:00 +00004651
drh7708e972008-11-29 00:56:52 +00004652 else if( pLockingStyle == &dotlockIoMethods ){
4653 /* Dotfile locking uses the file path so it needs to be included in
4654 ** the dotlockLockingContext
4655 */
4656 char *zLockFile;
4657 int nFilename;
drhea678832008-12-10 19:26:22 +00004658 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004659 zLockFile = (char *)sqlite3_malloc(nFilename);
4660 if( zLockFile==0 ){
4661 rc = SQLITE_NOMEM;
4662 }else{
4663 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004664 }
drh7708e972008-11-29 00:56:52 +00004665 pNew->lockingContext = zLockFile;
4666 }
danielk1977e339d652008-06-28 11:23:00 +00004667
drh6c7d5c52008-11-21 20:32:33 +00004668#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004669 else if( pLockingStyle == &semIoMethods ){
4670 /* Named semaphore locking uses the file path so it needs to be
4671 ** included in the semLockingContext
4672 */
4673 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004674 rc = findInodeInfo(pNew, &pNew->pInode);
4675 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4676 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004677 int n;
drh2238dcc2009-08-27 17:56:20 +00004678 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004679 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004680 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004681 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004682 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4683 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004684 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004685 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004686 }
chw97185482008-11-17 08:05:31 +00004687 }
drh7708e972008-11-29 00:56:52 +00004688 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004689 }
drh7708e972008-11-29 00:56:52 +00004690#endif
aswift5b1a2562008-08-22 00:22:35 +00004691
4692 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004693#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004694 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004695 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004696 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004697 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004698 isDelete = 0;
4699 }
4700 pNew->isDelete = isDelete;
4701#endif
danielk1977e339d652008-06-28 11:23:00 +00004702 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004703 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004704 }else{
drh7708e972008-11-29 00:56:52 +00004705 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004706 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004707 }
danielk1977e339d652008-06-28 11:23:00 +00004708 return rc;
drh054889e2005-11-30 03:20:31 +00004709}
drh9c06c952005-11-26 00:25:00 +00004710
danielk1977ad94b582007-08-20 06:44:22 +00004711/*
drh8b3cf822010-06-01 21:02:51 +00004712** Return the name of a directory in which to put temporary files.
4713** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004714*/
drh7234c6d2010-06-19 15:10:09 +00004715static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004716 static const char *azDirs[] = {
4717 0,
aswiftaebf4132008-11-21 00:10:35 +00004718 0,
danielk197717b90b52008-06-06 11:11:25 +00004719 "/var/tmp",
4720 "/usr/tmp",
4721 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004722 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004723 };
drh8b3cf822010-06-01 21:02:51 +00004724 unsigned int i;
4725 struct stat buf;
4726 const char *zDir = 0;
4727
4728 azDirs[0] = sqlite3_temp_directory;
4729 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004730 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004731 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004732 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004733 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004734 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004735 break;
4736 }
4737 return zDir;
4738}
4739
4740/*
4741** Create a temporary file name in zBuf. zBuf must be allocated
4742** by the calling process and must be big enough to hold at least
4743** pVfs->mxPathname bytes.
4744*/
4745static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004746 static const unsigned char zChars[] =
4747 "abcdefghijklmnopqrstuvwxyz"
4748 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4749 "0123456789";
drh41022642008-11-21 00:24:42 +00004750 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004751 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004752
4753 /* It's odd to simulate an io-error here, but really this is just
4754 ** using the io-error infrastructure to test that SQLite handles this
4755 ** function failing.
4756 */
4757 SimulateIOError( return SQLITE_IOERR );
4758
drh7234c6d2010-06-19 15:10:09 +00004759 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004760 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004761
4762 /* Check that the output buffer is large enough for the temporary file
4763 ** name. If it is not, return SQLITE_ERROR.
4764 */
danielk197700e13612008-11-17 19:18:54 +00004765 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004766 return SQLITE_ERROR;
4767 }
4768
4769 do{
4770 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004771 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004772 sqlite3_randomness(15, &zBuf[j]);
4773 for(i=0; i<15; i++, j++){
4774 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4775 }
4776 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004777 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004778 return SQLITE_OK;
4779}
4780
drhd2cb50b2009-01-09 21:41:17 +00004781#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004782/*
4783** Routine to transform a unixFile into a proxy-locking unixFile.
4784** Implementation in the proxy-lock division, but used by unixOpen()
4785** if SQLITE_PREFER_PROXY_LOCKING is defined.
4786*/
4787static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004788#endif
drhc66d5b62008-12-03 22:48:32 +00004789
dan08da86a2009-08-21 17:18:03 +00004790/*
4791** Search for an unused file descriptor that was opened on the database
4792** file (not a journal or master-journal file) identified by pathname
4793** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4794** argument to this function.
4795**
4796** Such a file descriptor may exist if a database connection was closed
4797** but the associated file descriptor could not be closed because some
4798** other file descriptor open on the same file is holding a file-lock.
4799** Refer to comments in the unixClose() function and the lengthy comment
4800** describing "Posix Advisory Locking" at the start of this file for
4801** further details. Also, ticket #4018.
4802**
4803** If a suitable file descriptor is found, then it is returned. If no
4804** such file descriptor is located, -1 is returned.
4805*/
dane946c392009-08-22 11:39:46 +00004806static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4807 UnixUnusedFd *pUnused = 0;
4808
4809 /* Do not search for an unused file descriptor on vxworks. Not because
4810 ** vxworks would not benefit from the change (it might, we're not sure),
4811 ** but because no way to test it is currently available. It is better
4812 ** not to risk breaking vxworks support for the sake of such an obscure
4813 ** feature. */
4814#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004815 struct stat sStat; /* Results of stat() call */
4816
4817 /* A stat() call may fail for various reasons. If this happens, it is
4818 ** almost certain that an open() call on the same path will also fail.
4819 ** For this reason, if an error occurs in the stat() call here, it is
4820 ** ignored and -1 is returned. The caller will try to open a new file
4821 ** descriptor on the same path, fail, and return an error to SQLite.
4822 **
4823 ** Even if a subsequent open() call does succeed, the consequences of
4824 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004825 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004826 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004827
4828 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004829 pInode = inodeList;
4830 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4831 || pInode->fileId.ino!=sStat.st_ino) ){
4832 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004833 }
drh8af6c222010-05-14 12:43:01 +00004834 if( pInode ){
dane946c392009-08-22 11:39:46 +00004835 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004836 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004837 pUnused = *pp;
4838 if( pUnused ){
4839 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004840 }
4841 }
4842 unixLeaveMutex();
4843 }
dane946c392009-08-22 11:39:46 +00004844#endif /* if !OS_VXWORKS */
4845 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004846}
danielk197717b90b52008-06-06 11:11:25 +00004847
4848/*
danddb0ac42010-07-14 14:48:58 +00004849** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004850** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004851** and a value suitable for passing as the third argument to open(2) is
4852** written to *pMode. If an IO error occurs, an SQLite error code is
4853** returned and the value of *pMode is not modified.
4854**
4855** If the file being opened is a temporary file, it is always created with
4856** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004857** is a database or master journal file, it is created with the permissions
4858** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004859**
drh8ab58662010-07-15 18:38:39 +00004860** Finally, if the file being opened is a WAL or regular journal file, then
4861** this function queries the file-system for the permissions on the
4862** corresponding database file and sets *pMode to this value. Whenever
4863** possible, WAL and journal files are created using the same permissions
4864** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004865**
4866** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4867** original filename is unavailable. But 8_3_NAMES is only used for
4868** FAT filesystems and permissions do not matter there, so just use
4869** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004870*/
4871static int findCreateFileMode(
4872 const char *zPath, /* Path of file (possibly) being created */
4873 int flags, /* Flags passed as 4th argument to xOpen() */
4874 mode_t *pMode /* OUT: Permissions to open file with */
4875){
4876 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004877 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004878 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004879 char zDb[MAX_PATHNAME+1]; /* Database file path */
4880 int nDb; /* Number of valid bytes in zDb */
4881 struct stat sStat; /* Output of stat() on database file */
4882
dana0c989d2010-11-05 18:07:37 +00004883 /* zPath is a path to a WAL or journal file. The following block derives
4884 ** the path to the associated database file from zPath. This block handles
4885 ** the following naming conventions:
4886 **
4887 ** "<path to db>-journal"
4888 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004889 ** "<path to db>-journalNN"
4890 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004891 **
drh81cc5162011-05-17 20:36:21 +00004892 ** where NN is a 4 digit decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004893 ** used by the test_multiplex.c module.
4894 */
4895 nDb = sqlite3Strlen30(zPath) - 1;
drh81cc5162011-05-17 20:36:21 +00004896 while( nDb>0 && zPath[nDb]!='-' ) nDb--;
4897 if( nDb==0 ) return SQLITE_OK;
danddb0ac42010-07-14 14:48:58 +00004898 memcpy(zDb, zPath, nDb);
4899 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004900
drh58384f12011-07-28 00:14:45 +00004901 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004902 *pMode = sStat.st_mode & 0777;
4903 }else{
4904 rc = SQLITE_IOERR_FSTAT;
4905 }
4906 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4907 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004908 }
4909 return rc;
4910}
4911
4912/*
danielk1977ad94b582007-08-20 06:44:22 +00004913** Open the file zPath.
4914**
danielk1977b4b47412007-08-17 15:53:36 +00004915** Previously, the SQLite OS layer used three functions in place of this
4916** one:
4917**
4918** sqlite3OsOpenReadWrite();
4919** sqlite3OsOpenReadOnly();
4920** sqlite3OsOpenExclusive();
4921**
4922** These calls correspond to the following combinations of flags:
4923**
4924** ReadWrite() -> (READWRITE | CREATE)
4925** ReadOnly() -> (READONLY)
4926** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4927**
4928** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4929** true, the file was configured to be automatically deleted when the
4930** file handle closed. To achieve the same effect using this new
4931** interface, add the DELETEONCLOSE flag to those specified above for
4932** OpenExclusive().
4933*/
4934static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004935 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4936 const char *zPath, /* Pathname of file to be opened */
4937 sqlite3_file *pFile, /* The file descriptor to be filled in */
4938 int flags, /* Input flags to control the opening */
4939 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004940){
dan08da86a2009-08-21 17:18:03 +00004941 unixFile *p = (unixFile *)pFile;
4942 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004943 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004944 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004945 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004946 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004947
4948 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4949 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4950 int isCreate = (flags & SQLITE_OPEN_CREATE);
4951 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4952 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004953#if SQLITE_ENABLE_LOCKING_STYLE
4954 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4955#endif
danielk1977b4b47412007-08-17 15:53:36 +00004956
danielk1977fee2d252007-08-18 10:59:19 +00004957 /* If creating a master or main-file journal, this function will open
4958 ** a file-descriptor on the directory too. The first time unixSync()
4959 ** is called the directory file descriptor will be fsync()ed and close()d.
4960 */
drh0059eae2011-08-08 23:48:40 +00004961 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00004962 eType==SQLITE_OPEN_MASTER_JOURNAL
4963 || eType==SQLITE_OPEN_MAIN_JOURNAL
4964 || eType==SQLITE_OPEN_WAL
4965 ));
danielk1977fee2d252007-08-18 10:59:19 +00004966
danielk197717b90b52008-06-06 11:11:25 +00004967 /* If argument zPath is a NULL pointer, this function is required to open
4968 ** a temporary file. Use this buffer to store the file name in.
4969 */
4970 char zTmpname[MAX_PATHNAME+1];
4971 const char *zName = zPath;
4972
danielk1977fee2d252007-08-18 10:59:19 +00004973 /* Check the following statements are true:
4974 **
4975 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
4976 ** (b) if CREATE is set, then READWRITE must also be set, and
4977 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00004978 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00004979 */
danielk1977b4b47412007-08-17 15:53:36 +00004980 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00004981 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00004982 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00004983 assert(isDelete==0 || isCreate);
4984
danddb0ac42010-07-14 14:48:58 +00004985 /* The main DB, main journal, WAL file and master journal are never
4986 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00004987 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
4988 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
4989 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00004990 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00004991
danielk1977fee2d252007-08-18 10:59:19 +00004992 /* Assert that the upper layer has set one of the "file-type" flags. */
4993 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
4994 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
4995 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00004996 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00004997 );
4998
dan08da86a2009-08-21 17:18:03 +00004999 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005000
dan08da86a2009-08-21 17:18:03 +00005001 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005002 UnixUnusedFd *pUnused;
5003 pUnused = findReusableFd(zName, flags);
5004 if( pUnused ){
5005 fd = pUnused->fd;
5006 }else{
dan6aa657f2009-08-24 18:57:58 +00005007 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005008 if( !pUnused ){
5009 return SQLITE_NOMEM;
5010 }
5011 }
5012 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005013 }else if( !zName ){
5014 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005015 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005016 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005017 if( rc!=SQLITE_OK ){
5018 return rc;
5019 }
5020 zName = zTmpname;
5021 }
5022
dan08da86a2009-08-21 17:18:03 +00005023 /* Determine the value of the flags parameter passed to POSIX function
5024 ** open(). These must be calculated even if open() is not called, as
5025 ** they may be stored as part of the file handle and used by the
5026 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005027 if( isReadonly ) openFlags |= O_RDONLY;
5028 if( isReadWrite ) openFlags |= O_RDWR;
5029 if( isCreate ) openFlags |= O_CREAT;
5030 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5031 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005032
danielk1977b4b47412007-08-17 15:53:36 +00005033 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005034 mode_t openMode; /* Permissions to create file with */
5035 rc = findCreateFileMode(zName, flags, &openMode);
5036 if( rc!=SQLITE_OK ){
5037 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005038 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005039 return rc;
5040 }
drhad4f1e52011-03-04 15:43:57 +00005041 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005042 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005043 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5044 /* Failed to open the file for read/write access. Try read-only. */
5045 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005046 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005047 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005048 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005049 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005050 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005051 }
5052 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005053 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005054 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005055 }
danielk1977b4b47412007-08-17 15:53:36 +00005056 }
dan08da86a2009-08-21 17:18:03 +00005057 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005058 if( pOutFlags ){
5059 *pOutFlags = flags;
5060 }
5061
dane946c392009-08-22 11:39:46 +00005062 if( p->pUnused ){
5063 p->pUnused->fd = fd;
5064 p->pUnused->flags = flags;
5065 }
5066
danielk1977b4b47412007-08-17 15:53:36 +00005067 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005068#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005069 zPath = zName;
5070#else
drh036ac7f2011-08-08 23:18:05 +00005071 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005072#endif
danielk1977b4b47412007-08-17 15:53:36 +00005073 }
drh41022642008-11-21 00:24:42 +00005074#if SQLITE_ENABLE_LOCKING_STYLE
5075 else{
dan08da86a2009-08-21 17:18:03 +00005076 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005077 }
5078#endif
5079
danielk1977e339d652008-06-28 11:23:00 +00005080#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005081 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005082#endif
5083
drhda0e7682008-07-30 15:27:54 +00005084 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005085
drh7ed97b92010-01-20 13:07:21 +00005086
5087#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5088 struct statfs fsInfo;
5089 if( fstatfs(fd, &fsInfo) == -1 ){
5090 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005091 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005092 return SQLITE_IOERR_ACCESS;
5093 }
5094 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5095 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5096 }
5097#endif
5098
5099#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005100#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005101 isAutoProxy = 1;
5102#endif
5103 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005104 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5105 int useProxy = 0;
5106
dan08da86a2009-08-21 17:18:03 +00005107 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5108 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005109 if( envforce!=NULL ){
5110 useProxy = atoi(envforce)>0;
5111 }else{
5112 struct statfs fsInfo;
aswiftaebf4132008-11-21 00:10:35 +00005113 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005114 /* In theory, the close(fd) call is sub-optimal. If the file opened
5115 ** with fd is a database file, and there are other connections open
5116 ** on that file that are currently holding advisory locks on it,
5117 ** then the call to close() will cancel those locks. In practice,
5118 ** we're assuming that statfs() doesn't fail very often. At least
5119 ** not while other file descriptors opened by the same process on
5120 ** the same file are working. */
5121 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005122 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005123 rc = SQLITE_IOERR_ACCESS;
5124 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005125 }
5126 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5127 }
5128 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005129 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005130 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005131 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005132 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005133 if( rc!=SQLITE_OK ){
5134 /* Use unixClose to clean up the resources added in fillInUnixFile
5135 ** and clear all the structure's references. Specifically,
5136 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5137 */
5138 unixClose(pFile);
5139 return rc;
5140 }
aswiftaebf4132008-11-21 00:10:35 +00005141 }
dane946c392009-08-22 11:39:46 +00005142 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005143 }
5144 }
5145#endif
5146
drh0059eae2011-08-08 23:48:40 +00005147 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005148 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005149open_finished:
5150 if( rc!=SQLITE_OK ){
5151 sqlite3_free(p->pUnused);
5152 }
5153 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005154}
5155
dane946c392009-08-22 11:39:46 +00005156
danielk1977b4b47412007-08-17 15:53:36 +00005157/*
danielk1977fee2d252007-08-18 10:59:19 +00005158** Delete the file at zPath. If the dirSync argument is true, fsync()
5159** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005160*/
drh6b9d6dd2008-12-03 19:34:47 +00005161static int unixDelete(
5162 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5163 const char *zPath, /* Name of file to be deleted */
5164 int dirSync /* If true, fsync() directory after deleting file */
5165){
danielk1977fee2d252007-08-18 10:59:19 +00005166 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005167 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005168 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005169 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005170 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005171 }
danielk1977d39fa702008-10-16 13:27:40 +00005172#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005173 if( dirSync ){
5174 int fd;
drh90315a22011-08-10 01:52:12 +00005175 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005176 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005177#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005178 if( fsync(fd)==-1 )
5179#else
5180 if( fsync(fd) )
5181#endif
5182 {
dane18d4952011-02-21 11:46:24 +00005183 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005184 }
drh0e9365c2011-03-02 02:08:13 +00005185 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005186 }else if( rc==SQLITE_CANTOPEN ){
5187 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005188 }
5189 }
danielk1977d138dd82008-10-15 16:02:48 +00005190#endif
danielk1977fee2d252007-08-18 10:59:19 +00005191 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005192}
5193
danielk197790949c22007-08-17 16:50:38 +00005194/*
5195** Test the existance of or access permissions of file zPath. The
5196** test performed depends on the value of flags:
5197**
5198** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5199** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5200** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5201**
5202** Otherwise return 0.
5203*/
danielk1977861f7452008-06-05 11:39:11 +00005204static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005205 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5206 const char *zPath, /* Path of the file to examine */
5207 int flags, /* What do we want to learn about the zPath file? */
5208 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005209){
rse25c0d1a2007-09-20 08:38:14 +00005210 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005211 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005212 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005213 switch( flags ){
5214 case SQLITE_ACCESS_EXISTS:
5215 amode = F_OK;
5216 break;
5217 case SQLITE_ACCESS_READWRITE:
5218 amode = W_OK|R_OK;
5219 break;
drh50d3f902007-08-27 21:10:36 +00005220 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005221 amode = R_OK;
5222 break;
5223
5224 default:
5225 assert(!"Invalid flags argument");
5226 }
drh99ab3b12011-03-02 15:09:07 +00005227 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005228 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5229 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005230 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005231 *pResOut = 0;
5232 }
5233 }
danielk1977861f7452008-06-05 11:39:11 +00005234 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005235}
5236
danielk1977b4b47412007-08-17 15:53:36 +00005237
5238/*
5239** Turn a relative pathname into a full pathname. The relative path
5240** is stored as a nul-terminated string in the buffer pointed to by
5241** zPath.
5242**
5243** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5244** (in this case, MAX_PATHNAME bytes). The full-path is written to
5245** this buffer before returning.
5246*/
danielk1977adfb9b02007-09-17 07:02:56 +00005247static int unixFullPathname(
5248 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5249 const char *zPath, /* Possibly relative input path */
5250 int nOut, /* Size of output buffer in bytes */
5251 char *zOut /* Output buffer */
5252){
danielk1977843e65f2007-09-01 16:16:15 +00005253
5254 /* It's odd to simulate an io-error here, but really this is just
5255 ** using the io-error infrastructure to test that SQLite handles this
5256 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005257 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005258 */
5259 SimulateIOError( return SQLITE_ERROR );
5260
drh153c62c2007-08-24 03:51:33 +00005261 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005262 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005263
drh3c7f2dc2007-12-06 13:26:20 +00005264 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005265 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005266 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005267 }else{
5268 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005269 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005270 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005271 }
drhea678832008-12-10 19:26:22 +00005272 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005273 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005274 }
5275 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005276}
5277
drh0ccebe72005-06-07 22:22:50 +00005278
drh761df872006-12-21 01:29:22 +00005279#ifndef SQLITE_OMIT_LOAD_EXTENSION
5280/*
5281** Interfaces for opening a shared library, finding entry points
5282** within the shared library, and closing the shared library.
5283*/
5284#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005285static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5286 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005287 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5288}
danielk197795c8a542007-09-01 06:51:27 +00005289
5290/*
5291** SQLite calls this function immediately after a call to unixDlSym() or
5292** unixDlOpen() fails (returns a null pointer). If a more detailed error
5293** message is available, it is written to zBufOut. If no error message
5294** is available, zBufOut is left unmodified and SQLite uses a default
5295** error message.
5296*/
danielk1977397d65f2008-11-19 11:35:39 +00005297static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005298 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005299 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005300 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005301 zErr = dlerror();
5302 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005303 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005304 }
drh6c7d5c52008-11-21 20:32:33 +00005305 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005306}
drh1875f7a2008-12-08 18:19:17 +00005307static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5308 /*
5309 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5310 ** cast into a pointer to a function. And yet the library dlsym() routine
5311 ** returns a void* which is really a pointer to a function. So how do we
5312 ** use dlsym() with -pedantic-errors?
5313 **
5314 ** Variable x below is defined to be a pointer to a function taking
5315 ** parameters void* and const char* and returning a pointer to a function.
5316 ** We initialize x by assigning it a pointer to the dlsym() function.
5317 ** (That assignment requires a cast.) Then we call the function that
5318 ** x points to.
5319 **
5320 ** This work-around is unlikely to work correctly on any system where
5321 ** you really cannot cast a function pointer into void*. But then, on the
5322 ** other hand, dlsym() will not work on such a system either, so we have
5323 ** not really lost anything.
5324 */
5325 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005326 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005327 x = (void(*(*)(void*,const char*))(void))dlsym;
5328 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005329}
danielk1977397d65f2008-11-19 11:35:39 +00005330static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5331 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005332 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005333}
danielk1977b4b47412007-08-17 15:53:36 +00005334#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5335 #define unixDlOpen 0
5336 #define unixDlError 0
5337 #define unixDlSym 0
5338 #define unixDlClose 0
5339#endif
5340
5341/*
danielk197790949c22007-08-17 16:50:38 +00005342** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005343*/
danielk1977397d65f2008-11-19 11:35:39 +00005344static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5345 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005346 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005347
drhbbd42a62004-05-22 17:41:58 +00005348 /* We have to initialize zBuf to prevent valgrind from reporting
5349 ** errors. The reports issued by valgrind are incorrect - we would
5350 ** prefer that the randomness be increased by making use of the
5351 ** uninitialized space in zBuf - but valgrind errors tend to worry
5352 ** some users. Rather than argue, it seems easier just to initialize
5353 ** the whole array and silence valgrind, even if that means less randomness
5354 ** in the random seed.
5355 **
5356 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005357 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005358 ** tests repeatable.
5359 */
danielk1977b4b47412007-08-17 15:53:36 +00005360 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005361#if !defined(SQLITE_TEST)
5362 {
drh842b8642005-01-21 17:53:17 +00005363 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005364 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005365 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005366 time_t t;
5367 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005368 memcpy(zBuf, &t, sizeof(t));
5369 pid = getpid();
5370 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005371 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005372 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005373 }else{
drhe562be52011-03-02 18:01:10 +00005374 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005375 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005376 }
drhbbd42a62004-05-22 17:41:58 +00005377 }
5378#endif
drh72cbd072008-10-14 17:58:38 +00005379 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005380}
5381
danielk1977b4b47412007-08-17 15:53:36 +00005382
drhbbd42a62004-05-22 17:41:58 +00005383/*
5384** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005385** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005386** The return value is the number of microseconds of sleep actually
5387** requested from the underlying operating system, a number which
5388** might be greater than or equal to the argument, but not less
5389** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005390*/
danielk1977397d65f2008-11-19 11:35:39 +00005391static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005392#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005393 struct timespec sp;
5394
5395 sp.tv_sec = microseconds / 1000000;
5396 sp.tv_nsec = (microseconds % 1000000) * 1000;
5397 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005398 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005399 return microseconds;
5400#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005401 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005402 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005403 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005404#else
danielk1977b4b47412007-08-17 15:53:36 +00005405 int seconds = (microseconds+999999)/1000000;
5406 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005407 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005408 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005409#endif
drh88f474a2006-01-02 20:00:12 +00005410}
5411
5412/*
drh6b9d6dd2008-12-03 19:34:47 +00005413** The following variable, if set to a non-zero value, is interpreted as
5414** the number of seconds since 1970 and is used to set the result of
5415** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005416*/
5417#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005418int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005419#endif
5420
5421/*
drhb7e8ea22010-05-03 14:32:30 +00005422** Find the current time (in Universal Coordinated Time). Write into *piNow
5423** the current time and date as a Julian Day number times 86_400_000. In
5424** other words, write into *piNow the number of milliseconds since the Julian
5425** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5426** proleptic Gregorian calendar.
5427**
5428** On success, return 0. Return 1 if the time and date cannot be found.
5429*/
5430static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5431 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
5432#if defined(NO_GETTOD)
5433 time_t t;
5434 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005435 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005436#elif OS_VXWORKS
5437 struct timespec sNow;
5438 clock_gettime(CLOCK_REALTIME, &sNow);
5439 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5440#else
5441 struct timeval sNow;
5442 gettimeofday(&sNow, 0);
5443 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5444#endif
5445
5446#ifdef SQLITE_TEST
5447 if( sqlite3_current_time ){
5448 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5449 }
5450#endif
5451 UNUSED_PARAMETER(NotUsed);
5452 return 0;
5453}
5454
5455/*
drhbbd42a62004-05-22 17:41:58 +00005456** Find the current time (in Universal Coordinated Time). Write the
5457** current time and date as a Julian Day number into *prNow and
5458** return 0. Return 1 if the time and date cannot be found.
5459*/
danielk1977397d65f2008-11-19 11:35:39 +00005460static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb7e8ea22010-05-03 14:32:30 +00005461 sqlite3_int64 i;
drhff828942010-06-26 21:34:06 +00005462 UNUSED_PARAMETER(NotUsed);
drhb7e8ea22010-05-03 14:32:30 +00005463 unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005464 *prNow = i/86400000.0;
drhbbd42a62004-05-22 17:41:58 +00005465 return 0;
5466}
danielk1977b4b47412007-08-17 15:53:36 +00005467
drh6b9d6dd2008-12-03 19:34:47 +00005468/*
5469** We added the xGetLastError() method with the intention of providing
5470** better low-level error messages when operating-system problems come up
5471** during SQLite operation. But so far, none of that has been implemented
5472** in the core. So this routine is never called. For now, it is merely
5473** a place-holder.
5474*/
danielk1977397d65f2008-11-19 11:35:39 +00005475static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5476 UNUSED_PARAMETER(NotUsed);
5477 UNUSED_PARAMETER(NotUsed2);
5478 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005479 return 0;
5480}
5481
drhf2424c52010-04-26 00:04:55 +00005482
5483/*
drh734c9862008-11-28 15:37:20 +00005484************************ End of sqlite3_vfs methods ***************************
5485******************************************************************************/
5486
drh715ff302008-12-03 22:32:44 +00005487/******************************************************************************
5488************************** Begin Proxy Locking ********************************
5489**
5490** Proxy locking is a "uber-locking-method" in this sense: It uses the
5491** other locking methods on secondary lock files. Proxy locking is a
5492** meta-layer over top of the primitive locking implemented above. For
5493** this reason, the division that implements of proxy locking is deferred
5494** until late in the file (here) after all of the other I/O methods have
5495** been defined - so that the primitive locking methods are available
5496** as services to help with the implementation of proxy locking.
5497**
5498****
5499**
5500** The default locking schemes in SQLite use byte-range locks on the
5501** database file to coordinate safe, concurrent access by multiple readers
5502** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5503** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5504** as POSIX read & write locks over fixed set of locations (via fsctl),
5505** on AFP and SMB only exclusive byte-range locks are available via fsctl
5506** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5507** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5508** address in the shared range is taken for a SHARED lock, the entire
5509** shared range is taken for an EXCLUSIVE lock):
5510**
5511** PENDING_BYTE 0x40000000
5512** RESERVED_BYTE 0x40000001
5513** SHARED_RANGE 0x40000002 -> 0x40000200
5514**
5515** This works well on the local file system, but shows a nearly 100x
5516** slowdown in read performance on AFP because the AFP client disables
5517** the read cache when byte-range locks are present. Enabling the read
5518** cache exposes a cache coherency problem that is present on all OS X
5519** supported network file systems. NFS and AFP both observe the
5520** close-to-open semantics for ensuring cache coherency
5521** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5522** address the requirements for concurrent database access by multiple
5523** readers and writers
5524** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5525**
5526** To address the performance and cache coherency issues, proxy file locking
5527** changes the way database access is controlled by limiting access to a
5528** single host at a time and moving file locks off of the database file
5529** and onto a proxy file on the local file system.
5530**
5531**
5532** Using proxy locks
5533** -----------------
5534**
5535** C APIs
5536**
5537** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5538** <proxy_path> | ":auto:");
5539** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5540**
5541**
5542** SQL pragmas
5543**
5544** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5545** PRAGMA [database.]lock_proxy_file
5546**
5547** Specifying ":auto:" means that if there is a conch file with a matching
5548** host ID in it, the proxy path in the conch file will be used, otherwise
5549** a proxy path based on the user's temp dir
5550** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5551** actual proxy file name is generated from the name and path of the
5552** database file. For example:
5553**
5554** For database path "/Users/me/foo.db"
5555** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5556**
5557** Once a lock proxy is configured for a database connection, it can not
5558** be removed, however it may be switched to a different proxy path via
5559** the above APIs (assuming the conch file is not being held by another
5560** connection or process).
5561**
5562**
5563** How proxy locking works
5564** -----------------------
5565**
5566** Proxy file locking relies primarily on two new supporting files:
5567**
5568** * conch file to limit access to the database file to a single host
5569** at a time
5570**
5571** * proxy file to act as a proxy for the advisory locks normally
5572** taken on the database
5573**
5574** The conch file - to use a proxy file, sqlite must first "hold the conch"
5575** by taking an sqlite-style shared lock on the conch file, reading the
5576** contents and comparing the host's unique host ID (see below) and lock
5577** proxy path against the values stored in the conch. The conch file is
5578** stored in the same directory as the database file and the file name
5579** is patterned after the database file name as ".<databasename>-conch".
5580** If the conch file does not exist, or it's contents do not match the
5581** host ID and/or proxy path, then the lock is escalated to an exclusive
5582** lock and the conch file contents is updated with the host ID and proxy
5583** path and the lock is downgraded to a shared lock again. If the conch
5584** is held by another process (with a shared lock), the exclusive lock
5585** will fail and SQLITE_BUSY is returned.
5586**
5587** The proxy file - a single-byte file used for all advisory file locks
5588** normally taken on the database file. This allows for safe sharing
5589** of the database file for multiple readers and writers on the same
5590** host (the conch ensures that they all use the same local lock file).
5591**
drh715ff302008-12-03 22:32:44 +00005592** Requesting the lock proxy does not immediately take the conch, it is
5593** only taken when the first request to lock database file is made.
5594** This matches the semantics of the traditional locking behavior, where
5595** opening a connection to a database file does not take a lock on it.
5596** The shared lock and an open file descriptor are maintained until
5597** the connection to the database is closed.
5598**
5599** The proxy file and the lock file are never deleted so they only need
5600** to be created the first time they are used.
5601**
5602** Configuration options
5603** ---------------------
5604**
5605** SQLITE_PREFER_PROXY_LOCKING
5606**
5607** Database files accessed on non-local file systems are
5608** automatically configured for proxy locking, lock files are
5609** named automatically using the same logic as
5610** PRAGMA lock_proxy_file=":auto:"
5611**
5612** SQLITE_PROXY_DEBUG
5613**
5614** Enables the logging of error messages during host id file
5615** retrieval and creation
5616**
drh715ff302008-12-03 22:32:44 +00005617** LOCKPROXYDIR
5618**
5619** Overrides the default directory used for lock proxy files that
5620** are named automatically via the ":auto:" setting
5621**
5622** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5623**
5624** Permissions to use when creating a directory for storing the
5625** lock proxy files, only used when LOCKPROXYDIR is not set.
5626**
5627**
5628** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5629** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5630** force proxy locking to be used for every database file opened, and 0
5631** will force automatic proxy locking to be disabled for all database
5632** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5633** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5634*/
5635
5636/*
5637** Proxy locking is only available on MacOSX
5638*/
drhd2cb50b2009-01-09 21:41:17 +00005639#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005640
drh715ff302008-12-03 22:32:44 +00005641/*
5642** The proxyLockingContext has the path and file structures for the remote
5643** and local proxy files in it
5644*/
5645typedef struct proxyLockingContext proxyLockingContext;
5646struct proxyLockingContext {
5647 unixFile *conchFile; /* Open conch file */
5648 char *conchFilePath; /* Name of the conch file */
5649 unixFile *lockProxy; /* Open proxy lock file */
5650 char *lockProxyPath; /* Name of the proxy lock file */
5651 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005652 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005653 void *oldLockingContext; /* Original lockingcontext to restore on close */
5654 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5655};
5656
drh7ed97b92010-01-20 13:07:21 +00005657/*
5658** The proxy lock file path for the database at dbPath is written into lPath,
5659** which must point to valid, writable memory large enough for a maxLen length
5660** file path.
drh715ff302008-12-03 22:32:44 +00005661*/
drh715ff302008-12-03 22:32:44 +00005662static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5663 int len;
5664 int dbLen;
5665 int i;
5666
5667#ifdef LOCKPROXYDIR
5668 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5669#else
5670# ifdef _CS_DARWIN_USER_TEMP_DIR
5671 {
drh7ed97b92010-01-20 13:07:21 +00005672 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005673 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5674 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005675 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005676 }
drh7ed97b92010-01-20 13:07:21 +00005677 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005678 }
5679# else
5680 len = strlcpy(lPath, "/tmp/", maxLen);
5681# endif
5682#endif
5683
5684 if( lPath[len-1]!='/' ){
5685 len = strlcat(lPath, "/", maxLen);
5686 }
5687
5688 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005689 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005690 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005691 char c = dbPath[i];
5692 lPath[i+len] = (c=='/')?'_':c;
5693 }
5694 lPath[i+len]='\0';
5695 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005696 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005697 return SQLITE_OK;
5698}
5699
drh7ed97b92010-01-20 13:07:21 +00005700/*
5701 ** Creates the lock file and any missing directories in lockPath
5702 */
5703static int proxyCreateLockPath(const char *lockPath){
5704 int i, len;
5705 char buf[MAXPATHLEN];
5706 int start = 0;
5707
5708 assert(lockPath!=NULL);
5709 /* try to create all the intermediate directories */
5710 len = (int)strlen(lockPath);
5711 buf[0] = lockPath[0];
5712 for( i=1; i<len; i++ ){
5713 if( lockPath[i] == '/' && (i - start > 0) ){
5714 /* only mkdir if leaf dir != "." or "/" or ".." */
5715 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5716 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5717 buf[i]='\0';
5718 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5719 int err=errno;
5720 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005721 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005722 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005723 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005724 return err;
5725 }
5726 }
5727 }
5728 start=i+1;
5729 }
5730 buf[i] = lockPath[i];
5731 }
drh308c2a52010-05-14 11:30:18 +00005732 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005733 return 0;
5734}
5735
drh715ff302008-12-03 22:32:44 +00005736/*
5737** Create a new VFS file descriptor (stored in memory obtained from
5738** sqlite3_malloc) and open the file named "path" in the file descriptor.
5739**
5740** The caller is responsible not only for closing the file descriptor
5741** but also for freeing the memory associated with the file descriptor.
5742*/
drh7ed97b92010-01-20 13:07:21 +00005743static int proxyCreateUnixFile(
5744 const char *path, /* path for the new unixFile */
5745 unixFile **ppFile, /* unixFile created and returned by ref */
5746 int islockfile /* if non zero missing dirs will be created */
5747) {
5748 int fd = -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
drh0059eae2011-08-08 23:48:40 +00005813 rc = fillInUnixFile(&dummyVfs, fd, 0, (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] */
drh90315a22011-08-10 01:52:12 +00006750 assert( ArraySize(aSyscall)==18 );
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 */