blob: 5378f862e90cf3979d2169f70d6bfbbd8206f36a [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
drh1da88f02011-12-17 16:09:16 +0000125#ifndef MISSING_STATVFS
126#include <sys/statvfs.h>
127#endif
128
danielk1977e339d652008-06-28 11:23:00 +0000129
drh40bbb0a2008-09-23 10:23:26 +0000130#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000131# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000132# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000133# include <semaphore.h>
134# include <limits.h>
135# else
drh9b35ea62008-11-29 02:20:26 +0000136# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000137# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000138# endif
drhbfe66312006-10-03 17:40:40 +0000139#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000140
drhf8b4d8c2010-03-05 13:53:22 +0000141#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000142# include <sys/mount.h>
143#endif
144
drhdbe4b882011-06-20 18:00:17 +0000145#ifdef HAVE_UTIME
146# include <utime.h>
147#endif
148
drh9cbe6352005-11-29 03:13:21 +0000149/*
drh7ed97b92010-01-20 13:07:21 +0000150** Allowed values of unixFile.fsFlags
151*/
152#define SQLITE_FSFLAGS_IS_MSDOS 0x1
153
154/*
drhf1a221e2006-01-15 17:27:17 +0000155** If we are to be thread-safe, include the pthreads header and define
156** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000157*/
drhd677b3d2007-08-20 22:48:41 +0000158#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000159# include <pthread.h>
160# define SQLITE_UNIX_THREADS 1
161#endif
162
163/*
164** Default permissions when creating a new file
165*/
166#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
167# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
168#endif
169
danielk1977b4b47412007-08-17 15:53:36 +0000170/*
aswiftaebf4132008-11-21 00:10:35 +0000171 ** Default permissions when creating auto proxy dir
172 */
173#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
174# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
175#endif
176
177/*
danielk1977b4b47412007-08-17 15:53:36 +0000178** Maximum supported path-length.
179*/
180#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000181
drh734c9862008-11-28 15:37:20 +0000182/*
drh734c9862008-11-28 15:37:20 +0000183** Only set the lastErrno if the error code is a real error and not
184** a normal expected return code of SQLITE_BUSY or SQLITE_OK
185*/
186#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
187
drhd91c68f2010-05-14 14:52:25 +0000188/* Forward references */
189typedef struct unixShm unixShm; /* Connection shared memory */
190typedef struct unixShmNode unixShmNode; /* Shared memory instance */
191typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
192typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000193
194/*
dane946c392009-08-22 11:39:46 +0000195** Sometimes, after a file handle is closed by SQLite, the file descriptor
196** cannot be closed immediately. In these cases, instances of the following
197** structure are used to store the file descriptor while waiting for an
198** opportunity to either close or reuse it.
199*/
dane946c392009-08-22 11:39:46 +0000200struct UnixUnusedFd {
201 int fd; /* File descriptor to close */
202 int flags; /* Flags this file descriptor was opened with */
203 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
204};
205
206/*
drh9b35ea62008-11-29 02:20:26 +0000207** The unixFile structure is subclass of sqlite3_file specific to the unix
208** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000209*/
drh054889e2005-11-30 03:20:31 +0000210typedef struct unixFile unixFile;
211struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000212 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000213 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000214 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000215 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000216 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000217 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drhf12b3f62011-12-21 14:42:29 +0000218 unsigned char szSector; /* Sectorsize/512 */
drh8af6c222010-05-14 12:43:01 +0000219 int lastErrno; /* The unix errno from last I/O error */
220 void *lockingContext; /* Locking style specific state */
221 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000222 const char *zPath; /* Name of the file */
223 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000224 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000225#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000226 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000227#endif
drh7ed97b92010-01-20 13:07:21 +0000228#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000229 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000230#endif
231#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000232 int isDelete; /* Delete on close if true */
233 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000234#endif
drh8f941bc2009-01-14 23:03:40 +0000235#ifndef NDEBUG
236 /* The next group of variables are used to track whether or not the
237 ** transaction counter in bytes 24-27 of database files are updated
238 ** whenever any part of the database changes. An assertion fault will
239 ** occur if a file is updated without also updating the transaction
240 ** counter. This test is made to avoid new problems similar to the
241 ** one described by ticket #3584.
242 */
243 unsigned char transCntrChng; /* True if the transaction counter changed */
244 unsigned char dbUpdate; /* True if any part of database file changed */
245 unsigned char inNormalWrite; /* True if in a normal write operation */
246#endif
danielk1977967a4a12007-08-20 14:23:44 +0000247#ifdef SQLITE_TEST
248 /* In test mode, increase the size of this structure a bit so that
249 ** it is larger than the struct CrashFile defined in test6.c.
250 */
251 char aPadding[32];
252#endif
drh9cbe6352005-11-29 03:13:21 +0000253};
254
drh0ccebe72005-06-07 22:22:50 +0000255/*
drha7e61d82011-03-12 17:02:57 +0000256** Allowed values for the unixFile.ctrlFlags bitmask:
257*/
drhf0b190d2011-07-26 16:03:07 +0000258#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
259#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
260#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000261#ifndef SQLITE_DISABLE_DIRSYNC
262# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
263#else
264# define UNIXFILE_DIRSYNC 0x00
265#endif
drhf12b3f62011-12-21 14:42:29 +0000266#define UNIXFILE_ZERO_DAMAGE 0x10 /* True if SQLITE_IOCAP_ZERO_DAMAGE */
drha7e61d82011-03-12 17:02:57 +0000267
268/*
drh198bf392006-01-06 21:52:49 +0000269** Include code that is common to all os_*.c files
270*/
271#include "os_common.h"
272
273/*
drh0ccebe72005-06-07 22:22:50 +0000274** Define various macros that are missing from some systems.
275*/
drhbbd42a62004-05-22 17:41:58 +0000276#ifndef O_LARGEFILE
277# define O_LARGEFILE 0
278#endif
279#ifdef SQLITE_DISABLE_LFS
280# undef O_LARGEFILE
281# define O_LARGEFILE 0
282#endif
283#ifndef O_NOFOLLOW
284# define O_NOFOLLOW 0
285#endif
286#ifndef O_BINARY
287# define O_BINARY 0
288#endif
289
290/*
drh2b4b5962005-06-15 17:47:55 +0000291** The threadid macro resolves to the thread-id or to 0. Used for
292** testing and debugging only.
293*/
drhd677b3d2007-08-20 22:48:41 +0000294#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000295#define threadid pthread_self()
296#else
297#define threadid 0
298#endif
299
drh99ab3b12011-03-02 15:09:07 +0000300/*
drh9a3baf12011-04-25 18:01:27 +0000301** Different Unix systems declare open() in different ways. Same use
302** open(const char*,int,mode_t). Others use open(const char*,int,...).
303** The difference is important when using a pointer to the function.
304**
305** The safest way to deal with the problem is to always use this wrapper
306** which always has the same well-defined interface.
307*/
308static int posixOpen(const char *zFile, int flags, int mode){
309 return open(zFile, flags, mode);
310}
311
drh90315a22011-08-10 01:52:12 +0000312/* Forward reference */
313static int openDirectory(const char*, int*);
314
drh9a3baf12011-04-25 18:01:27 +0000315/*
drh99ab3b12011-03-02 15:09:07 +0000316** Many system calls are accessed through pointer-to-functions so that
317** they may be overridden at runtime to facilitate fault injection during
318** testing and sandboxing. The following array holds the names and pointers
319** to all overrideable system calls.
320*/
321static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000322 const char *zName; /* Name of the sytem call */
323 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
324 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000325} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000326 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
327#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000328
drh58ad5802011-03-23 22:02:23 +0000329 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000330#define osClose ((int(*)(int))aSyscall[1].pCurrent)
331
drh58ad5802011-03-23 22:02:23 +0000332 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000333#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
334
drh58ad5802011-03-23 22:02:23 +0000335 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000336#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
337
drh58ad5802011-03-23 22:02:23 +0000338 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000339#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
340
341/*
342** The DJGPP compiler environment looks mostly like Unix, but it
343** lacks the fcntl() system call. So redefine fcntl() to be something
344** that always succeeds. This means that locking does not occur under
345** DJGPP. But it is DOS - what did you expect?
346*/
347#ifdef __DJGPP__
348 { "fstat", 0, 0 },
349#define osFstat(a,b,c) 0
350#else
drh58ad5802011-03-23 22:02:23 +0000351 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
353#endif
354
drh58ad5802011-03-23 22:02:23 +0000355 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000356#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
357
drh58ad5802011-03-23 22:02:23 +0000358 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000359#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000360
drh58ad5802011-03-23 22:02:23 +0000361 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000362#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
363
drhd4a80312011-04-15 14:33:20 +0000364#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000365 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000366#else
drh58ad5802011-03-23 22:02:23 +0000367 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000368#endif
369#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
370
371#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000372 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000373#else
drh58ad5802011-03-23 22:02:23 +0000374 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000375#endif
376#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
377
drh58ad5802011-03-23 22:02:23 +0000378 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000379#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
380
drhd4a80312011-04-15 14:33:20 +0000381#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000382 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000383#else
drh58ad5802011-03-23 22:02:23 +0000384 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000385#endif
386#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
387 aSyscall[12].pCurrent)
388
389#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000390 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000393#endif
394#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
395 aSyscall[13].pCurrent)
396
drha6c47492011-04-11 18:35:09 +0000397#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000398 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000399#else
400 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000401#endif
drh2aa5a002011-04-13 13:42:25 +0000402#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000403
404#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000405 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000406#else
drh58ad5802011-03-23 22:02:23 +0000407 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000408#endif
dan0fd7d862011-03-29 10:04:23 +0000409#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000410
drh036ac7f2011-08-08 23:18:05 +0000411 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
412#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
413
drh90315a22011-08-10 01:52:12 +0000414 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
415#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
416
drh9ef6bc42011-11-04 02:24:02 +0000417 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
418#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
419
420 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
421#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
422
drh1da88f02011-12-17 16:09:16 +0000423#if defined(MISSING_STATVFS)
424 { "statvfs", (sqlite3_syscall_ptr)0, 0 },
425#define osStatvfs ((int(*)(const char*,void*))aSyscall[20].pCurrent)
426#else
427 { "statvfs", (sqlite3_syscall_ptr)statvfs, 0 },
428#define osStatvfs ((int(*)(const char*,struct statvfs*))aSyscall[20].pCurrent)
429#endif
430
drhe562be52011-03-02 18:01:10 +0000431}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000432
433/*
434** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000435** "unix" VFSes. Return SQLITE_OK opon successfully updating the
436** system call pointer, or SQLITE_NOTFOUND if there is no configurable
437** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000438*/
439static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000440 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
441 const char *zName, /* Name of system call to override */
442 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000443){
drh58ad5802011-03-23 22:02:23 +0000444 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000445 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000446
447 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000448 if( zName==0 ){
449 /* If no zName is given, restore all system calls to their default
450 ** settings and return NULL
451 */
dan51438a72011-04-02 17:00:47 +0000452 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000453 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
454 if( aSyscall[i].pDefault ){
455 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000456 }
457 }
458 }else{
459 /* If zName is specified, operate on only the one system call
460 ** specified.
461 */
462 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
463 if( strcmp(zName, aSyscall[i].zName)==0 ){
464 if( aSyscall[i].pDefault==0 ){
465 aSyscall[i].pDefault = aSyscall[i].pCurrent;
466 }
drh1df30962011-03-02 19:06:42 +0000467 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000468 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
469 aSyscall[i].pCurrent = pNewFunc;
470 break;
471 }
472 }
473 }
474 return rc;
475}
476
drh1df30962011-03-02 19:06:42 +0000477/*
478** Return the value of a system call. Return NULL if zName is not a
479** recognized system call name. NULL is also returned if the system call
480** is currently undefined.
481*/
drh58ad5802011-03-23 22:02:23 +0000482static sqlite3_syscall_ptr unixGetSystemCall(
483 sqlite3_vfs *pNotUsed,
484 const char *zName
485){
486 unsigned int i;
487
488 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000489 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
490 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
491 }
492 return 0;
493}
494
495/*
496** Return the name of the first system call after zName. If zName==NULL
497** then return the name of the first system call. Return NULL if zName
498** is the last system call or if zName is not the name of a valid
499** system call.
500*/
501static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000502 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000503
504 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000505 if( zName ){
506 for(i=0; i<ArraySize(aSyscall)-1; i++){
507 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000508 }
509 }
dan0fd7d862011-03-29 10:04:23 +0000510 for(i++; i<ArraySize(aSyscall); i++){
511 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000512 }
513 return 0;
514}
515
drhad4f1e52011-03-04 15:43:57 +0000516/*
517** Retry open() calls that fail due to EINTR
518*/
519static int robust_open(const char *z, int f, int m){
520 int rc;
521 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
522 return rc;
523}
danielk197713adf8a2004-06-03 16:08:41 +0000524
drh107886a2008-11-21 22:21:50 +0000525/*
dan9359c7b2009-08-21 08:29:10 +0000526** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000527** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000528** vxworksFileId objects used by this file, all of which may be
529** shared by multiple threads.
530**
531** Function unixMutexHeld() is used to assert() that the global mutex
532** is held when required. This function is only used as part of assert()
533** statements. e.g.
534**
535** unixEnterMutex()
536** assert( unixMutexHeld() );
537** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000538*/
539static void unixEnterMutex(void){
540 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
541}
542static void unixLeaveMutex(void){
543 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
544}
dan9359c7b2009-08-21 08:29:10 +0000545#ifdef SQLITE_DEBUG
546static int unixMutexHeld(void) {
547 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
548}
549#endif
drh107886a2008-11-21 22:21:50 +0000550
drh734c9862008-11-28 15:37:20 +0000551
drh30ddce62011-10-15 00:16:30 +0000552#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000553/*
554** Helper function for printing out trace information from debugging
555** binaries. This returns the string represetation of the supplied
556** integer lock-type.
557*/
drh308c2a52010-05-14 11:30:18 +0000558static const char *azFileLock(int eFileLock){
559 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000560 case NO_LOCK: return "NONE";
561 case SHARED_LOCK: return "SHARED";
562 case RESERVED_LOCK: return "RESERVED";
563 case PENDING_LOCK: return "PENDING";
564 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000565 }
566 return "ERROR";
567}
568#endif
569
570#ifdef SQLITE_LOCK_TRACE
571/*
572** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000573**
drh734c9862008-11-28 15:37:20 +0000574** This routine is used for troubleshooting locks on multithreaded
575** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
576** command-line option on the compiler. This code is normally
577** turned off.
578*/
579static int lockTrace(int fd, int op, struct flock *p){
580 char *zOpName, *zType;
581 int s;
582 int savedErrno;
583 if( op==F_GETLK ){
584 zOpName = "GETLK";
585 }else if( op==F_SETLK ){
586 zOpName = "SETLK";
587 }else{
drh99ab3b12011-03-02 15:09:07 +0000588 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000589 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
590 return s;
591 }
592 if( p->l_type==F_RDLCK ){
593 zType = "RDLCK";
594 }else if( p->l_type==F_WRLCK ){
595 zType = "WRLCK";
596 }else if( p->l_type==F_UNLCK ){
597 zType = "UNLCK";
598 }else{
599 assert( 0 );
600 }
601 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000602 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000603 savedErrno = errno;
604 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
605 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
606 (int)p->l_pid, s);
607 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
608 struct flock l2;
609 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000610 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000611 if( l2.l_type==F_RDLCK ){
612 zType = "RDLCK";
613 }else if( l2.l_type==F_WRLCK ){
614 zType = "WRLCK";
615 }else if( l2.l_type==F_UNLCK ){
616 zType = "UNLCK";
617 }else{
618 assert( 0 );
619 }
620 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
621 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
622 }
623 errno = savedErrno;
624 return s;
625}
drh99ab3b12011-03-02 15:09:07 +0000626#undef osFcntl
627#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000628#endif /* SQLITE_LOCK_TRACE */
629
drhff812312011-02-23 13:33:46 +0000630/*
631** Retry ftruncate() calls that fail due to EINTR
632*/
drhff812312011-02-23 13:33:46 +0000633static int robust_ftruncate(int h, sqlite3_int64 sz){
634 int rc;
drh99ab3b12011-03-02 15:09:07 +0000635 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000636 return rc;
637}
drh734c9862008-11-28 15:37:20 +0000638
639/*
640** This routine translates a standard POSIX errno code into something
641** useful to the clients of the sqlite3 functions. Specifically, it is
642** intended to translate a variety of "try again" errors into SQLITE_BUSY
643** and a variety of "please close the file descriptor NOW" errors into
644** SQLITE_IOERR
645**
646** Errors during initialization of locks, or file system support for locks,
647** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
648*/
649static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
650 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000651#if 0
652 /* At one point this code was not commented out. In theory, this branch
653 ** should never be hit, as this function should only be called after
654 ** a locking-related function (i.e. fcntl()) has returned non-zero with
655 ** the value of errno as the first argument. Since a system call has failed,
656 ** errno should be non-zero.
657 **
658 ** Despite this, if errno really is zero, we still don't want to return
659 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
660 ** propagated back to the caller. Commenting this branch out means errno==0
661 ** will be handled by the "default:" case below.
662 */
drh734c9862008-11-28 15:37:20 +0000663 case 0:
664 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000665#endif
666
drh734c9862008-11-28 15:37:20 +0000667 case EAGAIN:
668 case ETIMEDOUT:
669 case EBUSY:
670 case EINTR:
671 case ENOLCK:
672 /* random NFS retry error, unless during file system support
673 * introspection, in which it actually means what it says */
674 return SQLITE_BUSY;
675
676 case EACCES:
677 /* EACCES is like EAGAIN during locking operations, but not any other time*/
678 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
679 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
680 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
681 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
682 return SQLITE_BUSY;
683 }
684 /* else fall through */
685 case EPERM:
686 return SQLITE_PERM;
687
danea83bc62011-04-01 11:56:32 +0000688 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
689 ** this module never makes such a call. And the code in SQLite itself
690 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
691 ** this case is also commented out. If the system does set errno to EDEADLK,
692 ** the default SQLITE_IOERR_XXX code will be returned. */
693#if 0
drh734c9862008-11-28 15:37:20 +0000694 case EDEADLK:
695 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000696#endif
drh734c9862008-11-28 15:37:20 +0000697
698#if EOPNOTSUPP!=ENOTSUP
699 case EOPNOTSUPP:
700 /* something went terribly awry, unless during file system support
701 * introspection, in which it actually means what it says */
702#endif
703#ifdef ENOTSUP
704 case ENOTSUP:
705 /* invalid fd, unless during file system support introspection, in which
706 * it actually means what it says */
707#endif
708 case EIO:
709 case EBADF:
710 case EINVAL:
711 case ENOTCONN:
712 case ENODEV:
713 case ENXIO:
714 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000715#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000716 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000717#endif
drh734c9862008-11-28 15:37:20 +0000718 case ENOSYS:
719 /* these should force the client to close the file and reconnect */
720
721 default:
722 return sqliteIOErr;
723 }
724}
725
726
727
728/******************************************************************************
729****************** Begin Unique File ID Utility Used By VxWorks ***************
730**
731** On most versions of unix, we can get a unique ID for a file by concatenating
732** the device number and the inode number. But this does not work on VxWorks.
733** On VxWorks, a unique file id must be based on the canonical filename.
734**
735** A pointer to an instance of the following structure can be used as a
736** unique file ID in VxWorks. Each instance of this structure contains
737** a copy of the canonical filename. There is also a reference count.
738** The structure is reclaimed when the number of pointers to it drops to
739** zero.
740**
741** There are never very many files open at one time and lookups are not
742** a performance-critical path, so it is sufficient to put these
743** structures on a linked list.
744*/
745struct vxworksFileId {
746 struct vxworksFileId *pNext; /* Next in a list of them all */
747 int nRef; /* Number of references to this one */
748 int nName; /* Length of the zCanonicalName[] string */
749 char *zCanonicalName; /* Canonical filename */
750};
751
752#if OS_VXWORKS
753/*
drh9b35ea62008-11-29 02:20:26 +0000754** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000755** variable:
756*/
757static struct vxworksFileId *vxworksFileList = 0;
758
759/*
760** Simplify a filename into its canonical form
761** by making the following changes:
762**
763** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000764** * convert /./ into just /
765** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000766**
767** Changes are made in-place. Return the new name length.
768**
769** The original filename is in z[0..n-1]. Return the number of
770** characters in the simplified name.
771*/
772static int vxworksSimplifyName(char *z, int n){
773 int i, j;
774 while( n>1 && z[n-1]=='/' ){ n--; }
775 for(i=j=0; i<n; i++){
776 if( z[i]=='/' ){
777 if( z[i+1]=='/' ) continue;
778 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
779 i += 1;
780 continue;
781 }
782 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
783 while( j>0 && z[j-1]!='/' ){ j--; }
784 if( j>0 ){ j--; }
785 i += 2;
786 continue;
787 }
788 }
789 z[j++] = z[i];
790 }
791 z[j] = 0;
792 return j;
793}
794
795/*
796** Find a unique file ID for the given absolute pathname. Return
797** a pointer to the vxworksFileId object. This pointer is the unique
798** file ID.
799**
800** The nRef field of the vxworksFileId object is incremented before
801** the object is returned. A new vxworksFileId object is created
802** and added to the global list if necessary.
803**
804** If a memory allocation error occurs, return NULL.
805*/
806static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
807 struct vxworksFileId *pNew; /* search key and new file ID */
808 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
809 int n; /* Length of zAbsoluteName string */
810
811 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000812 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000813 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
814 if( pNew==0 ) return 0;
815 pNew->zCanonicalName = (char*)&pNew[1];
816 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
817 n = vxworksSimplifyName(pNew->zCanonicalName, n);
818
819 /* Search for an existing entry that matching the canonical name.
820 ** If found, increment the reference count and return a pointer to
821 ** the existing file ID.
822 */
823 unixEnterMutex();
824 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
825 if( pCandidate->nName==n
826 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
827 ){
828 sqlite3_free(pNew);
829 pCandidate->nRef++;
830 unixLeaveMutex();
831 return pCandidate;
832 }
833 }
834
835 /* No match was found. We will make a new file ID */
836 pNew->nRef = 1;
837 pNew->nName = n;
838 pNew->pNext = vxworksFileList;
839 vxworksFileList = pNew;
840 unixLeaveMutex();
841 return pNew;
842}
843
844/*
845** Decrement the reference count on a vxworksFileId object. Free
846** the object when the reference count reaches zero.
847*/
848static void vxworksReleaseFileId(struct vxworksFileId *pId){
849 unixEnterMutex();
850 assert( pId->nRef>0 );
851 pId->nRef--;
852 if( pId->nRef==0 ){
853 struct vxworksFileId **pp;
854 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
855 assert( *pp==pId );
856 *pp = pId->pNext;
857 sqlite3_free(pId);
858 }
859 unixLeaveMutex();
860}
861#endif /* OS_VXWORKS */
862/*************** End of Unique File ID Utility Used By VxWorks ****************
863******************************************************************************/
864
865
866/******************************************************************************
867*************************** Posix Advisory Locking ****************************
868**
drh9b35ea62008-11-29 02:20:26 +0000869** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000870** section 6.5.2.2 lines 483 through 490 specify that when a process
871** sets or clears a lock, that operation overrides any prior locks set
872** by the same process. It does not explicitly say so, but this implies
873** that it overrides locks set by the same process using a different
874** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000875**
876** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000877** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
878**
879** Suppose ./file1 and ./file2 are really the same file (because
880** one is a hard or symbolic link to the other) then if you set
881** an exclusive lock on fd1, then try to get an exclusive lock
882** on fd2, it works. I would have expected the second lock to
883** fail since there was already a lock on the file due to fd1.
884** But not so. Since both locks came from the same process, the
885** second overrides the first, even though they were on different
886** file descriptors opened on different file names.
887**
drh734c9862008-11-28 15:37:20 +0000888** This means that we cannot use POSIX locks to synchronize file access
889** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000890** to synchronize access for threads in separate processes, but not
891** threads within the same process.
892**
893** To work around the problem, SQLite has to manage file locks internally
894** on its own. Whenever a new database is opened, we have to find the
895** specific inode of the database file (the inode is determined by the
896** st_dev and st_ino fields of the stat structure that fstat() fills in)
897** and check for locks already existing on that inode. When locks are
898** created or removed, we have to look at our own internal record of the
899** locks to see if another thread has previously set a lock on that same
900** inode.
901**
drh9b35ea62008-11-29 02:20:26 +0000902** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
903** For VxWorks, we have to use the alternative unique ID system based on
904** canonical filename and implemented in the previous division.)
905**
danielk1977ad94b582007-08-20 06:44:22 +0000906** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000907** descriptor. It is now a structure that holds the integer file
908** descriptor and a pointer to a structure that describes the internal
909** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000910** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000911** point to the same locking structure. The locking structure keeps
912** a reference count (so we will know when to delete it) and a "cnt"
913** field that tells us its internal lock status. cnt==0 means the
914** file is unlocked. cnt==-1 means the file has an exclusive lock.
915** cnt>0 means there are cnt shared locks on the file.
916**
917** Any attempt to lock or unlock a file first checks the locking
918** structure. The fcntl() system call is only invoked to set a
919** POSIX lock if the internal lock structure transitions between
920** a locked and an unlocked state.
921**
drh734c9862008-11-28 15:37:20 +0000922** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000923**
924** If you close a file descriptor that points to a file that has locks,
925** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000926** released. To work around this problem, each unixInodeInfo object
927** maintains a count of the number of pending locks on tha inode.
928** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000929** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000930** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000931** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000932** be closed and that list is walked (and cleared) when the last lock
933** clears.
934**
drh9b35ea62008-11-29 02:20:26 +0000935** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000936**
drh9b35ea62008-11-29 02:20:26 +0000937** Many older versions of linux use the LinuxThreads library which is
938** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000939** A cannot be modified or overridden by a different thread B.
940** Only thread A can modify the lock. Locking behavior is correct
941** if the appliation uses the newer Native Posix Thread Library (NPTL)
942** on linux - with NPTL a lock created by thread A can override locks
943** in thread B. But there is no way to know at compile-time which
944** threading library is being used. So there is no way to know at
945** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000946** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000947** current process.
drh5fdae772004-06-29 03:29:00 +0000948**
drh8af6c222010-05-14 12:43:01 +0000949** SQLite used to support LinuxThreads. But support for LinuxThreads
950** was dropped beginning with version 3.7.0. SQLite will still work with
951** LinuxThreads provided that (1) there is no more than one connection
952** per database file in the same process and (2) database connections
953** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000954*/
955
956/*
957** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000958** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000959*/
960struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000961 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000962#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000963 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000964#else
drh107886a2008-11-21 22:21:50 +0000965 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000966#endif
967};
968
969/*
drhbbd42a62004-05-22 17:41:58 +0000970** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000971** inode. Or, on LinuxThreads, there is one of these structures for
972** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000973**
danielk1977ad94b582007-08-20 06:44:22 +0000974** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000975** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000976** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000977*/
drh8af6c222010-05-14 12:43:01 +0000978struct unixInodeInfo {
979 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000980 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000981 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
982 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000983 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000984 unixShmNode *pShmNode; /* Shared memory associated with this inode */
985 int nLock; /* Number of outstanding file locks */
986 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
987 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
988 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000989#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000990 unsigned long long sharedByte; /* for AFP simulated shared lock */
991#endif
drh6c7d5c52008-11-21 20:32:33 +0000992#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000993 sem_t *pSem; /* Named POSIX semaphore */
994 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000995#endif
drhbbd42a62004-05-22 17:41:58 +0000996};
997
drhda0e7682008-07-30 15:27:54 +0000998/*
drh8af6c222010-05-14 12:43:01 +0000999** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001000*/
drhd91c68f2010-05-14 14:52:25 +00001001static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001002
drh5fdae772004-06-29 03:29:00 +00001003/*
dane18d4952011-02-21 11:46:24 +00001004**
1005** This function - unixLogError_x(), is only ever called via the macro
1006** unixLogError().
1007**
1008** It is invoked after an error occurs in an OS function and errno has been
1009** set. It logs a message using sqlite3_log() containing the current value of
1010** errno and, if possible, the human-readable equivalent from strerror() or
1011** strerror_r().
1012**
1013** The first argument passed to the macro should be the error code that
1014** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1015** The two subsequent arguments should be the name of the OS function that
1016** failed (e.g. "unlink", "open") and the the associated file-system path,
1017** if any.
1018*/
drh0e9365c2011-03-02 02:08:13 +00001019#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1020static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001021 int errcode, /* SQLite error code */
1022 const char *zFunc, /* Name of OS function that failed */
1023 const char *zPath, /* File path associated with error */
1024 int iLine /* Source line number where error occurred */
1025){
1026 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001027 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001028
1029 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1030 ** the strerror() function to obtain the human-readable error message
1031 ** equivalent to errno. Otherwise, use strerror_r().
1032 */
1033#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1034 char aErr[80];
1035 memset(aErr, 0, sizeof(aErr));
1036 zErr = aErr;
1037
1038 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1039 ** assume that the system provides the the GNU version of strerror_r() that
1040 ** returns a pointer to a buffer containing the error message. That pointer
1041 ** may point to aErr[], or it may point to some static storage somewhere.
1042 ** Otherwise, assume that the system provides the POSIX version of
1043 ** strerror_r(), which always writes an error message into aErr[].
1044 **
1045 ** If the code incorrectly assumes that it is the POSIX version that is
1046 ** available, the error message will often be an empty string. Not a
1047 ** huge problem. Incorrectly concluding that the GNU version is available
1048 ** could lead to a segfault though.
1049 */
1050#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1051 zErr =
1052# endif
drh0e9365c2011-03-02 02:08:13 +00001053 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001054
1055#elif SQLITE_THREADSAFE
1056 /* This is a threadsafe build, but strerror_r() is not available. */
1057 zErr = "";
1058#else
1059 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001060 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001061#endif
1062
1063 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001064 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001065 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001066 "os_unix.c:%d: (%d) %s(%s) - %s",
1067 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001068 );
1069
1070 return errcode;
1071}
1072
drh0e9365c2011-03-02 02:08:13 +00001073/*
1074** Close a file descriptor.
1075**
1076** We assume that close() almost always works, since it is only in a
1077** very sick application or on a very sick platform that it might fail.
1078** If it does fail, simply leak the file descriptor, but do log the
1079** error.
1080**
1081** Note that it is not safe to retry close() after EINTR since the
1082** file descriptor might have already been reused by another thread.
1083** So we don't even try to recover from an EINTR. Just log the error
1084** and move on.
1085*/
1086static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001087 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001088 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1089 pFile ? pFile->zPath : 0, lineno);
1090 }
1091}
dane18d4952011-02-21 11:46:24 +00001092
1093/*
danb0ac3e32010-06-16 10:55:42 +00001094** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001095*/
drh0e9365c2011-03-02 02:08:13 +00001096static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001097 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001098 UnixUnusedFd *p;
1099 UnixUnusedFd *pNext;
1100 for(p=pInode->pUnused; p; p=pNext){
1101 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001102 robust_close(pFile, p->fd, __LINE__);
1103 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001104 }
drh0e9365c2011-03-02 02:08:13 +00001105 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001106}
1107
1108/*
drh8af6c222010-05-14 12:43:01 +00001109** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001110**
1111** The mutex entered using the unixEnterMutex() function must be held
1112** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001113*/
danb0ac3e32010-06-16 10:55:42 +00001114static void releaseInodeInfo(unixFile *pFile){
1115 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001116 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001117 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001118 pInode->nRef--;
1119 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001120 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001121 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001122 if( pInode->pPrev ){
1123 assert( pInode->pPrev->pNext==pInode );
1124 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001125 }else{
drh8af6c222010-05-14 12:43:01 +00001126 assert( inodeList==pInode );
1127 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001128 }
drh8af6c222010-05-14 12:43:01 +00001129 if( pInode->pNext ){
1130 assert( pInode->pNext->pPrev==pInode );
1131 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001132 }
drh8af6c222010-05-14 12:43:01 +00001133 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001134 }
drhbbd42a62004-05-22 17:41:58 +00001135 }
1136}
1137
1138/*
drh8af6c222010-05-14 12:43:01 +00001139** Given a file descriptor, locate the unixInodeInfo object that
1140** describes that file descriptor. Create a new one if necessary. The
1141** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001142**
dan9359c7b2009-08-21 08:29:10 +00001143** The mutex entered using the unixEnterMutex() function must be held
1144** when this function is called.
1145**
drh6c7d5c52008-11-21 20:32:33 +00001146** Return an appropriate error code.
1147*/
drh8af6c222010-05-14 12:43:01 +00001148static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001149 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001150 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001151){
1152 int rc; /* System call return code */
1153 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001154 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1155 struct stat statbuf; /* Low-level file information */
1156 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001157
dan9359c7b2009-08-21 08:29:10 +00001158 assert( unixMutexHeld() );
1159
drh6c7d5c52008-11-21 20:32:33 +00001160 /* Get low-level information about the file that we can used to
1161 ** create a unique name for the file.
1162 */
1163 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001164 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001165 if( rc!=0 ){
1166 pFile->lastErrno = errno;
1167#ifdef EOVERFLOW
1168 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1169#endif
1170 return SQLITE_IOERR;
1171 }
1172
drheb0d74f2009-02-03 15:27:02 +00001173#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001174 /* On OS X on an msdos filesystem, the inode number is reported
1175 ** incorrectly for zero-size files. See ticket #3260. To work
1176 ** around this problem (we consider it a bug in OS X, not SQLite)
1177 ** we always increase the file size to 1 by writing a single byte
1178 ** prior to accessing the inode number. The one byte written is
1179 ** an ASCII 'S' character which also happens to be the first byte
1180 ** in the header of every SQLite database. In this way, if there
1181 ** is a race condition such that another thread has already populated
1182 ** the first page of the database, no damage is done.
1183 */
drh7ed97b92010-01-20 13:07:21 +00001184 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001185 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001186 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001187 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001188 return SQLITE_IOERR;
1189 }
drh99ab3b12011-03-02 15:09:07 +00001190 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001191 if( rc!=0 ){
1192 pFile->lastErrno = errno;
1193 return SQLITE_IOERR;
1194 }
1195 }
drheb0d74f2009-02-03 15:27:02 +00001196#endif
drh6c7d5c52008-11-21 20:32:33 +00001197
drh8af6c222010-05-14 12:43:01 +00001198 memset(&fileId, 0, sizeof(fileId));
1199 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001200#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001201 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001202#else
drh8af6c222010-05-14 12:43:01 +00001203 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001204#endif
drh8af6c222010-05-14 12:43:01 +00001205 pInode = inodeList;
1206 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1207 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001208 }
drh8af6c222010-05-14 12:43:01 +00001209 if( pInode==0 ){
1210 pInode = sqlite3_malloc( sizeof(*pInode) );
1211 if( pInode==0 ){
1212 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001213 }
drh8af6c222010-05-14 12:43:01 +00001214 memset(pInode, 0, sizeof(*pInode));
1215 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1216 pInode->nRef = 1;
1217 pInode->pNext = inodeList;
1218 pInode->pPrev = 0;
1219 if( inodeList ) inodeList->pPrev = pInode;
1220 inodeList = pInode;
1221 }else{
1222 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001223 }
drh8af6c222010-05-14 12:43:01 +00001224 *ppInode = pInode;
1225 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001226}
drh6c7d5c52008-11-21 20:32:33 +00001227
aswift5b1a2562008-08-22 00:22:35 +00001228
1229/*
danielk197713adf8a2004-06-03 16:08:41 +00001230** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001231** file by this or any other process. If such a lock is held, set *pResOut
1232** to a non-zero value otherwise *pResOut is set to zero. The return value
1233** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001234*/
danielk1977861f7452008-06-05 11:39:11 +00001235static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001236 int rc = SQLITE_OK;
1237 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001238 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001239
danielk1977861f7452008-06-05 11:39:11 +00001240 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1241
drh054889e2005-11-30 03:20:31 +00001242 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001243 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001244
1245 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001246 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001247 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001248 }
1249
drh2ac3ee92004-06-07 16:27:46 +00001250 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001251 */
danielk197709480a92009-02-09 05:32:32 +00001252#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001253 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001254 struct flock lock;
1255 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001256 lock.l_start = RESERVED_BYTE;
1257 lock.l_len = 1;
1258 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001259 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1260 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1261 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001262 } else if( lock.l_type!=F_UNLCK ){
1263 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001264 }
1265 }
danielk197709480a92009-02-09 05:32:32 +00001266#endif
danielk197713adf8a2004-06-03 16:08:41 +00001267
drh6c7d5c52008-11-21 20:32:33 +00001268 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001269 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001270
aswift5b1a2562008-08-22 00:22:35 +00001271 *pResOut = reserved;
1272 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001273}
1274
1275/*
drha7e61d82011-03-12 17:02:57 +00001276** Attempt to set a system-lock on the file pFile. The lock is
1277** described by pLock.
1278**
drh77197112011-03-15 19:08:48 +00001279** If the pFile was opened read/write from unix-excl, then the only lock
1280** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001281** the first time any lock is attempted. All subsequent system locking
1282** operations become no-ops. Locking operations still happen internally,
1283** in order to coordinate access between separate database connections
1284** within this process, but all of that is handled in memory and the
1285** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001286**
1287** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1288** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1289** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001290**
1291** Zero is returned if the call completes successfully, or -1 if a call
1292** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001293*/
1294static int unixFileLock(unixFile *pFile, struct flock *pLock){
1295 int rc;
drh3cb93392011-03-12 18:10:44 +00001296 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001297 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001298 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001299 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1300 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1301 ){
drh3cb93392011-03-12 18:10:44 +00001302 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001303 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001304 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001305 lock.l_whence = SEEK_SET;
1306 lock.l_start = SHARED_FIRST;
1307 lock.l_len = SHARED_SIZE;
1308 lock.l_type = F_WRLCK;
1309 rc = osFcntl(pFile->h, F_SETLK, &lock);
1310 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001311 pInode->bProcessLock = 1;
1312 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001313 }else{
1314 rc = 0;
1315 }
1316 }else{
1317 rc = osFcntl(pFile->h, F_SETLK, pLock);
1318 }
1319 return rc;
1320}
1321
1322/*
drh308c2a52010-05-14 11:30:18 +00001323** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001324** of the following:
1325**
drh2ac3ee92004-06-07 16:27:46 +00001326** (1) SHARED_LOCK
1327** (2) RESERVED_LOCK
1328** (3) PENDING_LOCK
1329** (4) EXCLUSIVE_LOCK
1330**
drhb3e04342004-06-08 00:47:47 +00001331** Sometimes when requesting one lock state, additional lock states
1332** are inserted in between. The locking might fail on one of the later
1333** transitions leaving the lock state different from what it started but
1334** still short of its goal. The following chart shows the allowed
1335** transitions and the inserted intermediate states:
1336**
1337** UNLOCKED -> SHARED
1338** SHARED -> RESERVED
1339** SHARED -> (PENDING) -> EXCLUSIVE
1340** RESERVED -> (PENDING) -> EXCLUSIVE
1341** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001342**
drha6abd042004-06-09 17:37:22 +00001343** This routine will only increase a lock. Use the sqlite3OsUnlock()
1344** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001345*/
drh308c2a52010-05-14 11:30:18 +00001346static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001347 /* The following describes the implementation of the various locks and
1348 ** lock transitions in terms of the POSIX advisory shared and exclusive
1349 ** lock primitives (called read-locks and write-locks below, to avoid
1350 ** confusion with SQLite lock names). The algorithms are complicated
1351 ** slightly in order to be compatible with windows systems simultaneously
1352 ** accessing the same database file, in case that is ever required.
1353 **
1354 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1355 ** byte', each single bytes at well known offsets, and the 'shared byte
1356 ** range', a range of 510 bytes at a well known offset.
1357 **
1358 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1359 ** byte'. If this is successful, a random byte from the 'shared byte
1360 ** range' is read-locked and the lock on the 'pending byte' released.
1361 **
danielk197790ba3bd2004-06-25 08:32:25 +00001362 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1363 ** A RESERVED lock is implemented by grabbing a write-lock on the
1364 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001365 **
1366 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001367 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1368 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1369 ** obtained, but existing SHARED locks are allowed to persist. A process
1370 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1371 ** This property is used by the algorithm for rolling back a journal file
1372 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001373 **
danielk197790ba3bd2004-06-25 08:32:25 +00001374 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1375 ** implemented by obtaining a write-lock on the entire 'shared byte
1376 ** range'. Since all other locks require a read-lock on one of the bytes
1377 ** within this range, this ensures that no other locks are held on the
1378 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001379 **
1380 ** The reason a single byte cannot be used instead of the 'shared byte
1381 ** range' is that some versions of windows do not support read-locks. By
1382 ** locking a random byte from a range, concurrent SHARED locks may exist
1383 ** even if the locking primitive used is always a write-lock.
1384 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001385 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001386 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001387 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001388 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001389 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001390
drh054889e2005-11-30 03:20:31 +00001391 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001392 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1393 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001394 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001395
1396 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001397 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001398 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001399 */
drh308c2a52010-05-14 11:30:18 +00001400 if( pFile->eFileLock>=eFileLock ){
1401 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1402 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001403 return SQLITE_OK;
1404 }
1405
drh0c2694b2009-09-03 16:23:44 +00001406 /* Make sure the locking sequence is correct.
1407 ** (1) We never move from unlocked to anything higher than shared lock.
1408 ** (2) SQLite never explicitly requests a pendig lock.
1409 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001410 */
drh308c2a52010-05-14 11:30:18 +00001411 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1412 assert( eFileLock!=PENDING_LOCK );
1413 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001414
drh8af6c222010-05-14 12:43:01 +00001415 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001416 */
drh6c7d5c52008-11-21 20:32:33 +00001417 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001418 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001419
danielk1977ad94b582007-08-20 06:44:22 +00001420 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001421 ** handle that precludes the requested lock, return BUSY.
1422 */
drh8af6c222010-05-14 12:43:01 +00001423 if( (pFile->eFileLock!=pInode->eFileLock &&
1424 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001425 ){
1426 rc = SQLITE_BUSY;
1427 goto end_lock;
1428 }
1429
1430 /* If a SHARED lock is requested, and some thread using this PID already
1431 ** has a SHARED or RESERVED lock, then increment reference counts and
1432 ** return SQLITE_OK.
1433 */
drh308c2a52010-05-14 11:30:18 +00001434 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001435 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001436 assert( eFileLock==SHARED_LOCK );
1437 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001438 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001439 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001440 pInode->nShared++;
1441 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001442 goto end_lock;
1443 }
1444
danielk19779a1d0ab2004-06-01 14:09:28 +00001445
drh3cde3bb2004-06-12 02:17:14 +00001446 /* A PENDING lock is needed before acquiring a SHARED lock and before
1447 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1448 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001449 */
drh0c2694b2009-09-03 16:23:44 +00001450 lock.l_len = 1L;
1451 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001452 if( eFileLock==SHARED_LOCK
1453 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001454 ){
drh308c2a52010-05-14 11:30:18 +00001455 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001456 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001457 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001458 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001459 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001460 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001461 pFile->lastErrno = tErrno;
1462 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001463 goto end_lock;
1464 }
drh3cde3bb2004-06-12 02:17:14 +00001465 }
1466
1467
1468 /* If control gets to this point, then actually go ahead and make
1469 ** operating system calls for the specified lock.
1470 */
drh308c2a52010-05-14 11:30:18 +00001471 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001472 assert( pInode->nShared==0 );
1473 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001474 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001475
drh2ac3ee92004-06-07 16:27:46 +00001476 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001477 lock.l_start = SHARED_FIRST;
1478 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001479 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001480 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001481 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001482 }
dan661d71a2011-03-30 19:08:03 +00001483
drh2ac3ee92004-06-07 16:27:46 +00001484 /* Drop the temporary PENDING lock */
1485 lock.l_start = PENDING_BYTE;
1486 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001487 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001488 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1489 /* This could happen with a network mount */
1490 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001491 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001492 }
dan661d71a2011-03-30 19:08:03 +00001493
1494 if( rc ){
1495 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001496 pFile->lastErrno = tErrno;
1497 }
dan661d71a2011-03-30 19:08:03 +00001498 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001499 }else{
drh308c2a52010-05-14 11:30:18 +00001500 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001501 pInode->nLock++;
1502 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001503 }
drh8af6c222010-05-14 12:43:01 +00001504 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001505 /* We are trying for an exclusive lock but another thread in this
1506 ** same process is still holding a shared lock. */
1507 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001508 }else{
drh3cde3bb2004-06-12 02:17:14 +00001509 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001510 ** assumed that there is a SHARED or greater lock on the file
1511 ** already.
1512 */
drh308c2a52010-05-14 11:30:18 +00001513 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001515
1516 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1517 if( eFileLock==RESERVED_LOCK ){
1518 lock.l_start = RESERVED_BYTE;
1519 lock.l_len = 1L;
1520 }else{
1521 lock.l_start = SHARED_FIRST;
1522 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001523 }
dan661d71a2011-03-30 19:08:03 +00001524
1525 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001526 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001527 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001528 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001529 pFile->lastErrno = tErrno;
1530 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001531 }
drhbbd42a62004-05-22 17:41:58 +00001532 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001533
drh8f941bc2009-01-14 23:03:40 +00001534
1535#ifndef NDEBUG
1536 /* Set up the transaction-counter change checking flags when
1537 ** transitioning from a SHARED to a RESERVED lock. The change
1538 ** from SHARED to RESERVED marks the beginning of a normal
1539 ** write operation (not a hot journal rollback).
1540 */
1541 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001542 && pFile->eFileLock<=SHARED_LOCK
1543 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001544 ){
1545 pFile->transCntrChng = 0;
1546 pFile->dbUpdate = 0;
1547 pFile->inNormalWrite = 1;
1548 }
1549#endif
1550
1551
danielk1977ecb2a962004-06-02 06:30:16 +00001552 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001553 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001554 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001555 }else if( eFileLock==EXCLUSIVE_LOCK ){
1556 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001557 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001558 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001559
1560end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001561 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001562 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1563 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001564 return rc;
1565}
1566
1567/*
dan08da86a2009-08-21 17:18:03 +00001568** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001569** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001570*/
1571static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001572 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001573 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001574 p->pNext = pInode->pUnused;
1575 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001576 pFile->h = -1;
1577 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001578}
1579
1580/*
drh308c2a52010-05-14 11:30:18 +00001581** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001582** must be either NO_LOCK or SHARED_LOCK.
1583**
1584** If the locking level of the file descriptor is already at or below
1585** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001586**
1587** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1588** the byte range is divided into 2 parts and the first part is unlocked then
1589** set to a read lock, then the other part is simply unlocked. This works
1590** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1591** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001592*/
drha7e61d82011-03-12 17:02:57 +00001593static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001594 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001595 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001596 struct flock lock;
1597 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001598
drh054889e2005-11-30 03:20:31 +00001599 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001600 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001601 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001602 getpid()));
drha6abd042004-06-09 17:37:22 +00001603
drh308c2a52010-05-14 11:30:18 +00001604 assert( eFileLock<=SHARED_LOCK );
1605 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001606 return SQLITE_OK;
1607 }
drh6c7d5c52008-11-21 20:32:33 +00001608 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001609 pInode = pFile->pInode;
1610 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001611 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001612 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001613
1614#ifndef NDEBUG
1615 /* When reducing a lock such that other processes can start
1616 ** reading the database file again, make sure that the
1617 ** transaction counter was updated if any part of the database
1618 ** file changed. If the transaction counter is not updated,
1619 ** other connections to the same file might not realize that
1620 ** the file has changed and hence might not know to flush their
1621 ** cache. The use of a stale cache can lead to database corruption.
1622 */
drh8f941bc2009-01-14 23:03:40 +00001623 pFile->inNormalWrite = 0;
1624#endif
1625
drh7ed97b92010-01-20 13:07:21 +00001626 /* downgrading to a shared lock on NFS involves clearing the write lock
1627 ** before establishing the readlock - to avoid a race condition we downgrade
1628 ** the lock in 2 blocks, so that part of the range will be covered by a
1629 ** write lock until the rest is covered by a read lock:
1630 ** 1: [WWWWW]
1631 ** 2: [....W]
1632 ** 3: [RRRRW]
1633 ** 4: [RRRR.]
1634 */
drh308c2a52010-05-14 11:30:18 +00001635 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001636
1637#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001638 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001639 assert( handleNFSUnlock==0 );
1640#endif
1641#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001642 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001643 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001644 off_t divSize = SHARED_SIZE - 1;
1645
1646 lock.l_type = F_UNLCK;
1647 lock.l_whence = SEEK_SET;
1648 lock.l_start = SHARED_FIRST;
1649 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001650 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001651 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001652 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001653 if( IS_LOCK_ERROR(rc) ){
1654 pFile->lastErrno = tErrno;
1655 }
1656 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001657 }
drh7ed97b92010-01-20 13:07:21 +00001658 lock.l_type = F_RDLCK;
1659 lock.l_whence = SEEK_SET;
1660 lock.l_start = SHARED_FIRST;
1661 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001662 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001663 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001664 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1665 if( IS_LOCK_ERROR(rc) ){
1666 pFile->lastErrno = tErrno;
1667 }
1668 goto end_unlock;
1669 }
1670 lock.l_type = F_UNLCK;
1671 lock.l_whence = SEEK_SET;
1672 lock.l_start = SHARED_FIRST+divSize;
1673 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001674 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001675 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001676 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001677 if( IS_LOCK_ERROR(rc) ){
1678 pFile->lastErrno = tErrno;
1679 }
1680 goto end_unlock;
1681 }
drh30f776f2011-02-25 03:25:07 +00001682 }else
1683#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1684 {
drh7ed97b92010-01-20 13:07:21 +00001685 lock.l_type = F_RDLCK;
1686 lock.l_whence = SEEK_SET;
1687 lock.l_start = SHARED_FIRST;
1688 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001689 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001690 /* In theory, the call to unixFileLock() cannot fail because another
1691 ** process is holding an incompatible lock. If it does, this
1692 ** indicates that the other process is not following the locking
1693 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1694 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1695 ** an assert to fail). */
1696 rc = SQLITE_IOERR_RDLOCK;
1697 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001698 goto end_unlock;
1699 }
drh9c105bb2004-10-02 20:38:28 +00001700 }
1701 }
drhbbd42a62004-05-22 17:41:58 +00001702 lock.l_type = F_UNLCK;
1703 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001704 lock.l_start = PENDING_BYTE;
1705 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001706 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001707 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001708 }else{
danea83bc62011-04-01 11:56:32 +00001709 rc = SQLITE_IOERR_UNLOCK;
1710 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001711 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001712 }
drhbbd42a62004-05-22 17:41:58 +00001713 }
drh308c2a52010-05-14 11:30:18 +00001714 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001715 /* Decrement the shared lock counter. Release the lock using an
1716 ** OS call only when all threads in this same process have released
1717 ** the lock.
1718 */
drh8af6c222010-05-14 12:43:01 +00001719 pInode->nShared--;
1720 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001721 lock.l_type = F_UNLCK;
1722 lock.l_whence = SEEK_SET;
1723 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001724 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001725 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001726 }else{
danea83bc62011-04-01 11:56:32 +00001727 rc = SQLITE_IOERR_UNLOCK;
1728 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001729 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001730 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001731 }
drha6abd042004-06-09 17:37:22 +00001732 }
1733
drhbbd42a62004-05-22 17:41:58 +00001734 /* Decrement the count of locks against this same file. When the
1735 ** count reaches zero, close any other file descriptors whose close
1736 ** was deferred because of outstanding locks.
1737 */
drh8af6c222010-05-14 12:43:01 +00001738 pInode->nLock--;
1739 assert( pInode->nLock>=0 );
1740 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001741 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001742 }
1743 }
aswift5b1a2562008-08-22 00:22:35 +00001744
1745end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001746 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001747 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001748 return rc;
drhbbd42a62004-05-22 17:41:58 +00001749}
1750
1751/*
drh308c2a52010-05-14 11:30:18 +00001752** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001753** must be either NO_LOCK or SHARED_LOCK.
1754**
1755** If the locking level of the file descriptor is already at or below
1756** the requested locking level, this routine is a no-op.
1757*/
drh308c2a52010-05-14 11:30:18 +00001758static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001759 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001760}
1761
1762/*
danielk1977e339d652008-06-28 11:23:00 +00001763** This function performs the parts of the "close file" operation
1764** common to all locking schemes. It closes the directory and file
1765** handles, if they are valid, and sets all fields of the unixFile
1766** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001767**
1768** It is *not* necessary to hold the mutex when this routine is called,
1769** even on VxWorks. A mutex will be acquired on VxWorks by the
1770** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001771*/
1772static int closeUnixFile(sqlite3_file *id){
1773 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001774 if( pFile->h>=0 ){
1775 robust_close(pFile, pFile->h, __LINE__);
1776 pFile->h = -1;
1777 }
1778#if OS_VXWORKS
1779 if( pFile->pId ){
1780 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001781 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001782 }
1783 vxworksReleaseFileId(pFile->pId);
1784 pFile->pId = 0;
1785 }
1786#endif
1787 OSTRACE(("CLOSE %-3d\n", pFile->h));
1788 OpenCounter(-1);
1789 sqlite3_free(pFile->pUnused);
1790 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001791 return SQLITE_OK;
1792}
1793
1794/*
danielk1977e3026632004-06-22 11:29:02 +00001795** Close a file.
1796*/
danielk197762079062007-08-15 17:08:46 +00001797static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001798 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001799 unixFile *pFile = (unixFile *)id;
1800 unixUnlock(id, NO_LOCK);
1801 unixEnterMutex();
1802
1803 /* unixFile.pInode is always valid here. Otherwise, a different close
1804 ** routine (e.g. nolockClose()) would be called instead.
1805 */
1806 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1807 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1808 /* If there are outstanding locks, do not actually close the file just
1809 ** yet because that would clear those locks. Instead, add the file
1810 ** descriptor to pInode->pUnused list. It will be automatically closed
1811 ** when the last lock is cleared.
1812 */
1813 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001814 }
dan661d71a2011-03-30 19:08:03 +00001815 releaseInodeInfo(pFile);
1816 rc = closeUnixFile(id);
1817 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001818 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001819}
1820
drh734c9862008-11-28 15:37:20 +00001821/************** End of the posix advisory lock implementation *****************
1822******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001823
drh734c9862008-11-28 15:37:20 +00001824/******************************************************************************
1825****************************** No-op Locking **********************************
1826**
1827** Of the various locking implementations available, this is by far the
1828** simplest: locking is ignored. No attempt is made to lock the database
1829** file for reading or writing.
1830**
1831** This locking mode is appropriate for use on read-only databases
1832** (ex: databases that are burned into CD-ROM, for example.) It can
1833** also be used if the application employs some external mechanism to
1834** prevent simultaneous access of the same database by two or more
1835** database connections. But there is a serious risk of database
1836** corruption if this locking mode is used in situations where multiple
1837** database connections are accessing the same database file at the same
1838** time and one or more of those connections are writing.
1839*/
drhbfe66312006-10-03 17:40:40 +00001840
drh734c9862008-11-28 15:37:20 +00001841static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1842 UNUSED_PARAMETER(NotUsed);
1843 *pResOut = 0;
1844 return SQLITE_OK;
1845}
drh734c9862008-11-28 15:37:20 +00001846static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1847 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1848 return SQLITE_OK;
1849}
drh734c9862008-11-28 15:37:20 +00001850static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1851 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1852 return SQLITE_OK;
1853}
1854
1855/*
drh9b35ea62008-11-29 02:20:26 +00001856** Close the file.
drh734c9862008-11-28 15:37:20 +00001857*/
1858static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001859 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001860}
1861
1862/******************* End of the no-op lock implementation *********************
1863******************************************************************************/
1864
1865/******************************************************************************
1866************************* Begin dot-file Locking ******************************
1867**
drh0c2694b2009-09-03 16:23:44 +00001868** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001869** files (really a directory) to control access to the database. This works
1870** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001871**
1872** (1) There is zero concurrency. A single reader blocks all other
1873** connections from reading or writing the database.
1874**
1875** (2) An application crash or power loss can leave stale lock files
1876** sitting around that need to be cleared manually.
1877**
1878** Nevertheless, a dotlock is an appropriate locking mode for use if no
1879** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001880**
drh9ef6bc42011-11-04 02:24:02 +00001881** Dotfile locking works by creating a subdirectory in the same directory as
1882** the database and with the same name but with a ".lock" extension added.
1883** The existance of a lock directory implies an EXCLUSIVE lock. All other
1884** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001885*/
1886
1887/*
1888** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001889** lock directory.
drh734c9862008-11-28 15:37:20 +00001890*/
1891#define DOTLOCK_SUFFIX ".lock"
1892
drh7708e972008-11-29 00:56:52 +00001893/*
1894** This routine checks if there is a RESERVED lock held on the specified
1895** file by this or any other process. If such a lock is held, set *pResOut
1896** to a non-zero value otherwise *pResOut is set to zero. The return value
1897** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1898**
1899** In dotfile locking, either a lock exists or it does not. So in this
1900** variation of CheckReservedLock(), *pResOut is set to true if any lock
1901** is held on the file and false if the file is unlocked.
1902*/
drh734c9862008-11-28 15:37:20 +00001903static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1904 int rc = SQLITE_OK;
1905 int reserved = 0;
1906 unixFile *pFile = (unixFile*)id;
1907
1908 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1909
1910 assert( pFile );
1911
1912 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001913 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001914 /* Either this connection or some other connection in the same process
1915 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001916 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001917 }else{
1918 /* The lock is held if and only if the lockfile exists */
1919 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001920 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001921 }
drh308c2a52010-05-14 11:30:18 +00001922 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001923 *pResOut = reserved;
1924 return rc;
1925}
1926
drh7708e972008-11-29 00:56:52 +00001927/*
drh308c2a52010-05-14 11:30:18 +00001928** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001929** of the following:
1930**
1931** (1) SHARED_LOCK
1932** (2) RESERVED_LOCK
1933** (3) PENDING_LOCK
1934** (4) EXCLUSIVE_LOCK
1935**
1936** Sometimes when requesting one lock state, additional lock states
1937** are inserted in between. The locking might fail on one of the later
1938** transitions leaving the lock state different from what it started but
1939** still short of its goal. The following chart shows the allowed
1940** transitions and the inserted intermediate states:
1941**
1942** UNLOCKED -> SHARED
1943** SHARED -> RESERVED
1944** SHARED -> (PENDING) -> EXCLUSIVE
1945** RESERVED -> (PENDING) -> EXCLUSIVE
1946** PENDING -> EXCLUSIVE
1947**
1948** This routine will only increase a lock. Use the sqlite3OsUnlock()
1949** routine to lower a locking level.
1950**
1951** With dotfile locking, we really only support state (4): EXCLUSIVE.
1952** But we track the other locking levels internally.
1953*/
drh308c2a52010-05-14 11:30:18 +00001954static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001955 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001956 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001957 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001958
drh7708e972008-11-29 00:56:52 +00001959
1960 /* If we have any lock, then the lock file already exists. All we have
1961 ** to do is adjust our internal record of the lock level.
1962 */
drh308c2a52010-05-14 11:30:18 +00001963 if( pFile->eFileLock > NO_LOCK ){
1964 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001965 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001966#ifdef HAVE_UTIME
1967 utime(zLockFile, NULL);
1968#else
drh734c9862008-11-28 15:37:20 +00001969 utimes(zLockFile, NULL);
1970#endif
drh7708e972008-11-29 00:56:52 +00001971 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001972 }
1973
1974 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001975 rc = osMkdir(zLockFile, 0777);
1976 if( rc<0 ){
1977 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001978 int tErrno = errno;
1979 if( EEXIST == tErrno ){
1980 rc = SQLITE_BUSY;
1981 } else {
1982 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1983 if( IS_LOCK_ERROR(rc) ){
1984 pFile->lastErrno = tErrno;
1985 }
1986 }
drh7708e972008-11-29 00:56:52 +00001987 return rc;
drh734c9862008-11-28 15:37:20 +00001988 }
drh734c9862008-11-28 15:37:20 +00001989
1990 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001991 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001992 return rc;
1993}
1994
drh7708e972008-11-29 00:56:52 +00001995/*
drh308c2a52010-05-14 11:30:18 +00001996** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001997** must be either NO_LOCK or SHARED_LOCK.
1998**
1999** If the locking level of the file descriptor is already at or below
2000** the requested locking level, this routine is a no-op.
2001**
2002** When the locking level reaches NO_LOCK, delete the lock file.
2003*/
drh308c2a52010-05-14 11:30:18 +00002004static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002005 unixFile *pFile = (unixFile*)id;
2006 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002007 int rc;
drh734c9862008-11-28 15:37:20 +00002008
2009 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002010 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2011 pFile->eFileLock, getpid()));
2012 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002013
2014 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002015 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002016 return SQLITE_OK;
2017 }
drh7708e972008-11-29 00:56:52 +00002018
2019 /* To downgrade to shared, simply update our internal notion of the
2020 ** lock state. No need to mess with the file on disk.
2021 */
drh308c2a52010-05-14 11:30:18 +00002022 if( eFileLock==SHARED_LOCK ){
2023 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002024 return SQLITE_OK;
2025 }
2026
drh7708e972008-11-29 00:56:52 +00002027 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002028 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002029 rc = osRmdir(zLockFile);
2030 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2031 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002032 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002033 rc = 0;
drh734c9862008-11-28 15:37:20 +00002034 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002035 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002036 }
2037 if( IS_LOCK_ERROR(rc) ){
2038 pFile->lastErrno = tErrno;
2039 }
2040 return rc;
2041 }
drh308c2a52010-05-14 11:30:18 +00002042 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002043 return SQLITE_OK;
2044}
2045
2046/*
drh9b35ea62008-11-29 02:20:26 +00002047** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002048*/
2049static int dotlockClose(sqlite3_file *id) {
2050 int rc;
2051 if( id ){
2052 unixFile *pFile = (unixFile*)id;
2053 dotlockUnlock(id, NO_LOCK);
2054 sqlite3_free(pFile->lockingContext);
2055 }
drh734c9862008-11-28 15:37:20 +00002056 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002057 return rc;
2058}
2059/****************** End of the dot-file lock implementation *******************
2060******************************************************************************/
2061
2062/******************************************************************************
2063************************** Begin flock Locking ********************************
2064**
2065** Use the flock() system call to do file locking.
2066**
drh6b9d6dd2008-12-03 19:34:47 +00002067** flock() locking is like dot-file locking in that the various
2068** fine-grain locking levels supported by SQLite are collapsed into
2069** a single exclusive lock. In other words, SHARED, RESERVED, and
2070** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2071** still works when you do this, but concurrency is reduced since
2072** only a single process can be reading the database at a time.
2073**
drh734c9862008-11-28 15:37:20 +00002074** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2075** compiling for VXWORKS.
2076*/
2077#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002078
drh6b9d6dd2008-12-03 19:34:47 +00002079/*
drhff812312011-02-23 13:33:46 +00002080** Retry flock() calls that fail with EINTR
2081*/
2082#ifdef EINTR
2083static int robust_flock(int fd, int op){
2084 int rc;
2085 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2086 return rc;
2087}
2088#else
drh5c819272011-02-23 14:00:12 +00002089# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002090#endif
2091
2092
2093/*
drh6b9d6dd2008-12-03 19:34:47 +00002094** This routine checks if there is a RESERVED lock held on the specified
2095** file by this or any other process. If such a lock is held, set *pResOut
2096** to a non-zero value otherwise *pResOut is set to zero. The return value
2097** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2098*/
drh734c9862008-11-28 15:37:20 +00002099static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2100 int rc = SQLITE_OK;
2101 int reserved = 0;
2102 unixFile *pFile = (unixFile*)id;
2103
2104 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2105
2106 assert( pFile );
2107
2108 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002109 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002110 reserved = 1;
2111 }
2112
2113 /* Otherwise see if some other process holds it. */
2114 if( !reserved ){
2115 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002116 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002117 if( !lrc ){
2118 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002119 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002120 if ( lrc ) {
2121 int tErrno = errno;
2122 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002123 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002124 if( IS_LOCK_ERROR(lrc) ){
2125 pFile->lastErrno = tErrno;
2126 rc = lrc;
2127 }
2128 }
2129 } else {
2130 int tErrno = errno;
2131 reserved = 1;
2132 /* someone else might have it reserved */
2133 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2134 if( IS_LOCK_ERROR(lrc) ){
2135 pFile->lastErrno = tErrno;
2136 rc = lrc;
2137 }
2138 }
2139 }
drh308c2a52010-05-14 11:30:18 +00002140 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002141
2142#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2143 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2144 rc = SQLITE_OK;
2145 reserved=1;
2146 }
2147#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2148 *pResOut = reserved;
2149 return rc;
2150}
2151
drh6b9d6dd2008-12-03 19:34:47 +00002152/*
drh308c2a52010-05-14 11:30:18 +00002153** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002154** of the following:
2155**
2156** (1) SHARED_LOCK
2157** (2) RESERVED_LOCK
2158** (3) PENDING_LOCK
2159** (4) EXCLUSIVE_LOCK
2160**
2161** Sometimes when requesting one lock state, additional lock states
2162** are inserted in between. The locking might fail on one of the later
2163** transitions leaving the lock state different from what it started but
2164** still short of its goal. The following chart shows the allowed
2165** transitions and the inserted intermediate states:
2166**
2167** UNLOCKED -> SHARED
2168** SHARED -> RESERVED
2169** SHARED -> (PENDING) -> EXCLUSIVE
2170** RESERVED -> (PENDING) -> EXCLUSIVE
2171** PENDING -> EXCLUSIVE
2172**
2173** flock() only really support EXCLUSIVE locks. We track intermediate
2174** lock states in the sqlite3_file structure, but all locks SHARED or
2175** above are really EXCLUSIVE locks and exclude all other processes from
2176** access the file.
2177**
2178** This routine will only increase a lock. Use the sqlite3OsUnlock()
2179** routine to lower a locking level.
2180*/
drh308c2a52010-05-14 11:30:18 +00002181static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002182 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002183 unixFile *pFile = (unixFile*)id;
2184
2185 assert( pFile );
2186
2187 /* if we already have a lock, it is exclusive.
2188 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002189 if (pFile->eFileLock > NO_LOCK) {
2190 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002191 return SQLITE_OK;
2192 }
2193
2194 /* grab an exclusive lock */
2195
drhff812312011-02-23 13:33:46 +00002196 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002197 int tErrno = errno;
2198 /* didn't get, must be busy */
2199 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2200 if( IS_LOCK_ERROR(rc) ){
2201 pFile->lastErrno = tErrno;
2202 }
2203 } else {
2204 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002205 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002206 }
drh308c2a52010-05-14 11:30:18 +00002207 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2208 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002209#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2210 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2211 rc = SQLITE_BUSY;
2212 }
2213#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2214 return rc;
2215}
2216
drh6b9d6dd2008-12-03 19:34:47 +00002217
2218/*
drh308c2a52010-05-14 11:30:18 +00002219** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002220** must be either NO_LOCK or SHARED_LOCK.
2221**
2222** If the locking level of the file descriptor is already at or below
2223** the requested locking level, this routine is a no-op.
2224*/
drh308c2a52010-05-14 11:30:18 +00002225static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002226 unixFile *pFile = (unixFile*)id;
2227
2228 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002229 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2230 pFile->eFileLock, getpid()));
2231 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002232
2233 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002234 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002235 return SQLITE_OK;
2236 }
2237
2238 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002239 if (eFileLock==SHARED_LOCK) {
2240 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002241 return SQLITE_OK;
2242 }
2243
2244 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002245 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002246#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002247 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002248#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002249 return SQLITE_IOERR_UNLOCK;
2250 }else{
drh308c2a52010-05-14 11:30:18 +00002251 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002252 return SQLITE_OK;
2253 }
2254}
2255
2256/*
2257** Close a file.
2258*/
2259static int flockClose(sqlite3_file *id) {
2260 if( id ){
2261 flockUnlock(id, NO_LOCK);
2262 }
2263 return closeUnixFile(id);
2264}
2265
2266#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2267
2268/******************* End of the flock lock implementation *********************
2269******************************************************************************/
2270
2271/******************************************************************************
2272************************ Begin Named Semaphore Locking ************************
2273**
2274** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002275**
2276** Semaphore locking is like dot-lock and flock in that it really only
2277** supports EXCLUSIVE locking. Only a single process can read or write
2278** the database file at a time. This reduces potential concurrency, but
2279** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002280*/
2281#if OS_VXWORKS
2282
drh6b9d6dd2008-12-03 19:34:47 +00002283/*
2284** This routine checks if there is a RESERVED lock held on the specified
2285** file by this or any other process. If such a lock is held, set *pResOut
2286** to a non-zero value otherwise *pResOut is set to zero. The return value
2287** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2288*/
drh734c9862008-11-28 15:37:20 +00002289static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2290 int rc = SQLITE_OK;
2291 int reserved = 0;
2292 unixFile *pFile = (unixFile*)id;
2293
2294 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2295
2296 assert( pFile );
2297
2298 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002299 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002300 reserved = 1;
2301 }
2302
2303 /* Otherwise see if some other process holds it. */
2304 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002305 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002306 struct stat statBuf;
2307
2308 if( sem_trywait(pSem)==-1 ){
2309 int tErrno = errno;
2310 if( EAGAIN != tErrno ){
2311 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2312 pFile->lastErrno = tErrno;
2313 } else {
2314 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002315 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002316 }
2317 }else{
2318 /* we could have it if we want it */
2319 sem_post(pSem);
2320 }
2321 }
drh308c2a52010-05-14 11:30:18 +00002322 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002323
2324 *pResOut = reserved;
2325 return rc;
2326}
2327
drh6b9d6dd2008-12-03 19:34:47 +00002328/*
drh308c2a52010-05-14 11:30:18 +00002329** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002330** of the following:
2331**
2332** (1) SHARED_LOCK
2333** (2) RESERVED_LOCK
2334** (3) PENDING_LOCK
2335** (4) EXCLUSIVE_LOCK
2336**
2337** Sometimes when requesting one lock state, additional lock states
2338** are inserted in between. The locking might fail on one of the later
2339** transitions leaving the lock state different from what it started but
2340** still short of its goal. The following chart shows the allowed
2341** transitions and the inserted intermediate states:
2342**
2343** UNLOCKED -> SHARED
2344** SHARED -> RESERVED
2345** SHARED -> (PENDING) -> EXCLUSIVE
2346** RESERVED -> (PENDING) -> EXCLUSIVE
2347** PENDING -> EXCLUSIVE
2348**
2349** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2350** lock states in the sqlite3_file structure, but all locks SHARED or
2351** above are really EXCLUSIVE locks and exclude all other processes from
2352** access the file.
2353**
2354** This routine will only increase a lock. Use the sqlite3OsUnlock()
2355** routine to lower a locking level.
2356*/
drh308c2a52010-05-14 11:30:18 +00002357static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002358 unixFile *pFile = (unixFile*)id;
2359 int fd;
drh8af6c222010-05-14 12:43:01 +00002360 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002361 int rc = SQLITE_OK;
2362
2363 /* if we already have a lock, it is exclusive.
2364 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002365 if (pFile->eFileLock > NO_LOCK) {
2366 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002367 rc = SQLITE_OK;
2368 goto sem_end_lock;
2369 }
2370
2371 /* lock semaphore now but bail out when already locked. */
2372 if( sem_trywait(pSem)==-1 ){
2373 rc = SQLITE_BUSY;
2374 goto sem_end_lock;
2375 }
2376
2377 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002378 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002379
2380 sem_end_lock:
2381 return rc;
2382}
2383
drh6b9d6dd2008-12-03 19:34:47 +00002384/*
drh308c2a52010-05-14 11:30:18 +00002385** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002386** must be either NO_LOCK or SHARED_LOCK.
2387**
2388** If the locking level of the file descriptor is already at or below
2389** the requested locking level, this routine is a no-op.
2390*/
drh308c2a52010-05-14 11:30:18 +00002391static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002392 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002393 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002394
2395 assert( pFile );
2396 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002397 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2398 pFile->eFileLock, getpid()));
2399 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002400
2401 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002402 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404 }
2405
2406 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002407 if (eFileLock==SHARED_LOCK) {
2408 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002409 return SQLITE_OK;
2410 }
2411
2412 /* no, really unlock. */
2413 if ( sem_post(pSem)==-1 ) {
2414 int rc, tErrno = errno;
2415 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2416 if( IS_LOCK_ERROR(rc) ){
2417 pFile->lastErrno = tErrno;
2418 }
2419 return rc;
2420 }
drh308c2a52010-05-14 11:30:18 +00002421 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002422 return SQLITE_OK;
2423}
2424
2425/*
2426 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002427 */
drh734c9862008-11-28 15:37:20 +00002428static int semClose(sqlite3_file *id) {
2429 if( id ){
2430 unixFile *pFile = (unixFile*)id;
2431 semUnlock(id, NO_LOCK);
2432 assert( pFile );
2433 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002434 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002435 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002436 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002437 }
2438 return SQLITE_OK;
2439}
2440
2441#endif /* OS_VXWORKS */
2442/*
2443** Named semaphore locking is only available on VxWorks.
2444**
2445*************** End of the named semaphore lock implementation ****************
2446******************************************************************************/
2447
2448
2449/******************************************************************************
2450*************************** Begin AFP Locking *********************************
2451**
2452** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2453** on Apple Macintosh computers - both OS9 and OSX.
2454**
2455** Third-party implementations of AFP are available. But this code here
2456** only works on OSX.
2457*/
2458
drhd2cb50b2009-01-09 21:41:17 +00002459#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002460/*
2461** The afpLockingContext structure contains all afp lock specific state
2462*/
drhbfe66312006-10-03 17:40:40 +00002463typedef struct afpLockingContext afpLockingContext;
2464struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002465 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002466 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002467};
2468
2469struct ByteRangeLockPB2
2470{
2471 unsigned long long offset; /* offset to first byte to lock */
2472 unsigned long long length; /* nbr of bytes to lock */
2473 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2474 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2475 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2476 int fd; /* file desc to assoc this lock with */
2477};
2478
drhfd131da2007-08-07 17:13:03 +00002479#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002480
drh6b9d6dd2008-12-03 19:34:47 +00002481/*
2482** This is a utility for setting or clearing a bit-range lock on an
2483** AFP filesystem.
2484**
2485** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2486*/
2487static int afpSetLock(
2488 const char *path, /* Name of the file to be locked or unlocked */
2489 unixFile *pFile, /* Open file descriptor on path */
2490 unsigned long long offset, /* First byte to be locked */
2491 unsigned long long length, /* Number of bytes to lock */
2492 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002493){
drh6b9d6dd2008-12-03 19:34:47 +00002494 struct ByteRangeLockPB2 pb;
2495 int err;
drhbfe66312006-10-03 17:40:40 +00002496
2497 pb.unLockFlag = setLockFlag ? 0 : 1;
2498 pb.startEndFlag = 0;
2499 pb.offset = offset;
2500 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002501 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002502
drh308c2a52010-05-14 11:30:18 +00002503 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002504 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002505 offset, length));
drhbfe66312006-10-03 17:40:40 +00002506 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2507 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002508 int rc;
2509 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002510 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2511 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002512#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2513 rc = SQLITE_BUSY;
2514#else
drh734c9862008-11-28 15:37:20 +00002515 rc = sqliteErrorFromPosixError(tErrno,
2516 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002517#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002518 if( IS_LOCK_ERROR(rc) ){
2519 pFile->lastErrno = tErrno;
2520 }
2521 return rc;
drhbfe66312006-10-03 17:40:40 +00002522 } else {
aswift5b1a2562008-08-22 00:22:35 +00002523 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002524 }
2525}
2526
drh6b9d6dd2008-12-03 19:34:47 +00002527/*
2528** This routine checks if there is a RESERVED lock held on the specified
2529** file by this or any other process. If such a lock is held, set *pResOut
2530** to a non-zero value otherwise *pResOut is set to zero. The return value
2531** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2532*/
danielk1977e339d652008-06-28 11:23:00 +00002533static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002534 int rc = SQLITE_OK;
2535 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002536 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002537 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002538
aswift5b1a2562008-08-22 00:22:35 +00002539 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2540
2541 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002542 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002543 if( context->reserved ){
2544 *pResOut = 1;
2545 return SQLITE_OK;
2546 }
drh8af6c222010-05-14 12:43:01 +00002547 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002548
2549 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002550 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002551 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002552 }
2553
2554 /* Otherwise see if some other process holds it.
2555 */
aswift5b1a2562008-08-22 00:22:35 +00002556 if( !reserved ){
2557 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002558 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002559 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002560 /* if we succeeded in taking the reserved lock, unlock it to restore
2561 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002562 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002563 } else {
2564 /* if we failed to get the lock then someone else must have it */
2565 reserved = 1;
2566 }
2567 if( IS_LOCK_ERROR(lrc) ){
2568 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002569 }
2570 }
drhbfe66312006-10-03 17:40:40 +00002571
drh7ed97b92010-01-20 13:07:21 +00002572 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002573 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002574
2575 *pResOut = reserved;
2576 return rc;
drhbfe66312006-10-03 17:40:40 +00002577}
2578
drh6b9d6dd2008-12-03 19:34:47 +00002579/*
drh308c2a52010-05-14 11:30:18 +00002580** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002581** of the following:
2582**
2583** (1) SHARED_LOCK
2584** (2) RESERVED_LOCK
2585** (3) PENDING_LOCK
2586** (4) EXCLUSIVE_LOCK
2587**
2588** Sometimes when requesting one lock state, additional lock states
2589** are inserted in between. The locking might fail on one of the later
2590** transitions leaving the lock state different from what it started but
2591** still short of its goal. The following chart shows the allowed
2592** transitions and the inserted intermediate states:
2593**
2594** UNLOCKED -> SHARED
2595** SHARED -> RESERVED
2596** SHARED -> (PENDING) -> EXCLUSIVE
2597** RESERVED -> (PENDING) -> EXCLUSIVE
2598** PENDING -> EXCLUSIVE
2599**
2600** This routine will only increase a lock. Use the sqlite3OsUnlock()
2601** routine to lower a locking level.
2602*/
drh308c2a52010-05-14 11:30:18 +00002603static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002604 int rc = SQLITE_OK;
2605 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002606 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002607 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002608
2609 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002610 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2611 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002612 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002613
drhbfe66312006-10-03 17:40:40 +00002614 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002615 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002616 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002617 */
drh308c2a52010-05-14 11:30:18 +00002618 if( pFile->eFileLock>=eFileLock ){
2619 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2620 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002621 return SQLITE_OK;
2622 }
2623
2624 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002625 ** (1) We never move from unlocked to anything higher than shared lock.
2626 ** (2) SQLite never explicitly requests a pendig lock.
2627 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002628 */
drh308c2a52010-05-14 11:30:18 +00002629 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2630 assert( eFileLock!=PENDING_LOCK );
2631 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002632
drh8af6c222010-05-14 12:43:01 +00002633 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002634 */
drh6c7d5c52008-11-21 20:32:33 +00002635 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002636 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002637
2638 /* If some thread using this PID has a lock via a different unixFile*
2639 ** handle that precludes the requested lock, return BUSY.
2640 */
drh8af6c222010-05-14 12:43:01 +00002641 if( (pFile->eFileLock!=pInode->eFileLock &&
2642 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002643 ){
2644 rc = SQLITE_BUSY;
2645 goto afp_end_lock;
2646 }
2647
2648 /* If a SHARED lock is requested, and some thread using this PID already
2649 ** has a SHARED or RESERVED lock, then increment reference counts and
2650 ** return SQLITE_OK.
2651 */
drh308c2a52010-05-14 11:30:18 +00002652 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002653 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002654 assert( eFileLock==SHARED_LOCK );
2655 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002656 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002657 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002658 pInode->nShared++;
2659 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002660 goto afp_end_lock;
2661 }
drhbfe66312006-10-03 17:40:40 +00002662
2663 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002664 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2665 ** be released.
2666 */
drh308c2a52010-05-14 11:30:18 +00002667 if( eFileLock==SHARED_LOCK
2668 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002669 ){
2670 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002671 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002672 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002673 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002674 goto afp_end_lock;
2675 }
2676 }
2677
2678 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002679 ** operating system calls for the specified lock.
2680 */
drh308c2a52010-05-14 11:30:18 +00002681 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002682 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002683 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002684
drh8af6c222010-05-14 12:43:01 +00002685 assert( pInode->nShared==0 );
2686 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002687
2688 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002689 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002690 /* note that the quality of the randomness doesn't matter that much */
2691 lk = random();
drh8af6c222010-05-14 12:43:01 +00002692 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002693 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002694 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002695 if( IS_LOCK_ERROR(lrc1) ){
2696 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002697 }
aswift5b1a2562008-08-22 00:22:35 +00002698 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002699 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002700
aswift5b1a2562008-08-22 00:22:35 +00002701 if( IS_LOCK_ERROR(lrc1) ) {
2702 pFile->lastErrno = lrc1Errno;
2703 rc = lrc1;
2704 goto afp_end_lock;
2705 } else if( IS_LOCK_ERROR(lrc2) ){
2706 rc = lrc2;
2707 goto afp_end_lock;
2708 } else if( lrc1 != SQLITE_OK ) {
2709 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002710 } else {
drh308c2a52010-05-14 11:30:18 +00002711 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002712 pInode->nLock++;
2713 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002714 }
drh8af6c222010-05-14 12:43:01 +00002715 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002716 /* We are trying for an exclusive lock but another thread in this
2717 ** same process is still holding a shared lock. */
2718 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002719 }else{
2720 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2721 ** assumed that there is a SHARED or greater lock on the file
2722 ** already.
2723 */
2724 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002725 assert( 0!=pFile->eFileLock );
2726 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002727 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002728 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002729 if( !failed ){
2730 context->reserved = 1;
2731 }
drhbfe66312006-10-03 17:40:40 +00002732 }
drh308c2a52010-05-14 11:30:18 +00002733 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002734 /* Acquire an EXCLUSIVE lock */
2735
2736 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002737 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002738 */
drh6b9d6dd2008-12-03 19:34:47 +00002739 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002740 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002741 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002742 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002743 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002744 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002745 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002746 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002747 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2748 ** a critical I/O error
2749 */
2750 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2751 SQLITE_IOERR_LOCK;
2752 goto afp_end_lock;
2753 }
2754 }else{
aswift5b1a2562008-08-22 00:22:35 +00002755 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002756 }
2757 }
aswift5b1a2562008-08-22 00:22:35 +00002758 if( failed ){
2759 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002760 }
2761 }
2762
2763 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002764 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002765 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002766 }else if( eFileLock==EXCLUSIVE_LOCK ){
2767 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002768 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002769 }
2770
2771afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002772 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002773 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2774 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002775 return rc;
2776}
2777
2778/*
drh308c2a52010-05-14 11:30:18 +00002779** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002780** must be either NO_LOCK or SHARED_LOCK.
2781**
2782** If the locking level of the file descriptor is already at or below
2783** the requested locking level, this routine is a no-op.
2784*/
drh308c2a52010-05-14 11:30:18 +00002785static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002786 int rc = SQLITE_OK;
2787 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002788 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002789 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2790 int skipShared = 0;
2791#ifdef SQLITE_TEST
2792 int h = pFile->h;
2793#endif
drhbfe66312006-10-03 17:40:40 +00002794
2795 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002796 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002797 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002798 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002799
drh308c2a52010-05-14 11:30:18 +00002800 assert( eFileLock<=SHARED_LOCK );
2801 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002802 return SQLITE_OK;
2803 }
drh6c7d5c52008-11-21 20:32:33 +00002804 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002805 pInode = pFile->pInode;
2806 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002807 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002808 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002809 SimulateIOErrorBenign(1);
2810 SimulateIOError( h=(-1) )
2811 SimulateIOErrorBenign(0);
2812
2813#ifndef NDEBUG
2814 /* When reducing a lock such that other processes can start
2815 ** reading the database file again, make sure that the
2816 ** transaction counter was updated if any part of the database
2817 ** file changed. If the transaction counter is not updated,
2818 ** other connections to the same file might not realize that
2819 ** the file has changed and hence might not know to flush their
2820 ** cache. The use of a stale cache can lead to database corruption.
2821 */
2822 assert( pFile->inNormalWrite==0
2823 || pFile->dbUpdate==0
2824 || pFile->transCntrChng==1 );
2825 pFile->inNormalWrite = 0;
2826#endif
aswiftaebf4132008-11-21 00:10:35 +00002827
drh308c2a52010-05-14 11:30:18 +00002828 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002829 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002830 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002831 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002832 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002833 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2834 } else {
2835 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002836 }
2837 }
drh308c2a52010-05-14 11:30:18 +00002838 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002839 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002840 }
drh308c2a52010-05-14 11:30:18 +00002841 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002842 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2843 if( !rc ){
2844 context->reserved = 0;
2845 }
aswiftaebf4132008-11-21 00:10:35 +00002846 }
drh8af6c222010-05-14 12:43:01 +00002847 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2848 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002849 }
aswiftaebf4132008-11-21 00:10:35 +00002850 }
drh308c2a52010-05-14 11:30:18 +00002851 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002852
drh7ed97b92010-01-20 13:07:21 +00002853 /* Decrement the shared lock counter. Release the lock using an
2854 ** OS call only when all threads in this same process have released
2855 ** the lock.
2856 */
drh8af6c222010-05-14 12:43:01 +00002857 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2858 pInode->nShared--;
2859 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002860 SimulateIOErrorBenign(1);
2861 SimulateIOError( h=(-1) )
2862 SimulateIOErrorBenign(0);
2863 if( !skipShared ){
2864 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2865 }
2866 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002867 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002868 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002869 }
2870 }
2871 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002872 pInode->nLock--;
2873 assert( pInode->nLock>=0 );
2874 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002875 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002876 }
2877 }
drhbfe66312006-10-03 17:40:40 +00002878 }
drh7ed97b92010-01-20 13:07:21 +00002879
drh6c7d5c52008-11-21 20:32:33 +00002880 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002881 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002882 return rc;
2883}
2884
2885/*
drh339eb0b2008-03-07 15:34:11 +00002886** Close a file & cleanup AFP specific locking context
2887*/
danielk1977e339d652008-06-28 11:23:00 +00002888static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002889 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002890 if( id ){
2891 unixFile *pFile = (unixFile*)id;
2892 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002893 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002894 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002895 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002896 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002897 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002898 ** the last lock is cleared.
2899 */
dan08da86a2009-08-21 17:18:03 +00002900 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002901 }
danb0ac3e32010-06-16 10:55:42 +00002902 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002903 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002904 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002905 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002906 }
drh7ed97b92010-01-20 13:07:21 +00002907 return rc;
drhbfe66312006-10-03 17:40:40 +00002908}
2909
drhd2cb50b2009-01-09 21:41:17 +00002910#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002911/*
2912** The code above is the AFP lock implementation. The code is specific
2913** to MacOSX and does not work on other unix platforms. No alternative
2914** is available. If you don't compile for a mac, then the "unix-afp"
2915** VFS is not available.
2916**
2917********************* End of the AFP lock implementation **********************
2918******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002919
drh7ed97b92010-01-20 13:07:21 +00002920/******************************************************************************
2921*************************** Begin NFS Locking ********************************/
2922
2923#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2924/*
drh308c2a52010-05-14 11:30:18 +00002925 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002926 ** must be either NO_LOCK or SHARED_LOCK.
2927 **
2928 ** If the locking level of the file descriptor is already at or below
2929 ** the requested locking level, this routine is a no-op.
2930 */
drh308c2a52010-05-14 11:30:18 +00002931static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002932 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002933}
2934
2935#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2936/*
2937** The code above is the NFS lock implementation. The code is specific
2938** to MacOSX and does not work on other unix platforms. No alternative
2939** is available.
2940**
2941********************* End of the NFS lock implementation **********************
2942******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002943
2944/******************************************************************************
2945**************** Non-locking sqlite3_file methods *****************************
2946**
2947** The next division contains implementations for all methods of the
2948** sqlite3_file object other than the locking methods. The locking
2949** methods were defined in divisions above (one locking method per
2950** division). Those methods that are common to all locking modes
2951** are gather together into this division.
2952*/
drhbfe66312006-10-03 17:40:40 +00002953
2954/*
drh734c9862008-11-28 15:37:20 +00002955** Seek to the offset passed as the second argument, then read cnt
2956** bytes into pBuf. Return the number of bytes actually read.
2957**
2958** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2959** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2960** one system to another. Since SQLite does not define USE_PREAD
2961** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2962** See tickets #2741 and #2681.
2963**
2964** To avoid stomping the errno value on a failed read the lastErrno value
2965** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002966*/
drh734c9862008-11-28 15:37:20 +00002967static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2968 int got;
drh58024642011-11-07 18:16:00 +00002969 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002970#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002971 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002972#endif
drh734c9862008-11-28 15:37:20 +00002973 TIMER_START;
drh58024642011-11-07 18:16:00 +00002974 do{
drh734c9862008-11-28 15:37:20 +00002975#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002976 got = osPread(id->h, pBuf, cnt, offset);
2977 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002978#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00002979 got = osPread64(id->h, pBuf, cnt, offset);
2980 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002981#else
drh58024642011-11-07 18:16:00 +00002982 newOffset = lseek(id->h, offset, SEEK_SET);
2983 SimulateIOError( newOffset-- );
2984 if( newOffset!=offset ){
2985 if( newOffset == -1 ){
2986 ((unixFile*)id)->lastErrno = errno;
2987 }else{
2988 ((unixFile*)id)->lastErrno = 0;
2989 }
2990 return -1;
drh734c9862008-11-28 15:37:20 +00002991 }
drh58024642011-11-07 18:16:00 +00002992 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00002993#endif
drh58024642011-11-07 18:16:00 +00002994 if( got==cnt ) break;
2995 if( got<0 ){
2996 if( errno==EINTR ){ got = 1; continue; }
2997 prior = 0;
2998 ((unixFile*)id)->lastErrno = errno;
2999 break;
3000 }else if( got>0 ){
3001 cnt -= got;
3002 offset += got;
3003 prior += got;
3004 pBuf = (void*)(got + (char*)pBuf);
3005 }
3006 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003007 TIMER_END;
drh58024642011-11-07 18:16:00 +00003008 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3009 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3010 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003011}
3012
3013/*
drh734c9862008-11-28 15:37:20 +00003014** Read data from a file into a buffer. Return SQLITE_OK if all
3015** bytes were read successfully and SQLITE_IOERR if anything goes
3016** wrong.
drh339eb0b2008-03-07 15:34:11 +00003017*/
drh734c9862008-11-28 15:37:20 +00003018static int unixRead(
3019 sqlite3_file *id,
3020 void *pBuf,
3021 int amt,
3022 sqlite3_int64 offset
3023){
dan08da86a2009-08-21 17:18:03 +00003024 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003025 int got;
3026 assert( id );
drh08c6d442009-02-09 17:34:07 +00003027
dan08da86a2009-08-21 17:18:03 +00003028 /* If this is a database file (not a journal, master-journal or temp
3029 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003030#if 0
dane946c392009-08-22 11:39:46 +00003031 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003032 || offset>=PENDING_BYTE+512
3033 || offset+amt<=PENDING_BYTE
3034 );
dan7c246102010-04-12 19:00:29 +00003035#endif
drh08c6d442009-02-09 17:34:07 +00003036
dan08da86a2009-08-21 17:18:03 +00003037 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003038 if( got==amt ){
3039 return SQLITE_OK;
3040 }else if( got<0 ){
3041 /* lastErrno set by seekAndRead */
3042 return SQLITE_IOERR_READ;
3043 }else{
dan08da86a2009-08-21 17:18:03 +00003044 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003045 /* Unread parts of the buffer must be zero-filled */
3046 memset(&((char*)pBuf)[got], 0, amt-got);
3047 return SQLITE_IOERR_SHORT_READ;
3048 }
3049}
3050
3051/*
3052** Seek to the offset in id->offset then read cnt bytes into pBuf.
3053** Return the number of bytes actually read. Update the offset.
3054**
3055** To avoid stomping the errno value on a failed write the lastErrno value
3056** is set before returning.
3057*/
3058static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3059 int got;
drh7ed97b92010-01-20 13:07:21 +00003060#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003061 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003062#endif
drh734c9862008-11-28 15:37:20 +00003063 TIMER_START;
3064#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003065 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003066#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003067 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003068#else
drhbd1e50c2011-08-19 14:54:12 +00003069 do{
3070 newOffset = lseek(id->h, offset, SEEK_SET);
3071 SimulateIOError( newOffset-- );
3072 if( newOffset!=offset ){
3073 if( newOffset == -1 ){
3074 ((unixFile*)id)->lastErrno = errno;
3075 }else{
3076 ((unixFile*)id)->lastErrno = 0;
3077 }
3078 return -1;
drh734c9862008-11-28 15:37:20 +00003079 }
drhbd1e50c2011-08-19 14:54:12 +00003080 got = osWrite(id->h, pBuf, cnt);
3081 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003082#endif
3083 TIMER_END;
3084 if( got<0 ){
3085 ((unixFile*)id)->lastErrno = errno;
3086 }
3087
drh308c2a52010-05-14 11:30:18 +00003088 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003089 return got;
3090}
3091
3092
3093/*
3094** Write data from a buffer into a file. Return SQLITE_OK on success
3095** or some other error code on failure.
3096*/
3097static int unixWrite(
3098 sqlite3_file *id,
3099 const void *pBuf,
3100 int amt,
3101 sqlite3_int64 offset
3102){
dan08da86a2009-08-21 17:18:03 +00003103 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003104 int wrote = 0;
3105 assert( id );
3106 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003107
dan08da86a2009-08-21 17:18:03 +00003108 /* If this is a database file (not a journal, master-journal or temp
3109 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003110#if 0
dane946c392009-08-22 11:39:46 +00003111 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003112 || offset>=PENDING_BYTE+512
3113 || offset+amt<=PENDING_BYTE
3114 );
dan7c246102010-04-12 19:00:29 +00003115#endif
drh08c6d442009-02-09 17:34:07 +00003116
drh8f941bc2009-01-14 23:03:40 +00003117#ifndef NDEBUG
3118 /* If we are doing a normal write to a database file (as opposed to
3119 ** doing a hot-journal rollback or a write to some file other than a
3120 ** normal database file) then record the fact that the database
3121 ** has changed. If the transaction counter is modified, record that
3122 ** fact too.
3123 */
dan08da86a2009-08-21 17:18:03 +00003124 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003125 pFile->dbUpdate = 1; /* The database has been modified */
3126 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003127 int rc;
drh8f941bc2009-01-14 23:03:40 +00003128 char oldCntr[4];
3129 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003130 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003131 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003132 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003133 pFile->transCntrChng = 1; /* The transaction counter has changed */
3134 }
3135 }
3136 }
3137#endif
3138
dan08da86a2009-08-21 17:18:03 +00003139 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003140 amt -= wrote;
3141 offset += wrote;
3142 pBuf = &((char*)pBuf)[wrote];
3143 }
3144 SimulateIOError(( wrote=(-1), amt=1 ));
3145 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003146
drh734c9862008-11-28 15:37:20 +00003147 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003148 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003149 /* lastErrno set by seekAndWrite */
3150 return SQLITE_IOERR_WRITE;
3151 }else{
dan08da86a2009-08-21 17:18:03 +00003152 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003153 return SQLITE_FULL;
3154 }
3155 }
dan6e09d692010-07-27 18:34:15 +00003156
drh734c9862008-11-28 15:37:20 +00003157 return SQLITE_OK;
3158}
3159
3160#ifdef SQLITE_TEST
3161/*
3162** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003163** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003164*/
3165int sqlite3_sync_count = 0;
3166int sqlite3_fullsync_count = 0;
3167#endif
3168
3169/*
drh89240432009-03-25 01:06:01 +00003170** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003171** Others do no. To be safe, we will stick with the (slightly slower)
3172** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003173** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003174*/
drh20f8e132011-08-31 21:01:55 +00003175#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003176# define fdatasync fsync
3177#endif
3178
3179/*
3180** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3181** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3182** only available on Mac OS X. But that could change.
3183*/
3184#ifdef F_FULLFSYNC
3185# define HAVE_FULLFSYNC 1
3186#else
3187# define HAVE_FULLFSYNC 0
3188#endif
3189
3190
3191/*
3192** The fsync() system call does not work as advertised on many
3193** unix systems. The following procedure is an attempt to make
3194** it work better.
3195**
3196** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3197** for testing when we want to run through the test suite quickly.
3198** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3199** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3200** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003201**
3202** SQLite sets the dataOnly flag if the size of the file is unchanged.
3203** The idea behind dataOnly is that it should only write the file content
3204** to disk, not the inode. We only set dataOnly if the file size is
3205** unchanged since the file size is part of the inode. However,
3206** Ted Ts'o tells us that fdatasync() will also write the inode if the
3207** file size has changed. The only real difference between fdatasync()
3208** and fsync(), Ted tells us, is that fdatasync() will not flush the
3209** inode if the mtime or owner or other inode attributes have changed.
3210** We only care about the file size, not the other file attributes, so
3211** as far as SQLite is concerned, an fdatasync() is always adequate.
3212** So, we always use fdatasync() if it is available, regardless of
3213** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003214*/
3215static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003216 int rc;
drh734c9862008-11-28 15:37:20 +00003217
3218 /* The following "ifdef/elif/else/" block has the same structure as
3219 ** the one below. It is replicated here solely to avoid cluttering
3220 ** up the real code with the UNUSED_PARAMETER() macros.
3221 */
3222#ifdef SQLITE_NO_SYNC
3223 UNUSED_PARAMETER(fd);
3224 UNUSED_PARAMETER(fullSync);
3225 UNUSED_PARAMETER(dataOnly);
3226#elif HAVE_FULLFSYNC
3227 UNUSED_PARAMETER(dataOnly);
3228#else
3229 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003230 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003231#endif
3232
3233 /* Record the number of times that we do a normal fsync() and
3234 ** FULLSYNC. This is used during testing to verify that this procedure
3235 ** gets called with the correct arguments.
3236 */
3237#ifdef SQLITE_TEST
3238 if( fullSync ) sqlite3_fullsync_count++;
3239 sqlite3_sync_count++;
3240#endif
3241
3242 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3243 ** no-op
3244 */
3245#ifdef SQLITE_NO_SYNC
3246 rc = SQLITE_OK;
3247#elif HAVE_FULLFSYNC
3248 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003249 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003250 }else{
3251 rc = 1;
3252 }
3253 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003254 ** It shouldn't be possible for fullfsync to fail on the local
3255 ** file system (on OSX), so failure indicates that FULLFSYNC
3256 ** isn't supported for this file system. So, attempt an fsync
3257 ** and (for now) ignore the overhead of a superfluous fcntl call.
3258 ** It'd be better to detect fullfsync support once and avoid
3259 ** the fcntl call every time sync is called.
3260 */
drh734c9862008-11-28 15:37:20 +00003261 if( rc ) rc = fsync(fd);
3262
drh7ed97b92010-01-20 13:07:21 +00003263#elif defined(__APPLE__)
3264 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3265 ** so currently we default to the macro that redefines fdatasync to fsync
3266 */
3267 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003268#else
drh0b647ff2009-03-21 14:41:04 +00003269 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003270#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003271 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003272 rc = fsync(fd);
3273 }
drh0b647ff2009-03-21 14:41:04 +00003274#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003275#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3276
3277 if( OS_VXWORKS && rc!= -1 ){
3278 rc = 0;
3279 }
chw97185482008-11-17 08:05:31 +00003280 return rc;
drhbfe66312006-10-03 17:40:40 +00003281}
3282
drh734c9862008-11-28 15:37:20 +00003283/*
drh0059eae2011-08-08 23:48:40 +00003284** Open a file descriptor to the directory containing file zFilename.
3285** If successful, *pFd is set to the opened file descriptor and
3286** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3287** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3288** value.
3289**
drh90315a22011-08-10 01:52:12 +00003290** The directory file descriptor is used for only one thing - to
3291** fsync() a directory to make sure file creation and deletion events
3292** are flushed to disk. Such fsyncs are not needed on newer
3293** journaling filesystems, but are required on older filesystems.
3294**
3295** This routine can be overridden using the xSetSysCall interface.
3296** The ability to override this routine was added in support of the
3297** chromium sandbox. Opening a directory is a security risk (we are
3298** told) so making it overrideable allows the chromium sandbox to
3299** replace this routine with a harmless no-op. To make this routine
3300** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3301** *pFd set to a negative number.
3302**
drh0059eae2011-08-08 23:48:40 +00003303** If SQLITE_OK is returned, the caller is responsible for closing
3304** the file descriptor *pFd using close().
3305*/
3306static int openDirectory(const char *zFilename, int *pFd){
3307 int ii;
3308 int fd = -1;
3309 char zDirname[MAX_PATHNAME+1];
3310
3311 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3312 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3313 if( ii>0 ){
3314 zDirname[ii] = '\0';
3315 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3316 if( fd>=0 ){
3317#ifdef FD_CLOEXEC
3318 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3319#endif
3320 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3321 }
3322 }
3323 *pFd = fd;
3324 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3325}
3326
3327/*
drh734c9862008-11-28 15:37:20 +00003328** Make sure all writes to a particular file are committed to disk.
3329**
3330** If dataOnly==0 then both the file itself and its metadata (file
3331** size, access time, etc) are synced. If dataOnly!=0 then only the
3332** file data is synced.
3333**
3334** Under Unix, also make sure that the directory entry for the file
3335** has been created by fsync-ing the directory that contains the file.
3336** If we do not do this and we encounter a power failure, the directory
3337** entry for the journal might not exist after we reboot. The next
3338** SQLite to access the file will not know that the journal exists (because
3339** the directory entry for the journal was never created) and the transaction
3340** will not roll back - possibly leading to database corruption.
3341*/
3342static int unixSync(sqlite3_file *id, int flags){
3343 int rc;
3344 unixFile *pFile = (unixFile*)id;
3345
3346 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3347 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3348
3349 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3350 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3351 || (flags&0x0F)==SQLITE_SYNC_FULL
3352 );
3353
3354 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3355 ** line is to test that doing so does not cause any problems.
3356 */
3357 SimulateDiskfullError( return SQLITE_FULL );
3358
3359 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003360 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003361 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3362 SimulateIOError( rc=1 );
3363 if( rc ){
3364 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003365 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003366 }
drh0059eae2011-08-08 23:48:40 +00003367
3368 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003369 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3370 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003371 */
3372 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3373 int dirfd;
3374 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003375 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003376 rc = osOpenDirectory(pFile->zPath, &dirfd);
3377 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003378 full_fsync(dirfd, 0, 0);
3379 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003380 }else if( rc==SQLITE_CANTOPEN ){
3381 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003382 }
drh0059eae2011-08-08 23:48:40 +00003383 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003384 }
3385 return rc;
3386}
3387
3388/*
3389** Truncate an open file to a specified size
3390*/
3391static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003392 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003393 int rc;
dan6e09d692010-07-27 18:34:15 +00003394 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003395 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003396
3397 /* If the user has configured a chunk-size for this file, truncate the
3398 ** file so that it consists of an integer number of chunks (i.e. the
3399 ** actual file size after the operation may be larger than the requested
3400 ** size).
3401 */
3402 if( pFile->szChunk ){
3403 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3404 }
3405
drhff812312011-02-23 13:33:46 +00003406 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003407 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003408 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003409 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003410 }else{
drh3313b142009-11-06 04:13:18 +00003411#ifndef NDEBUG
3412 /* If we are doing a normal write to a database file (as opposed to
3413 ** doing a hot-journal rollback or a write to some file other than a
3414 ** normal database file) and we truncate the file to zero length,
3415 ** that effectively updates the change counter. This might happen
3416 ** when restoring a database using the backup API from a zero-length
3417 ** source.
3418 */
dan6e09d692010-07-27 18:34:15 +00003419 if( pFile->inNormalWrite && nByte==0 ){
3420 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003421 }
3422#endif
3423
drh734c9862008-11-28 15:37:20 +00003424 return SQLITE_OK;
3425 }
3426}
3427
3428/*
3429** Determine the current size of a file in bytes
3430*/
3431static int unixFileSize(sqlite3_file *id, i64 *pSize){
3432 int rc;
3433 struct stat buf;
3434 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003435 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003436 SimulateIOError( rc=1 );
3437 if( rc!=0 ){
3438 ((unixFile*)id)->lastErrno = errno;
3439 return SQLITE_IOERR_FSTAT;
3440 }
3441 *pSize = buf.st_size;
3442
drh8af6c222010-05-14 12:43:01 +00003443 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003444 ** writes a single byte into that file in order to work around a bug
3445 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3446 ** layers, we need to report this file size as zero even though it is
3447 ** really 1. Ticket #3260.
3448 */
3449 if( *pSize==1 ) *pSize = 0;
3450
3451
3452 return SQLITE_OK;
3453}
3454
drhd2cb50b2009-01-09 21:41:17 +00003455#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003456/*
3457** Handler for proxy-locking file-control verbs. Defined below in the
3458** proxying locking division.
3459*/
3460static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003461#endif
drh715ff302008-12-03 22:32:44 +00003462
dan502019c2010-07-28 14:26:17 +00003463/*
3464** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003465** file-control operation. Enlarge the database to nBytes in size
3466** (rounded up to the next chunk-size). If the database is already
3467** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003468*/
3469static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003470 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003471 i64 nSize; /* Required file size */
3472 struct stat buf; /* Used to hold return values of fstat() */
3473
drh99ab3b12011-03-02 15:09:07 +00003474 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003475
3476 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3477 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003478
dan502019c2010-07-28 14:26:17 +00003479#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003480 /* The code below is handling the return value of osFallocate()
3481 ** correctly. posix_fallocate() is defined to "returns zero on success,
3482 ** or an error number on failure". See the manpage for details. */
3483 int err;
drhff812312011-02-23 13:33:46 +00003484 do{
dan661d71a2011-03-30 19:08:03 +00003485 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3486 }while( err==EINTR );
3487 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003488#else
3489 /* If the OS does not have posix_fallocate(), fake it. First use
3490 ** ftruncate() to set the file size, then write a single byte to
3491 ** the last byte in each block within the extended region. This
3492 ** is the same technique used by glibc to implement posix_fallocate()
3493 ** on systems that do not have a real fallocate() system call.
3494 */
3495 int nBlk = buf.st_blksize; /* File-system block size */
3496 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003497
drhff812312011-02-23 13:33:46 +00003498 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003499 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003500 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003501 }
3502 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003503 while( iWrite<nSize ){
3504 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3505 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003506 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003507 }
dan502019c2010-07-28 14:26:17 +00003508#endif
3509 }
3510 }
3511
3512 return SQLITE_OK;
3513}
danielk1977ad94b582007-08-20 06:44:22 +00003514
danielk1977e3026632004-06-22 11:29:02 +00003515/*
drhf12b3f62011-12-21 14:42:29 +00003516** If *pArg is inititially negative then this is a query. Set *pArg to
3517** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3518**
3519** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3520*/
3521static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3522 if( *pArg<0 ){
3523 *pArg = (pFile->ctrlFlags & mask)!=0;
3524 }else if( (*pArg)==0 ){
3525 pFile->ctrlFlags &= ~mask;
3526 }else{
3527 pFile->ctrlFlags |= mask;
3528 }
3529}
3530
3531/*
drh9e33c2c2007-08-31 18:34:59 +00003532** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003533*/
drhcc6bb3e2007-08-31 16:11:35 +00003534static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003535 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003536 switch( op ){
3537 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003538 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003539 return SQLITE_OK;
3540 }
drh7708e972008-11-29 00:56:52 +00003541 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003542 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003543 return SQLITE_OK;
3544 }
dan6e09d692010-07-27 18:34:15 +00003545 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003546 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003547 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003548 }
drh9ff27ec2010-05-19 19:26:05 +00003549 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003550 int rc;
3551 SimulateIOErrorBenign(1);
3552 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3553 SimulateIOErrorBenign(0);
3554 return rc;
drhf0b190d2011-07-26 16:03:07 +00003555 }
3556 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003557 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3558 return SQLITE_OK;
3559 }
3560 case SQLITE_FCNTL_ZERO_DAMAGE: {
3561 unixModeBit(pFile, UNIXFILE_ZERO_DAMAGE, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003562 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003563 }
drhde60fc22011-12-14 17:53:36 +00003564 case SQLITE_FCNTL_VFSNAME: {
3565 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3566 return SQLITE_OK;
3567 }
drh8f941bc2009-01-14 23:03:40 +00003568#ifndef NDEBUG
3569 /* The pager calls this method to signal that it has done
3570 ** a rollback and that the database is therefore unchanged and
3571 ** it hence it is OK for the transaction change counter to be
3572 ** unchanged.
3573 */
3574 case SQLITE_FCNTL_DB_UNCHANGED: {
3575 ((unixFile*)id)->dbUpdate = 0;
3576 return SQLITE_OK;
3577 }
3578#endif
drhd2cb50b2009-01-09 21:41:17 +00003579#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003580 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003581 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003582 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003583 }
drhd2cb50b2009-01-09 21:41:17 +00003584#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003585 case SQLITE_FCNTL_SYNC_OMITTED: {
3586 return SQLITE_OK; /* A no-op */
3587 }
drh9e33c2c2007-08-31 18:34:59 +00003588 }
drh0b52b7d2011-01-26 19:46:22 +00003589 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003590}
3591
3592/*
danielk1977a3d4c882007-03-23 10:08:38 +00003593** Return the sector size in bytes of the underlying block device for
3594** the specified file. This is almost always 512 bytes, but may be
3595** larger for some devices.
3596**
3597** SQLite code assumes this function cannot fail. It also assumes that
3598** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003599** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003600** same for both.
3601*/
drh1da88f02011-12-17 16:09:16 +00003602static int unixSectorSize(sqlite3_file *pFile){
3603 unixFile *p = (unixFile*)pFile;
3604 if( p->szSector==0 ){
3605#ifdef MISSING_STATVFS
drhf12b3f62011-12-21 14:42:29 +00003606 p->szSector = SQLITE_DEFAULT_SECTOR_SIZE/512;
drh1da88f02011-12-17 16:09:16 +00003607#else
3608 struct statvfs x;
3609 int sz;
3610 memset(&x, 0, sizeof(x));
3611 osStatvfs(p->zPath, &x);
drhf12b3f62011-12-21 14:42:29 +00003612 sz = (int)x.f_frsize;
drh1da88f02011-12-17 16:09:16 +00003613 if( sz<512 || sz>65536 || (sz&(sz-1))!=0 ){
drhf12b3f62011-12-21 14:42:29 +00003614 sz = SQLITE_DEFAULT_SECTOR_SIZE;
drh1da88f02011-12-17 16:09:16 +00003615 }
drhf12b3f62011-12-21 14:42:29 +00003616 p->szSector = sz/512;
drh1da88f02011-12-17 16:09:16 +00003617#endif
drh9c0e2932011-12-17 16:25:17 +00003618 }
drhf12b3f62011-12-21 14:42:29 +00003619 return p->szSector*512;
danielk1977a3d4c882007-03-23 10:08:38 +00003620}
3621
danielk197790949c22007-08-17 16:50:38 +00003622/*
drhf12b3f62011-12-21 14:42:29 +00003623** Return the device characteristics for the file.
3624**
3625** This VFS is set up to return SQLITE_IOCAP_ZERO_DAMAGE by default.
3626** However, that choice is contraversial sicne technically the underlying
3627** file system does not always provide ZERO_DAMAGE. (In other words, after
3628** a power-loss event, parts of the file that were never written might end
3629** up being altered.) However, non-ZERO-DAMAGE behavior is very, very rare.
3630** And asserting ZERO_DAMAGE makes a large reduction in the amount of required
3631** I/O. Hence, while ZERO_DAMAGE is on by default, there is a file-control
3632** available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003633*/
drhf12b3f62011-12-21 14:42:29 +00003634static int unixDeviceCharacteristics(sqlite3_file *id){
3635 unixFile *p = (unixFile*)id;
3636 return (p->ctrlFlags & UNIXFILE_ZERO_DAMAGE) ? SQLITE_IOCAP_ZERO_DAMAGE : 0;
danielk197762079062007-08-15 17:08:46 +00003637}
3638
drhd9e5c4f2010-05-12 18:01:39 +00003639#ifndef SQLITE_OMIT_WAL
3640
3641
3642/*
drhd91c68f2010-05-14 14:52:25 +00003643** Object used to represent an shared memory buffer.
3644**
3645** When multiple threads all reference the same wal-index, each thread
3646** has its own unixShm object, but they all point to a single instance
3647** of this unixShmNode object. In other words, each wal-index is opened
3648** only once per process.
3649**
3650** Each unixShmNode object is connected to a single unixInodeInfo object.
3651** We could coalesce this object into unixInodeInfo, but that would mean
3652** every open file that does not use shared memory (in other words, most
3653** open files) would have to carry around this extra information. So
3654** the unixInodeInfo object contains a pointer to this unixShmNode object
3655** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003656**
3657** unixMutexHeld() must be true when creating or destroying
3658** this object or while reading or writing the following fields:
3659**
3660** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003661**
3662** The following fields are read-only after the object is created:
3663**
3664** fid
3665** zFilename
3666**
drhd91c68f2010-05-14 14:52:25 +00003667** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003668** unixMutexHeld() is true when reading or writing any other field
3669** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003670*/
drhd91c68f2010-05-14 14:52:25 +00003671struct unixShmNode {
3672 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003673 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003674 char *zFilename; /* Name of the mmapped file */
3675 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003676 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003677 u16 nRegion; /* Size of array apRegion */
3678 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003679 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003680 int nRef; /* Number of unixShm objects pointing to this */
3681 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003682#ifdef SQLITE_DEBUG
3683 u8 exclMask; /* Mask of exclusive locks held */
3684 u8 sharedMask; /* Mask of shared locks held */
3685 u8 nextShmId; /* Next available unixShm.id value */
3686#endif
3687};
3688
3689/*
drhd9e5c4f2010-05-12 18:01:39 +00003690** Structure used internally by this VFS to record the state of an
3691** open shared memory connection.
3692**
drhd91c68f2010-05-14 14:52:25 +00003693** The following fields are initialized when this object is created and
3694** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003695**
drhd91c68f2010-05-14 14:52:25 +00003696** unixShm.pFile
3697** unixShm.id
3698**
3699** All other fields are read/write. The unixShm.pFile->mutex must be held
3700** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003701*/
3702struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003703 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3704 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003705 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003706 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003707 u16 sharedMask; /* Mask of shared locks held */
3708 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003709};
3710
3711/*
drhd9e5c4f2010-05-12 18:01:39 +00003712** Constants used for locking
3713*/
drhbd9676c2010-06-23 17:58:38 +00003714#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003715#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003716
drhd9e5c4f2010-05-12 18:01:39 +00003717/*
drh73b64e42010-05-30 19:55:15 +00003718** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003719**
3720** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3721** otherwise.
3722*/
3723static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003724 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3725 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003726 int ofst, /* First byte of the locking range */
3727 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003728){
3729 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003730 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003731
drhd91c68f2010-05-14 14:52:25 +00003732 /* Access to the unixShmNode object is serialized by the caller */
3733 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003734
drh73b64e42010-05-30 19:55:15 +00003735 /* Shared locks never span more than one byte */
3736 assert( n==1 || lockType!=F_RDLCK );
3737
3738 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003739 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003740
drh3cb93392011-03-12 18:10:44 +00003741 if( pShmNode->h>=0 ){
3742 /* Initialize the locking parameters */
3743 memset(&f, 0, sizeof(f));
3744 f.l_type = lockType;
3745 f.l_whence = SEEK_SET;
3746 f.l_start = ofst;
3747 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003748
drh3cb93392011-03-12 18:10:44 +00003749 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3750 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3751 }
drhd9e5c4f2010-05-12 18:01:39 +00003752
3753 /* Update the global lock state and do debug tracing */
3754#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003755 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003756 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003757 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003758 if( rc==SQLITE_OK ){
3759 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003760 OSTRACE(("unlock %d ok", ofst));
3761 pShmNode->exclMask &= ~mask;
3762 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003763 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003764 OSTRACE(("read-lock %d ok", ofst));
3765 pShmNode->exclMask &= ~mask;
3766 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003767 }else{
3768 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003769 OSTRACE(("write-lock %d ok", ofst));
3770 pShmNode->exclMask |= mask;
3771 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003772 }
3773 }else{
3774 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003775 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003776 }else if( lockType==F_RDLCK ){
3777 OSTRACE(("read-lock failed"));
3778 }else{
3779 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003780 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003781 }
3782 }
drh20e1f082010-05-31 16:10:12 +00003783 OSTRACE((" - afterwards %03x,%03x\n",
3784 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003785 }
drhd9e5c4f2010-05-12 18:01:39 +00003786#endif
3787
3788 return rc;
3789}
3790
drhd9e5c4f2010-05-12 18:01:39 +00003791
3792/*
drhd91c68f2010-05-14 14:52:25 +00003793** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003794**
3795** This is not a VFS shared-memory method; it is a utility function called
3796** by VFS shared-memory methods.
3797*/
drhd91c68f2010-05-14 14:52:25 +00003798static void unixShmPurge(unixFile *pFd){
3799 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003800 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003801 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003802 int i;
drhd91c68f2010-05-14 14:52:25 +00003803 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003804 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003805 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003806 if( p->h>=0 ){
3807 munmap(p->apRegion[i], p->szRegion);
3808 }else{
3809 sqlite3_free(p->apRegion[i]);
3810 }
dan13a3cb82010-06-11 19:04:21 +00003811 }
dan18801912010-06-14 14:07:50 +00003812 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003813 if( p->h>=0 ){
3814 robust_close(pFd, p->h, __LINE__);
3815 p->h = -1;
3816 }
drhd91c68f2010-05-14 14:52:25 +00003817 p->pInode->pShmNode = 0;
3818 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003819 }
3820}
3821
3822/*
danda9fe0c2010-07-13 18:44:03 +00003823** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003824** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003825**
drh7234c6d2010-06-19 15:10:09 +00003826** The file used to implement shared-memory is in the same directory
3827** as the open database file and has the same name as the open database
3828** file with the "-shm" suffix added. For example, if the database file
3829** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003830** for shared memory will be called "/home/user1/config.db-shm".
3831**
3832** Another approach to is to use files in /dev/shm or /dev/tmp or an
3833** some other tmpfs mount. But if a file in a different directory
3834** from the database file is used, then differing access permissions
3835** or a chroot() might cause two different processes on the same
3836** database to end up using different files for shared memory -
3837** meaning that their memory would not really be shared - resulting
3838** in database corruption. Nevertheless, this tmpfs file usage
3839** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3840** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3841** option results in an incompatible build of SQLite; builds of SQLite
3842** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3843** same database file at the same time, database corruption will likely
3844** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3845** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003846**
3847** When opening a new shared-memory file, if no other instances of that
3848** file are currently open, in this process or in other processes, then
3849** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003850**
3851** If the original database file (pDbFd) is using the "unix-excl" VFS
3852** that means that an exclusive lock is held on the database file and
3853** that no other processes are able to read or write the database. In
3854** that case, we do not really need shared memory. No shared memory
3855** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003856*/
danda9fe0c2010-07-13 18:44:03 +00003857static int unixOpenSharedMemory(unixFile *pDbFd){
3858 struct unixShm *p = 0; /* The connection to be opened */
3859 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3860 int rc; /* Result code */
3861 unixInodeInfo *pInode; /* The inode of fd */
3862 char *zShmFilename; /* Name of the file used for SHM */
3863 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003864
danda9fe0c2010-07-13 18:44:03 +00003865 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003866 p = sqlite3_malloc( sizeof(*p) );
3867 if( p==0 ) return SQLITE_NOMEM;
3868 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003869 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003870
danda9fe0c2010-07-13 18:44:03 +00003871 /* Check to see if a unixShmNode object already exists. Reuse an existing
3872 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003873 */
3874 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003875 pInode = pDbFd->pInode;
3876 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003877 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003878 struct stat sStat; /* fstat() info for database file */
3879
3880 /* Call fstat() to figure out the permissions on the database file. If
3881 ** a new *-shm file is created, an attempt will be made to create it
3882 ** with the same permissions. The actual permissions the file is created
3883 ** with are subject to the current umask setting.
3884 */
drh3cb93392011-03-12 18:10:44 +00003885 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003886 rc = SQLITE_IOERR_FSTAT;
3887 goto shm_open_err;
3888 }
3889
drha4ced192010-07-15 18:32:40 +00003890#ifdef SQLITE_SHM_DIRECTORY
3891 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3892#else
drh7234c6d2010-06-19 15:10:09 +00003893 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003894#endif
drh7234c6d2010-06-19 15:10:09 +00003895 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003896 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003897 rc = SQLITE_NOMEM;
3898 goto shm_open_err;
3899 }
drhd91c68f2010-05-14 14:52:25 +00003900 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003901 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003902#ifdef SQLITE_SHM_DIRECTORY
3903 sqlite3_snprintf(nShmFilename, zShmFilename,
3904 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3905 (u32)sStat.st_ino, (u32)sStat.st_dev);
3906#else
drh7234c6d2010-06-19 15:10:09 +00003907 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003908 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003909#endif
drhd91c68f2010-05-14 14:52:25 +00003910 pShmNode->h = -1;
3911 pDbFd->pInode->pShmNode = pShmNode;
3912 pShmNode->pInode = pDbFd->pInode;
3913 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3914 if( pShmNode->mutex==0 ){
3915 rc = SQLITE_NOMEM;
3916 goto shm_open_err;
3917 }
drhd9e5c4f2010-05-12 18:01:39 +00003918
drh3cb93392011-03-12 18:10:44 +00003919 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003920 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003921 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003922 openFlags = O_RDONLY;
3923 pShmNode->isReadonly = 1;
3924 }
3925 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003926 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003927 if( pShmNode->h<0 ){
3928 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3929 goto shm_open_err;
3930 }
drhd9e5c4f2010-05-12 18:01:39 +00003931 }
drh3cb93392011-03-12 18:10:44 +00003932
3933 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003934 ** If not, truncate the file to zero length.
3935 */
3936 rc = SQLITE_OK;
3937 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3938 if( robust_ftruncate(pShmNode->h, 0) ){
3939 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003940 }
3941 }
drh66dfec8b2011-06-01 20:01:49 +00003942 if( rc==SQLITE_OK ){
3943 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3944 }
3945 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003946 }
drhd9e5c4f2010-05-12 18:01:39 +00003947 }
3948
drhd91c68f2010-05-14 14:52:25 +00003949 /* Make the new connection a child of the unixShmNode */
3950 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003951#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003952 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003953#endif
drhd91c68f2010-05-14 14:52:25 +00003954 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003955 pDbFd->pShm = p;
3956 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003957
3958 /* The reference count on pShmNode has already been incremented under
3959 ** the cover of the unixEnterMutex() mutex and the pointer from the
3960 ** new (struct unixShm) object to the pShmNode has been set. All that is
3961 ** left to do is to link the new object into the linked list starting
3962 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3963 ** mutex.
3964 */
3965 sqlite3_mutex_enter(pShmNode->mutex);
3966 p->pNext = pShmNode->pFirst;
3967 pShmNode->pFirst = p;
3968 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003969 return SQLITE_OK;
3970
3971 /* Jump here on any error */
3972shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003973 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003974 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003975 unixLeaveMutex();
3976 return rc;
3977}
3978
3979/*
danda9fe0c2010-07-13 18:44:03 +00003980** This function is called to obtain a pointer to region iRegion of the
3981** shared-memory associated with the database file fd. Shared-memory regions
3982** are numbered starting from zero. Each shared-memory region is szRegion
3983** bytes in size.
3984**
3985** If an error occurs, an error code is returned and *pp is set to NULL.
3986**
3987** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3988** region has not been allocated (by any client, including one running in a
3989** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3990** bExtend is non-zero and the requested shared-memory region has not yet
3991** been allocated, it is allocated by this function.
3992**
3993** If the shared-memory region has already been allocated or is allocated by
3994** this call as described above, then it is mapped into this processes
3995** address space (if it is not already), *pp is set to point to the mapped
3996** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003997*/
danda9fe0c2010-07-13 18:44:03 +00003998static int unixShmMap(
3999 sqlite3_file *fd, /* Handle open on database file */
4000 int iRegion, /* Region to retrieve */
4001 int szRegion, /* Size of regions */
4002 int bExtend, /* True to extend file if necessary */
4003 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004004){
danda9fe0c2010-07-13 18:44:03 +00004005 unixFile *pDbFd = (unixFile*)fd;
4006 unixShm *p;
4007 unixShmNode *pShmNode;
4008 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004009
danda9fe0c2010-07-13 18:44:03 +00004010 /* If the shared-memory file has not yet been opened, open it now. */
4011 if( pDbFd->pShm==0 ){
4012 rc = unixOpenSharedMemory(pDbFd);
4013 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004014 }
drhd9e5c4f2010-05-12 18:01:39 +00004015
danda9fe0c2010-07-13 18:44:03 +00004016 p = pDbFd->pShm;
4017 pShmNode = p->pShmNode;
4018 sqlite3_mutex_enter(pShmNode->mutex);
4019 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004020 assert( pShmNode->pInode==pDbFd->pInode );
4021 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4022 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004023
4024 if( pShmNode->nRegion<=iRegion ){
4025 char **apNew; /* New apRegion[] array */
4026 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4027 struct stat sStat; /* Used by fstat() */
4028
4029 pShmNode->szRegion = szRegion;
4030
drh3cb93392011-03-12 18:10:44 +00004031 if( pShmNode->h>=0 ){
4032 /* The requested region is not mapped into this processes address space.
4033 ** Check to see if it has been allocated (i.e. if the wal-index file is
4034 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004035 */
drh3cb93392011-03-12 18:10:44 +00004036 if( osFstat(pShmNode->h, &sStat) ){
4037 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004038 goto shmpage_out;
4039 }
drh3cb93392011-03-12 18:10:44 +00004040
4041 if( sStat.st_size<nByte ){
4042 /* The requested memory region does not exist. If bExtend is set to
4043 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4044 **
4045 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4046 ** the requested memory region.
4047 */
4048 if( !bExtend ) goto shmpage_out;
4049 if( robust_ftruncate(pShmNode->h, nByte) ){
4050 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4051 pShmNode->zFilename);
4052 goto shmpage_out;
4053 }
4054 }
danda9fe0c2010-07-13 18:44:03 +00004055 }
4056
4057 /* Map the requested memory region into this processes address space. */
4058 apNew = (char **)sqlite3_realloc(
4059 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4060 );
4061 if( !apNew ){
4062 rc = SQLITE_IOERR_NOMEM;
4063 goto shmpage_out;
4064 }
4065 pShmNode->apRegion = apNew;
4066 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004067 void *pMem;
4068 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004069 pMem = mmap(0, szRegion,
4070 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004071 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4072 );
4073 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004074 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004075 goto shmpage_out;
4076 }
4077 }else{
4078 pMem = sqlite3_malloc(szRegion);
4079 if( pMem==0 ){
4080 rc = SQLITE_NOMEM;
4081 goto shmpage_out;
4082 }
4083 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004084 }
4085 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4086 pShmNode->nRegion++;
4087 }
4088 }
4089
4090shmpage_out:
4091 if( pShmNode->nRegion>iRegion ){
4092 *pp = pShmNode->apRegion[iRegion];
4093 }else{
4094 *pp = 0;
4095 }
drh66dfec8b2011-06-01 20:01:49 +00004096 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004097 sqlite3_mutex_leave(pShmNode->mutex);
4098 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004099}
4100
4101/*
drhd9e5c4f2010-05-12 18:01:39 +00004102** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004103**
4104** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4105** different here than in posix. In xShmLock(), one can go from unlocked
4106** to shared and back or from unlocked to exclusive and back. But one may
4107** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004108*/
4109static int unixShmLock(
4110 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004111 int ofst, /* First lock to acquire or release */
4112 int n, /* Number of locks to acquire or release */
4113 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004114){
drh73b64e42010-05-30 19:55:15 +00004115 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4116 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4117 unixShm *pX; /* For looping over all siblings */
4118 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4119 int rc = SQLITE_OK; /* Result code */
4120 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004121
drhd91c68f2010-05-14 14:52:25 +00004122 assert( pShmNode==pDbFd->pInode->pShmNode );
4123 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004124 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004125 assert( n>=1 );
4126 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4127 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4128 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4129 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4130 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004131 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4132 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004133
drhc99597c2010-05-31 01:41:15 +00004134 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004135 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004136 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004137 if( flags & SQLITE_SHM_UNLOCK ){
4138 u16 allMask = 0; /* Mask of locks held by siblings */
4139
4140 /* See if any siblings hold this same lock */
4141 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4142 if( pX==p ) continue;
4143 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4144 allMask |= pX->sharedMask;
4145 }
4146
4147 /* Unlock the system-level locks */
4148 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004149 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004150 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004151 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004152 }
drh73b64e42010-05-30 19:55:15 +00004153
4154 /* Undo the local locks */
4155 if( rc==SQLITE_OK ){
4156 p->exclMask &= ~mask;
4157 p->sharedMask &= ~mask;
4158 }
4159 }else if( flags & SQLITE_SHM_SHARED ){
4160 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4161
4162 /* Find out which shared locks are already held by sibling connections.
4163 ** If any sibling already holds an exclusive lock, go ahead and return
4164 ** SQLITE_BUSY.
4165 */
4166 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004167 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004168 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004169 break;
4170 }
4171 allShared |= pX->sharedMask;
4172 }
4173
4174 /* Get shared locks at the system level, if necessary */
4175 if( rc==SQLITE_OK ){
4176 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004177 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004178 }else{
drh73b64e42010-05-30 19:55:15 +00004179 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004180 }
drhd9e5c4f2010-05-12 18:01:39 +00004181 }
drh73b64e42010-05-30 19:55:15 +00004182
4183 /* Get the local shared locks */
4184 if( rc==SQLITE_OK ){
4185 p->sharedMask |= mask;
4186 }
4187 }else{
4188 /* Make sure no sibling connections hold locks that will block this
4189 ** lock. If any do, return SQLITE_BUSY right away.
4190 */
4191 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004192 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4193 rc = SQLITE_BUSY;
4194 break;
4195 }
4196 }
4197
4198 /* Get the exclusive locks at the system level. Then if successful
4199 ** also mark the local connection as being locked.
4200 */
4201 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004202 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004203 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004204 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004205 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004206 }
drhd9e5c4f2010-05-12 18:01:39 +00004207 }
4208 }
drhd91c68f2010-05-14 14:52:25 +00004209 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004210 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4211 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004212 return rc;
4213}
4214
drh286a2882010-05-20 23:51:06 +00004215/*
4216** Implement a memory barrier or memory fence on shared memory.
4217**
4218** All loads and stores begun before the barrier must complete before
4219** any load or store begun after the barrier.
4220*/
4221static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004222 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004223){
drhff828942010-06-26 21:34:06 +00004224 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004225 unixEnterMutex();
4226 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004227}
4228
dan18801912010-06-14 14:07:50 +00004229/*
danda9fe0c2010-07-13 18:44:03 +00004230** Close a connection to shared-memory. Delete the underlying
4231** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004232**
4233** If there is no shared memory associated with the connection then this
4234** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004235*/
danda9fe0c2010-07-13 18:44:03 +00004236static int unixShmUnmap(
4237 sqlite3_file *fd, /* The underlying database file */
4238 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004239){
danda9fe0c2010-07-13 18:44:03 +00004240 unixShm *p; /* The connection to be closed */
4241 unixShmNode *pShmNode; /* The underlying shared-memory file */
4242 unixShm **pp; /* For looping over sibling connections */
4243 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004244
danda9fe0c2010-07-13 18:44:03 +00004245 pDbFd = (unixFile*)fd;
4246 p = pDbFd->pShm;
4247 if( p==0 ) return SQLITE_OK;
4248 pShmNode = p->pShmNode;
4249
4250 assert( pShmNode==pDbFd->pInode->pShmNode );
4251 assert( pShmNode->pInode==pDbFd->pInode );
4252
4253 /* Remove connection p from the set of connections associated
4254 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004255 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004256 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4257 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004258
danda9fe0c2010-07-13 18:44:03 +00004259 /* Free the connection p */
4260 sqlite3_free(p);
4261 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004262 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004263
4264 /* If pShmNode->nRef has reached 0, then close the underlying
4265 ** shared-memory file, too */
4266 unixEnterMutex();
4267 assert( pShmNode->nRef>0 );
4268 pShmNode->nRef--;
4269 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004270 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004271 unixShmPurge(pDbFd);
4272 }
4273 unixLeaveMutex();
4274
4275 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004276}
drh286a2882010-05-20 23:51:06 +00004277
danda9fe0c2010-07-13 18:44:03 +00004278
drhd9e5c4f2010-05-12 18:01:39 +00004279#else
drh6b017cc2010-06-14 18:01:46 +00004280# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004281# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004282# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004283# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004284#endif /* #ifndef SQLITE_OMIT_WAL */
4285
drh734c9862008-11-28 15:37:20 +00004286/*
4287** Here ends the implementation of all sqlite3_file methods.
4288**
4289********************** End sqlite3_file Methods *******************************
4290******************************************************************************/
4291
4292/*
drh6b9d6dd2008-12-03 19:34:47 +00004293** This division contains definitions of sqlite3_io_methods objects that
4294** implement various file locking strategies. It also contains definitions
4295** of "finder" functions. A finder-function is used to locate the appropriate
4296** sqlite3_io_methods object for a particular database file. The pAppData
4297** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4298** the correct finder-function for that VFS.
4299**
4300** Most finder functions return a pointer to a fixed sqlite3_io_methods
4301** object. The only interesting finder-function is autolockIoFinder, which
4302** looks at the filesystem type and tries to guess the best locking
4303** strategy from that.
4304**
drh1875f7a2008-12-08 18:19:17 +00004305** For finder-funtion F, two objects are created:
4306**
4307** (1) The real finder-function named "FImpt()".
4308**
dane946c392009-08-22 11:39:46 +00004309** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004310**
4311**
4312** A pointer to the F pointer is used as the pAppData value for VFS
4313** objects. We have to do this instead of letting pAppData point
4314** directly at the finder-function since C90 rules prevent a void*
4315** from be cast into a function pointer.
4316**
drh6b9d6dd2008-12-03 19:34:47 +00004317**
drh7708e972008-11-29 00:56:52 +00004318** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004319**
drh7708e972008-11-29 00:56:52 +00004320** * A constant sqlite3_io_methods object call METHOD that has locking
4321** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4322**
4323** * An I/O method finder function called FINDER that returns a pointer
4324** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004325*/
drhd9e5c4f2010-05-12 18:01:39 +00004326#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004327static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004328 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004329 CLOSE, /* xClose */ \
4330 unixRead, /* xRead */ \
4331 unixWrite, /* xWrite */ \
4332 unixTruncate, /* xTruncate */ \
4333 unixSync, /* xSync */ \
4334 unixFileSize, /* xFileSize */ \
4335 LOCK, /* xLock */ \
4336 UNLOCK, /* xUnlock */ \
4337 CKLOCK, /* xCheckReservedLock */ \
4338 unixFileControl, /* xFileControl */ \
4339 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004340 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004341 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004342 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004343 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004344 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004345}; \
drh0c2694b2009-09-03 16:23:44 +00004346static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4347 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004348 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004349} \
drh0c2694b2009-09-03 16:23:44 +00004350static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004351 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004352
4353/*
4354** Here are all of the sqlite3_io_methods objects for each of the
4355** locking strategies. Functions that return pointers to these methods
4356** are also created.
4357*/
4358IOMETHODS(
4359 posixIoFinder, /* Finder function name */
4360 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004361 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004362 unixClose, /* xClose method */
4363 unixLock, /* xLock method */
4364 unixUnlock, /* xUnlock method */
4365 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004366)
drh7708e972008-11-29 00:56:52 +00004367IOMETHODS(
4368 nolockIoFinder, /* Finder function name */
4369 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004370 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004371 nolockClose, /* xClose method */
4372 nolockLock, /* xLock method */
4373 nolockUnlock, /* xUnlock method */
4374 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004375)
drh7708e972008-11-29 00:56:52 +00004376IOMETHODS(
4377 dotlockIoFinder, /* Finder function name */
4378 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004379 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004380 dotlockClose, /* xClose method */
4381 dotlockLock, /* xLock method */
4382 dotlockUnlock, /* xUnlock method */
4383 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004384)
drh7708e972008-11-29 00:56:52 +00004385
chw78a13182009-04-07 05:35:03 +00004386#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004387IOMETHODS(
4388 flockIoFinder, /* Finder function name */
4389 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004390 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004391 flockClose, /* xClose method */
4392 flockLock, /* xLock method */
4393 flockUnlock, /* xUnlock method */
4394 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004395)
drh7708e972008-11-29 00:56:52 +00004396#endif
4397
drh6c7d5c52008-11-21 20:32:33 +00004398#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004399IOMETHODS(
4400 semIoFinder, /* Finder function name */
4401 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004402 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004403 semClose, /* xClose method */
4404 semLock, /* xLock method */
4405 semUnlock, /* xUnlock method */
4406 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004407)
aswiftaebf4132008-11-21 00:10:35 +00004408#endif
drh7708e972008-11-29 00:56:52 +00004409
drhd2cb50b2009-01-09 21:41:17 +00004410#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004411IOMETHODS(
4412 afpIoFinder, /* Finder function name */
4413 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004414 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004415 afpClose, /* xClose method */
4416 afpLock, /* xLock method */
4417 afpUnlock, /* xUnlock method */
4418 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004419)
drh715ff302008-12-03 22:32:44 +00004420#endif
4421
4422/*
4423** The proxy locking method is a "super-method" in the sense that it
4424** opens secondary file descriptors for the conch and lock files and
4425** it uses proxy, dot-file, AFP, and flock() locking methods on those
4426** secondary files. For this reason, the division that implements
4427** proxy locking is located much further down in the file. But we need
4428** to go ahead and define the sqlite3_io_methods and finder function
4429** for proxy locking here. So we forward declare the I/O methods.
4430*/
drhd2cb50b2009-01-09 21:41:17 +00004431#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004432static int proxyClose(sqlite3_file*);
4433static int proxyLock(sqlite3_file*, int);
4434static int proxyUnlock(sqlite3_file*, int);
4435static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004436IOMETHODS(
4437 proxyIoFinder, /* Finder function name */
4438 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004439 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004440 proxyClose, /* xClose method */
4441 proxyLock, /* xLock method */
4442 proxyUnlock, /* xUnlock method */
4443 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004444)
aswiftaebf4132008-11-21 00:10:35 +00004445#endif
drh7708e972008-11-29 00:56:52 +00004446
drh7ed97b92010-01-20 13:07:21 +00004447/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4448#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4449IOMETHODS(
4450 nfsIoFinder, /* Finder function name */
4451 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004452 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004453 unixClose, /* xClose method */
4454 unixLock, /* xLock method */
4455 nfsUnlock, /* xUnlock method */
4456 unixCheckReservedLock /* xCheckReservedLock method */
4457)
4458#endif
drh7708e972008-11-29 00:56:52 +00004459
drhd2cb50b2009-01-09 21:41:17 +00004460#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004461/*
drh6b9d6dd2008-12-03 19:34:47 +00004462** This "finder" function attempts to determine the best locking strategy
4463** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004464** object that implements that strategy.
4465**
4466** This is for MacOSX only.
4467*/
drh1875f7a2008-12-08 18:19:17 +00004468static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004469 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004470 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004471){
4472 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004473 const char *zFilesystem; /* Filesystem type name */
4474 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004475 } aMap[] = {
4476 { "hfs", &posixIoMethods },
4477 { "ufs", &posixIoMethods },
4478 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004479 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004480 { "webdav", &nolockIoMethods },
4481 { 0, 0 }
4482 };
4483 int i;
4484 struct statfs fsInfo;
4485 struct flock lockInfo;
4486
4487 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004488 /* If filePath==NULL that means we are dealing with a transient file
4489 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004490 return &nolockIoMethods;
4491 }
4492 if( statfs(filePath, &fsInfo) != -1 ){
4493 if( fsInfo.f_flags & MNT_RDONLY ){
4494 return &nolockIoMethods;
4495 }
4496 for(i=0; aMap[i].zFilesystem; i++){
4497 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4498 return aMap[i].pMethods;
4499 }
4500 }
4501 }
4502
4503 /* Default case. Handles, amongst others, "nfs".
4504 ** Test byte-range lock using fcntl(). If the call succeeds,
4505 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004506 */
drh7708e972008-11-29 00:56:52 +00004507 lockInfo.l_len = 1;
4508 lockInfo.l_start = 0;
4509 lockInfo.l_whence = SEEK_SET;
4510 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004511 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004512 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4513 return &nfsIoMethods;
4514 } else {
4515 return &posixIoMethods;
4516 }
drh7708e972008-11-29 00:56:52 +00004517 }else{
4518 return &dotlockIoMethods;
4519 }
4520}
drh0c2694b2009-09-03 16:23:44 +00004521static const sqlite3_io_methods
4522 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004523
drhd2cb50b2009-01-09 21:41:17 +00004524#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004525
chw78a13182009-04-07 05:35:03 +00004526#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4527/*
4528** This "finder" function attempts to determine the best locking strategy
4529** for the database file "filePath". It then returns the sqlite3_io_methods
4530** object that implements that strategy.
4531**
4532** This is for VXWorks only.
4533*/
4534static const sqlite3_io_methods *autolockIoFinderImpl(
4535 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004536 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004537){
4538 struct flock lockInfo;
4539
4540 if( !filePath ){
4541 /* If filePath==NULL that means we are dealing with a transient file
4542 ** that does not need to be locked. */
4543 return &nolockIoMethods;
4544 }
4545
4546 /* Test if fcntl() is supported and use POSIX style locks.
4547 ** Otherwise fall back to the named semaphore method.
4548 */
4549 lockInfo.l_len = 1;
4550 lockInfo.l_start = 0;
4551 lockInfo.l_whence = SEEK_SET;
4552 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004553 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004554 return &posixIoMethods;
4555 }else{
4556 return &semIoMethods;
4557 }
4558}
drh0c2694b2009-09-03 16:23:44 +00004559static const sqlite3_io_methods
4560 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004561
4562#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4563
drh7708e972008-11-29 00:56:52 +00004564/*
4565** An abstract type for a pointer to a IO method finder function:
4566*/
drh0c2694b2009-09-03 16:23:44 +00004567typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004568
aswiftaebf4132008-11-21 00:10:35 +00004569
drh734c9862008-11-28 15:37:20 +00004570/****************************************************************************
4571**************************** sqlite3_vfs methods ****************************
4572**
4573** This division contains the implementation of methods on the
4574** sqlite3_vfs object.
4575*/
4576
danielk1977a3d4c882007-03-23 10:08:38 +00004577/*
danielk1977e339d652008-06-28 11:23:00 +00004578** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004579*/
4580static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004581 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004582 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004583 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004584 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004585 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004586 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004587 int isDelete, /* Delete on close if true */
4588 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004589){
drh7708e972008-11-29 00:56:52 +00004590 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004591 unixFile *pNew = (unixFile *)pId;
4592 int rc = SQLITE_OK;
4593
drh8af6c222010-05-14 12:43:01 +00004594 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004595
dane946c392009-08-22 11:39:46 +00004596 /* Parameter isDelete is only used on vxworks. Express this explicitly
4597 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004598 */
drh7708e972008-11-29 00:56:52 +00004599 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004600
dan00157392010-10-05 11:33:15 +00004601 /* Usually the path zFilename should not be a relative pathname. The
4602 ** exception is when opening the proxy "conch" file in builds that
4603 ** include the special Apple locking styles.
4604 */
dan00157392010-10-05 11:33:15 +00004605#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004606 assert( zFilename==0 || zFilename[0]=='/'
4607 || pVfs->pAppData==(void*)&autolockIoFinder );
4608#else
4609 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004610#endif
dan00157392010-10-05 11:33:15 +00004611
drhb07028f2011-10-14 21:49:18 +00004612 /* No locking occurs in temporary files */
4613 assert( zFilename!=0 || noLock );
4614
drh308c2a52010-05-14 11:30:18 +00004615 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004616 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004617 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004618 pNew->zPath = zFilename;
drhbec7c972011-12-23 00:25:02 +00004619 pNew->ctrlFlags = 0;
4620 if( sqlite3_uri_boolean(zFilename, "zero_damage", 1) ){
4621 pNew->ctrlFlags |= UNIXFILE_ZERO_DAMAGE;
4622 }
drha7e61d82011-03-12 17:02:57 +00004623 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004624 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004625 }
drh77197112011-03-15 19:08:48 +00004626 if( isReadOnly ){
4627 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4628 }
drh0059eae2011-08-08 23:48:40 +00004629 if( syncDir ){
4630 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4631 }
drh339eb0b2008-03-07 15:34:11 +00004632
drh6c7d5c52008-11-21 20:32:33 +00004633#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004634 pNew->pId = vxworksFindFileId(zFilename);
4635 if( pNew->pId==0 ){
4636 noLock = 1;
4637 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004638 }
4639#endif
4640
drhda0e7682008-07-30 15:27:54 +00004641 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004642 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004643 }else{
drh0c2694b2009-09-03 16:23:44 +00004644 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004645#if SQLITE_ENABLE_LOCKING_STYLE
4646 /* Cache zFilename in the locking context (AFP and dotlock override) for
4647 ** proxyLock activation is possible (remote proxy is based on db name)
4648 ** zFilename remains valid until file is closed, to support */
4649 pNew->lockingContext = (void*)zFilename;
4650#endif
drhda0e7682008-07-30 15:27:54 +00004651 }
danielk1977e339d652008-06-28 11:23:00 +00004652
drh7ed97b92010-01-20 13:07:21 +00004653 if( pLockingStyle == &posixIoMethods
4654#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4655 || pLockingStyle == &nfsIoMethods
4656#endif
4657 ){
drh7708e972008-11-29 00:56:52 +00004658 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004659 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004660 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004661 /* If an error occured in findInodeInfo(), close the file descriptor
4662 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004663 ** in two scenarios:
4664 **
4665 ** (a) A call to fstat() failed.
4666 ** (b) A malloc failed.
4667 **
4668 ** Scenario (b) may only occur if the process is holding no other
4669 ** file descriptors open on the same file. If there were other file
4670 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004671 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004672 ** handle h - as it is guaranteed that no posix locks will be released
4673 ** by doing so.
4674 **
4675 ** If scenario (a) caused the error then things are not so safe. The
4676 ** implicit assumption here is that if fstat() fails, things are in
4677 ** such bad shape that dropping a lock or two doesn't matter much.
4678 */
drh0e9365c2011-03-02 02:08:13 +00004679 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004680 h = -1;
4681 }
drh7708e972008-11-29 00:56:52 +00004682 unixLeaveMutex();
4683 }
danielk1977e339d652008-06-28 11:23:00 +00004684
drhd2cb50b2009-01-09 21:41:17 +00004685#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004686 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004687 /* AFP locking uses the file path so it needs to be included in
4688 ** the afpLockingContext.
4689 */
4690 afpLockingContext *pCtx;
4691 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4692 if( pCtx==0 ){
4693 rc = SQLITE_NOMEM;
4694 }else{
4695 /* NB: zFilename exists and remains valid until the file is closed
4696 ** according to requirement F11141. So we do not need to make a
4697 ** copy of the filename. */
4698 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004699 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004700 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004701 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004702 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004703 if( rc!=SQLITE_OK ){
4704 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004705 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004706 h = -1;
4707 }
drh7708e972008-11-29 00:56:52 +00004708 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004709 }
drh7708e972008-11-29 00:56:52 +00004710 }
4711#endif
danielk1977e339d652008-06-28 11:23:00 +00004712
drh7708e972008-11-29 00:56:52 +00004713 else if( pLockingStyle == &dotlockIoMethods ){
4714 /* Dotfile locking uses the file path so it needs to be included in
4715 ** the dotlockLockingContext
4716 */
4717 char *zLockFile;
4718 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004719 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004720 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004721 zLockFile = (char *)sqlite3_malloc(nFilename);
4722 if( zLockFile==0 ){
4723 rc = SQLITE_NOMEM;
4724 }else{
4725 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004726 }
drh7708e972008-11-29 00:56:52 +00004727 pNew->lockingContext = zLockFile;
4728 }
danielk1977e339d652008-06-28 11:23:00 +00004729
drh6c7d5c52008-11-21 20:32:33 +00004730#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004731 else if( pLockingStyle == &semIoMethods ){
4732 /* Named semaphore locking uses the file path so it needs to be
4733 ** included in the semLockingContext
4734 */
4735 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004736 rc = findInodeInfo(pNew, &pNew->pInode);
4737 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4738 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004739 int n;
drh2238dcc2009-08-27 17:56:20 +00004740 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004741 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004742 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004743 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004744 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4745 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004746 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004747 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004748 }
chw97185482008-11-17 08:05:31 +00004749 }
drh7708e972008-11-29 00:56:52 +00004750 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004751 }
drh7708e972008-11-29 00:56:52 +00004752#endif
aswift5b1a2562008-08-22 00:22:35 +00004753
4754 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004755#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004756 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004757 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004758 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004759 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004760 isDelete = 0;
4761 }
4762 pNew->isDelete = isDelete;
4763#endif
danielk1977e339d652008-06-28 11:23:00 +00004764 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004765 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004766 }else{
drh7708e972008-11-29 00:56:52 +00004767 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004768 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004769 }
danielk1977e339d652008-06-28 11:23:00 +00004770 return rc;
drh054889e2005-11-30 03:20:31 +00004771}
drh9c06c952005-11-26 00:25:00 +00004772
danielk1977ad94b582007-08-20 06:44:22 +00004773/*
drh8b3cf822010-06-01 21:02:51 +00004774** Return the name of a directory in which to put temporary files.
4775** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004776*/
drh7234c6d2010-06-19 15:10:09 +00004777static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004778 static const char *azDirs[] = {
4779 0,
aswiftaebf4132008-11-21 00:10:35 +00004780 0,
danielk197717b90b52008-06-06 11:11:25 +00004781 "/var/tmp",
4782 "/usr/tmp",
4783 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004784 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004785 };
drh8b3cf822010-06-01 21:02:51 +00004786 unsigned int i;
4787 struct stat buf;
4788 const char *zDir = 0;
4789
4790 azDirs[0] = sqlite3_temp_directory;
4791 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004792 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004793 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004794 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004795 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004796 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004797 break;
4798 }
4799 return zDir;
4800}
4801
4802/*
4803** Create a temporary file name in zBuf. zBuf must be allocated
4804** by the calling process and must be big enough to hold at least
4805** pVfs->mxPathname bytes.
4806*/
4807static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004808 static const unsigned char zChars[] =
4809 "abcdefghijklmnopqrstuvwxyz"
4810 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4811 "0123456789";
drh41022642008-11-21 00:24:42 +00004812 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004813 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004814
4815 /* It's odd to simulate an io-error here, but really this is just
4816 ** using the io-error infrastructure to test that SQLite handles this
4817 ** function failing.
4818 */
4819 SimulateIOError( return SQLITE_IOERR );
4820
drh7234c6d2010-06-19 15:10:09 +00004821 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004822 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004823
4824 /* Check that the output buffer is large enough for the temporary file
4825 ** name. If it is not, return SQLITE_ERROR.
4826 */
danielk197700e13612008-11-17 19:18:54 +00004827 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004828 return SQLITE_ERROR;
4829 }
4830
4831 do{
4832 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004833 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004834 sqlite3_randomness(15, &zBuf[j]);
4835 for(i=0; i<15; i++, j++){
4836 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4837 }
4838 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004839 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004840 return SQLITE_OK;
4841}
4842
drhd2cb50b2009-01-09 21:41:17 +00004843#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004844/*
4845** Routine to transform a unixFile into a proxy-locking unixFile.
4846** Implementation in the proxy-lock division, but used by unixOpen()
4847** if SQLITE_PREFER_PROXY_LOCKING is defined.
4848*/
4849static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004850#endif
drhc66d5b62008-12-03 22:48:32 +00004851
dan08da86a2009-08-21 17:18:03 +00004852/*
4853** Search for an unused file descriptor that was opened on the database
4854** file (not a journal or master-journal file) identified by pathname
4855** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4856** argument to this function.
4857**
4858** Such a file descriptor may exist if a database connection was closed
4859** but the associated file descriptor could not be closed because some
4860** other file descriptor open on the same file is holding a file-lock.
4861** Refer to comments in the unixClose() function and the lengthy comment
4862** describing "Posix Advisory Locking" at the start of this file for
4863** further details. Also, ticket #4018.
4864**
4865** If a suitable file descriptor is found, then it is returned. If no
4866** such file descriptor is located, -1 is returned.
4867*/
dane946c392009-08-22 11:39:46 +00004868static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4869 UnixUnusedFd *pUnused = 0;
4870
4871 /* Do not search for an unused file descriptor on vxworks. Not because
4872 ** vxworks would not benefit from the change (it might, we're not sure),
4873 ** but because no way to test it is currently available. It is better
4874 ** not to risk breaking vxworks support for the sake of such an obscure
4875 ** feature. */
4876#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004877 struct stat sStat; /* Results of stat() call */
4878
4879 /* A stat() call may fail for various reasons. If this happens, it is
4880 ** almost certain that an open() call on the same path will also fail.
4881 ** For this reason, if an error occurs in the stat() call here, it is
4882 ** ignored and -1 is returned. The caller will try to open a new file
4883 ** descriptor on the same path, fail, and return an error to SQLite.
4884 **
4885 ** Even if a subsequent open() call does succeed, the consequences of
4886 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004887 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004888 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004889
4890 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004891 pInode = inodeList;
4892 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4893 || pInode->fileId.ino!=sStat.st_ino) ){
4894 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004895 }
drh8af6c222010-05-14 12:43:01 +00004896 if( pInode ){
dane946c392009-08-22 11:39:46 +00004897 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004898 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004899 pUnused = *pp;
4900 if( pUnused ){
4901 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004902 }
4903 }
4904 unixLeaveMutex();
4905 }
dane946c392009-08-22 11:39:46 +00004906#endif /* if !OS_VXWORKS */
4907 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004908}
danielk197717b90b52008-06-06 11:11:25 +00004909
4910/*
danddb0ac42010-07-14 14:48:58 +00004911** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004912** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004913** and a value suitable for passing as the third argument to open(2) is
4914** written to *pMode. If an IO error occurs, an SQLite error code is
4915** returned and the value of *pMode is not modified.
4916**
4917** If the file being opened is a temporary file, it is always created with
4918** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004919** is a database or master journal file, it is created with the permissions
4920** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004921**
drh8ab58662010-07-15 18:38:39 +00004922** Finally, if the file being opened is a WAL or regular journal file, then
4923** this function queries the file-system for the permissions on the
4924** corresponding database file and sets *pMode to this value. Whenever
4925** possible, WAL and journal files are created using the same permissions
4926** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004927**
4928** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4929** original filename is unavailable. But 8_3_NAMES is only used for
4930** FAT filesystems and permissions do not matter there, so just use
4931** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004932*/
4933static int findCreateFileMode(
4934 const char *zPath, /* Path of file (possibly) being created */
4935 int flags, /* Flags passed as 4th argument to xOpen() */
4936 mode_t *pMode /* OUT: Permissions to open file with */
4937){
4938 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004939 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004940 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004941 char zDb[MAX_PATHNAME+1]; /* Database file path */
4942 int nDb; /* Number of valid bytes in zDb */
4943 struct stat sStat; /* Output of stat() on database file */
4944
dana0c989d2010-11-05 18:07:37 +00004945 /* zPath is a path to a WAL or journal file. The following block derives
4946 ** the path to the associated database file from zPath. This block handles
4947 ** the following naming conventions:
4948 **
4949 ** "<path to db>-journal"
4950 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004951 ** "<path to db>-journalNN"
4952 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004953 **
drhd337c5b2011-10-20 18:23:35 +00004954 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004955 ** used by the test_multiplex.c module.
4956 */
4957 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004958#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004959 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004960 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004961#else
4962 while( zPath[nDb]!='-' ){
4963 assert( nDb>0 );
4964 assert( zPath[nDb]!='\n' );
4965 nDb--;
4966 }
4967#endif
danddb0ac42010-07-14 14:48:58 +00004968 memcpy(zDb, zPath, nDb);
4969 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004970
drh58384f12011-07-28 00:14:45 +00004971 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004972 *pMode = sStat.st_mode & 0777;
4973 }else{
4974 rc = SQLITE_IOERR_FSTAT;
4975 }
4976 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4977 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004978 }
4979 return rc;
4980}
4981
4982/*
danielk1977ad94b582007-08-20 06:44:22 +00004983** Open the file zPath.
4984**
danielk1977b4b47412007-08-17 15:53:36 +00004985** Previously, the SQLite OS layer used three functions in place of this
4986** one:
4987**
4988** sqlite3OsOpenReadWrite();
4989** sqlite3OsOpenReadOnly();
4990** sqlite3OsOpenExclusive();
4991**
4992** These calls correspond to the following combinations of flags:
4993**
4994** ReadWrite() -> (READWRITE | CREATE)
4995** ReadOnly() -> (READONLY)
4996** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4997**
4998** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4999** true, the file was configured to be automatically deleted when the
5000** file handle closed. To achieve the same effect using this new
5001** interface, add the DELETEONCLOSE flag to those specified above for
5002** OpenExclusive().
5003*/
5004static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005005 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5006 const char *zPath, /* Pathname of file to be opened */
5007 sqlite3_file *pFile, /* The file descriptor to be filled in */
5008 int flags, /* Input flags to control the opening */
5009 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005010){
dan08da86a2009-08-21 17:18:03 +00005011 unixFile *p = (unixFile *)pFile;
5012 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005013 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005014 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005015 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005016 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00005017
5018 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5019 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5020 int isCreate = (flags & SQLITE_OPEN_CREATE);
5021 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5022 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005023#if SQLITE_ENABLE_LOCKING_STYLE
5024 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5025#endif
drh3d4435b2011-08-26 20:55:50 +00005026#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5027 struct statfs fsInfo;
5028#endif
danielk1977b4b47412007-08-17 15:53:36 +00005029
danielk1977fee2d252007-08-18 10:59:19 +00005030 /* If creating a master or main-file journal, this function will open
5031 ** a file-descriptor on the directory too. The first time unixSync()
5032 ** is called the directory file descriptor will be fsync()ed and close()d.
5033 */
drh0059eae2011-08-08 23:48:40 +00005034 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005035 eType==SQLITE_OPEN_MASTER_JOURNAL
5036 || eType==SQLITE_OPEN_MAIN_JOURNAL
5037 || eType==SQLITE_OPEN_WAL
5038 ));
danielk1977fee2d252007-08-18 10:59:19 +00005039
danielk197717b90b52008-06-06 11:11:25 +00005040 /* If argument zPath is a NULL pointer, this function is required to open
5041 ** a temporary file. Use this buffer to store the file name in.
5042 */
5043 char zTmpname[MAX_PATHNAME+1];
5044 const char *zName = zPath;
5045
danielk1977fee2d252007-08-18 10:59:19 +00005046 /* Check the following statements are true:
5047 **
5048 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5049 ** (b) if CREATE is set, then READWRITE must also be set, and
5050 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005051 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005052 */
danielk1977b4b47412007-08-17 15:53:36 +00005053 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005054 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005055 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005056 assert(isDelete==0 || isCreate);
5057
danddb0ac42010-07-14 14:48:58 +00005058 /* The main DB, main journal, WAL file and master journal are never
5059 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005060 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5061 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5062 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005063 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005064
danielk1977fee2d252007-08-18 10:59:19 +00005065 /* Assert that the upper layer has set one of the "file-type" flags. */
5066 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5067 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5068 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005069 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005070 );
5071
dan08da86a2009-08-21 17:18:03 +00005072 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005073
dan08da86a2009-08-21 17:18:03 +00005074 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005075 UnixUnusedFd *pUnused;
5076 pUnused = findReusableFd(zName, flags);
5077 if( pUnused ){
5078 fd = pUnused->fd;
5079 }else{
dan6aa657f2009-08-24 18:57:58 +00005080 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005081 if( !pUnused ){
5082 return SQLITE_NOMEM;
5083 }
5084 }
5085 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005086 }else if( !zName ){
5087 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005088 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005089 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005090 if( rc!=SQLITE_OK ){
5091 return rc;
5092 }
5093 zName = zTmpname;
5094 }
5095
dan08da86a2009-08-21 17:18:03 +00005096 /* Determine the value of the flags parameter passed to POSIX function
5097 ** open(). These must be calculated even if open() is not called, as
5098 ** they may be stored as part of the file handle and used by the
5099 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005100 if( isReadonly ) openFlags |= O_RDONLY;
5101 if( isReadWrite ) openFlags |= O_RDWR;
5102 if( isCreate ) openFlags |= O_CREAT;
5103 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5104 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005105
danielk1977b4b47412007-08-17 15:53:36 +00005106 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005107 mode_t openMode; /* Permissions to create file with */
5108 rc = findCreateFileMode(zName, flags, &openMode);
5109 if( rc!=SQLITE_OK ){
5110 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005111 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005112 return rc;
5113 }
drhad4f1e52011-03-04 15:43:57 +00005114 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005115 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005116 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5117 /* Failed to open the file for read/write access. Try read-only. */
5118 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005119 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005120 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005121 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005122 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005123 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005124 }
5125 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005126 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005127 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005128 }
danielk1977b4b47412007-08-17 15:53:36 +00005129 }
dan08da86a2009-08-21 17:18:03 +00005130 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005131 if( pOutFlags ){
5132 *pOutFlags = flags;
5133 }
5134
dane946c392009-08-22 11:39:46 +00005135 if( p->pUnused ){
5136 p->pUnused->fd = fd;
5137 p->pUnused->flags = flags;
5138 }
5139
danielk1977b4b47412007-08-17 15:53:36 +00005140 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005141#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005142 zPath = zName;
5143#else
drh036ac7f2011-08-08 23:18:05 +00005144 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005145#endif
danielk1977b4b47412007-08-17 15:53:36 +00005146 }
drh41022642008-11-21 00:24:42 +00005147#if SQLITE_ENABLE_LOCKING_STYLE
5148 else{
dan08da86a2009-08-21 17:18:03 +00005149 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005150 }
5151#endif
5152
danielk1977e339d652008-06-28 11:23:00 +00005153#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005154 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005155#endif
5156
drhda0e7682008-07-30 15:27:54 +00005157 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005158
drh7ed97b92010-01-20 13:07:21 +00005159
5160#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005161 if( fstatfs(fd, &fsInfo) == -1 ){
5162 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005163 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005164 return SQLITE_IOERR_ACCESS;
5165 }
5166 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5167 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5168 }
5169#endif
5170
5171#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005172#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005173 isAutoProxy = 1;
5174#endif
5175 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005176 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5177 int useProxy = 0;
5178
dan08da86a2009-08-21 17:18:03 +00005179 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5180 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005181 if( envforce!=NULL ){
5182 useProxy = atoi(envforce)>0;
5183 }else{
aswiftaebf4132008-11-21 00:10:35 +00005184 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005185 /* In theory, the close(fd) call is sub-optimal. If the file opened
5186 ** with fd is a database file, and there are other connections open
5187 ** on that file that are currently holding advisory locks on it,
5188 ** then the call to close() will cancel those locks. In practice,
5189 ** we're assuming that statfs() doesn't fail very often. At least
5190 ** not while other file descriptors opened by the same process on
5191 ** the same file are working. */
5192 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005193 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005194 rc = SQLITE_IOERR_ACCESS;
5195 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005196 }
5197 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5198 }
5199 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005200 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005201 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005202 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005203 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005204 if( rc!=SQLITE_OK ){
5205 /* Use unixClose to clean up the resources added in fillInUnixFile
5206 ** and clear all the structure's references. Specifically,
5207 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5208 */
5209 unixClose(pFile);
5210 return rc;
5211 }
aswiftaebf4132008-11-21 00:10:35 +00005212 }
dane946c392009-08-22 11:39:46 +00005213 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005214 }
5215 }
5216#endif
5217
drh0059eae2011-08-08 23:48:40 +00005218 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005219 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005220open_finished:
5221 if( rc!=SQLITE_OK ){
5222 sqlite3_free(p->pUnused);
5223 }
5224 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005225}
5226
dane946c392009-08-22 11:39:46 +00005227
danielk1977b4b47412007-08-17 15:53:36 +00005228/*
danielk1977fee2d252007-08-18 10:59:19 +00005229** Delete the file at zPath. If the dirSync argument is true, fsync()
5230** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005231*/
drh6b9d6dd2008-12-03 19:34:47 +00005232static int unixDelete(
5233 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5234 const char *zPath, /* Name of file to be deleted */
5235 int dirSync /* If true, fsync() directory after deleting file */
5236){
danielk1977fee2d252007-08-18 10:59:19 +00005237 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005238 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005239 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005240 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005241 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005242 }
danielk1977d39fa702008-10-16 13:27:40 +00005243#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005244 if( dirSync ){
5245 int fd;
drh90315a22011-08-10 01:52:12 +00005246 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005247 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005248#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005249 if( fsync(fd)==-1 )
5250#else
5251 if( fsync(fd) )
5252#endif
5253 {
dane18d4952011-02-21 11:46:24 +00005254 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005255 }
drh0e9365c2011-03-02 02:08:13 +00005256 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005257 }else if( rc==SQLITE_CANTOPEN ){
5258 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005259 }
5260 }
danielk1977d138dd82008-10-15 16:02:48 +00005261#endif
danielk1977fee2d252007-08-18 10:59:19 +00005262 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005263}
5264
danielk197790949c22007-08-17 16:50:38 +00005265/*
5266** Test the existance of or access permissions of file zPath. The
5267** test performed depends on the value of flags:
5268**
5269** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5270** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5271** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5272**
5273** Otherwise return 0.
5274*/
danielk1977861f7452008-06-05 11:39:11 +00005275static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005276 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5277 const char *zPath, /* Path of the file to examine */
5278 int flags, /* What do we want to learn about the zPath file? */
5279 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005280){
rse25c0d1a2007-09-20 08:38:14 +00005281 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005282 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005283 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005284 switch( flags ){
5285 case SQLITE_ACCESS_EXISTS:
5286 amode = F_OK;
5287 break;
5288 case SQLITE_ACCESS_READWRITE:
5289 amode = W_OK|R_OK;
5290 break;
drh50d3f902007-08-27 21:10:36 +00005291 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005292 amode = R_OK;
5293 break;
5294
5295 default:
5296 assert(!"Invalid flags argument");
5297 }
drh99ab3b12011-03-02 15:09:07 +00005298 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005299 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5300 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005301 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005302 *pResOut = 0;
5303 }
5304 }
danielk1977861f7452008-06-05 11:39:11 +00005305 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005306}
5307
danielk1977b4b47412007-08-17 15:53:36 +00005308
5309/*
5310** Turn a relative pathname into a full pathname. The relative path
5311** is stored as a nul-terminated string in the buffer pointed to by
5312** zPath.
5313**
5314** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5315** (in this case, MAX_PATHNAME bytes). The full-path is written to
5316** this buffer before returning.
5317*/
danielk1977adfb9b02007-09-17 07:02:56 +00005318static int unixFullPathname(
5319 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5320 const char *zPath, /* Possibly relative input path */
5321 int nOut, /* Size of output buffer in bytes */
5322 char *zOut /* Output buffer */
5323){
danielk1977843e65f2007-09-01 16:16:15 +00005324
5325 /* It's odd to simulate an io-error here, but really this is just
5326 ** using the io-error infrastructure to test that SQLite handles this
5327 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005328 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005329 */
5330 SimulateIOError( return SQLITE_ERROR );
5331
drh153c62c2007-08-24 03:51:33 +00005332 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005333 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005334
drh3c7f2dc2007-12-06 13:26:20 +00005335 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005336 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005337 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005338 }else{
5339 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005340 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005341 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005342 }
drhea678832008-12-10 19:26:22 +00005343 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005344 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005345 }
5346 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005347}
5348
drh0ccebe72005-06-07 22:22:50 +00005349
drh761df872006-12-21 01:29:22 +00005350#ifndef SQLITE_OMIT_LOAD_EXTENSION
5351/*
5352** Interfaces for opening a shared library, finding entry points
5353** within the shared library, and closing the shared library.
5354*/
5355#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005356static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5357 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005358 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5359}
danielk197795c8a542007-09-01 06:51:27 +00005360
5361/*
5362** SQLite calls this function immediately after a call to unixDlSym() or
5363** unixDlOpen() fails (returns a null pointer). If a more detailed error
5364** message is available, it is written to zBufOut. If no error message
5365** is available, zBufOut is left unmodified and SQLite uses a default
5366** error message.
5367*/
danielk1977397d65f2008-11-19 11:35:39 +00005368static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005369 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005370 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005371 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005372 zErr = dlerror();
5373 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005374 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005375 }
drh6c7d5c52008-11-21 20:32:33 +00005376 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005377}
drh1875f7a2008-12-08 18:19:17 +00005378static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5379 /*
5380 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5381 ** cast into a pointer to a function. And yet the library dlsym() routine
5382 ** returns a void* which is really a pointer to a function. So how do we
5383 ** use dlsym() with -pedantic-errors?
5384 **
5385 ** Variable x below is defined to be a pointer to a function taking
5386 ** parameters void* and const char* and returning a pointer to a function.
5387 ** We initialize x by assigning it a pointer to the dlsym() function.
5388 ** (That assignment requires a cast.) Then we call the function that
5389 ** x points to.
5390 **
5391 ** This work-around is unlikely to work correctly on any system where
5392 ** you really cannot cast a function pointer into void*. But then, on the
5393 ** other hand, dlsym() will not work on such a system either, so we have
5394 ** not really lost anything.
5395 */
5396 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005397 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005398 x = (void(*(*)(void*,const char*))(void))dlsym;
5399 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005400}
danielk1977397d65f2008-11-19 11:35:39 +00005401static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5402 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005403 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005404}
danielk1977b4b47412007-08-17 15:53:36 +00005405#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5406 #define unixDlOpen 0
5407 #define unixDlError 0
5408 #define unixDlSym 0
5409 #define unixDlClose 0
5410#endif
5411
5412/*
danielk197790949c22007-08-17 16:50:38 +00005413** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005414*/
danielk1977397d65f2008-11-19 11:35:39 +00005415static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5416 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005417 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005418
drhbbd42a62004-05-22 17:41:58 +00005419 /* We have to initialize zBuf to prevent valgrind from reporting
5420 ** errors. The reports issued by valgrind are incorrect - we would
5421 ** prefer that the randomness be increased by making use of the
5422 ** uninitialized space in zBuf - but valgrind errors tend to worry
5423 ** some users. Rather than argue, it seems easier just to initialize
5424 ** the whole array and silence valgrind, even if that means less randomness
5425 ** in the random seed.
5426 **
5427 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005428 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005429 ** tests repeatable.
5430 */
danielk1977b4b47412007-08-17 15:53:36 +00005431 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005432#if !defined(SQLITE_TEST)
5433 {
drh842b8642005-01-21 17:53:17 +00005434 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005435 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005436 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005437 time_t t;
5438 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005439 memcpy(zBuf, &t, sizeof(t));
5440 pid = getpid();
5441 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005442 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005443 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005444 }else{
drhe562be52011-03-02 18:01:10 +00005445 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005446 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005447 }
drhbbd42a62004-05-22 17:41:58 +00005448 }
5449#endif
drh72cbd072008-10-14 17:58:38 +00005450 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005451}
5452
danielk1977b4b47412007-08-17 15:53:36 +00005453
drhbbd42a62004-05-22 17:41:58 +00005454/*
5455** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005456** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005457** The return value is the number of microseconds of sleep actually
5458** requested from the underlying operating system, a number which
5459** might be greater than or equal to the argument, but not less
5460** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005461*/
danielk1977397d65f2008-11-19 11:35:39 +00005462static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005463#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005464 struct timespec sp;
5465
5466 sp.tv_sec = microseconds / 1000000;
5467 sp.tv_nsec = (microseconds % 1000000) * 1000;
5468 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005469 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005470 return microseconds;
5471#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005472 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005473 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005474 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005475#else
danielk1977b4b47412007-08-17 15:53:36 +00005476 int seconds = (microseconds+999999)/1000000;
5477 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005478 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005479 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005480#endif
drh88f474a2006-01-02 20:00:12 +00005481}
5482
5483/*
drh6b9d6dd2008-12-03 19:34:47 +00005484** The following variable, if set to a non-zero value, is interpreted as
5485** the number of seconds since 1970 and is used to set the result of
5486** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005487*/
5488#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005489int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005490#endif
5491
5492/*
drhb7e8ea22010-05-03 14:32:30 +00005493** Find the current time (in Universal Coordinated Time). Write into *piNow
5494** the current time and date as a Julian Day number times 86_400_000. In
5495** other words, write into *piNow the number of milliseconds since the Julian
5496** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5497** proleptic Gregorian calendar.
5498**
drh31702252011-10-12 23:13:43 +00005499** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5500** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005501*/
5502static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5503 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005504 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005505#if defined(NO_GETTOD)
5506 time_t t;
5507 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005508 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005509#elif OS_VXWORKS
5510 struct timespec sNow;
5511 clock_gettime(CLOCK_REALTIME, &sNow);
5512 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5513#else
5514 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005515 if( gettimeofday(&sNow, 0)==0 ){
5516 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5517 }else{
5518 rc = SQLITE_ERROR;
5519 }
drhb7e8ea22010-05-03 14:32:30 +00005520#endif
5521
5522#ifdef SQLITE_TEST
5523 if( sqlite3_current_time ){
5524 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5525 }
5526#endif
5527 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005528 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005529}
5530
5531/*
drhbbd42a62004-05-22 17:41:58 +00005532** Find the current time (in Universal Coordinated Time). Write the
5533** current time and date as a Julian Day number into *prNow and
5534** return 0. Return 1 if the time and date cannot be found.
5535*/
danielk1977397d65f2008-11-19 11:35:39 +00005536static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005537 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005538 int rc;
drhff828942010-06-26 21:34:06 +00005539 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005540 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005541 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005542 return rc;
drhbbd42a62004-05-22 17:41:58 +00005543}
danielk1977b4b47412007-08-17 15:53:36 +00005544
drh6b9d6dd2008-12-03 19:34:47 +00005545/*
5546** We added the xGetLastError() method with the intention of providing
5547** better low-level error messages when operating-system problems come up
5548** during SQLite operation. But so far, none of that has been implemented
5549** in the core. So this routine is never called. For now, it is merely
5550** a place-holder.
5551*/
danielk1977397d65f2008-11-19 11:35:39 +00005552static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5553 UNUSED_PARAMETER(NotUsed);
5554 UNUSED_PARAMETER(NotUsed2);
5555 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005556 return 0;
5557}
5558
drhf2424c52010-04-26 00:04:55 +00005559
5560/*
drh734c9862008-11-28 15:37:20 +00005561************************ End of sqlite3_vfs methods ***************************
5562******************************************************************************/
5563
drh715ff302008-12-03 22:32:44 +00005564/******************************************************************************
5565************************** Begin Proxy Locking ********************************
5566**
5567** Proxy locking is a "uber-locking-method" in this sense: It uses the
5568** other locking methods on secondary lock files. Proxy locking is a
5569** meta-layer over top of the primitive locking implemented above. For
5570** this reason, the division that implements of proxy locking is deferred
5571** until late in the file (here) after all of the other I/O methods have
5572** been defined - so that the primitive locking methods are available
5573** as services to help with the implementation of proxy locking.
5574**
5575****
5576**
5577** The default locking schemes in SQLite use byte-range locks on the
5578** database file to coordinate safe, concurrent access by multiple readers
5579** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5580** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5581** as POSIX read & write locks over fixed set of locations (via fsctl),
5582** on AFP and SMB only exclusive byte-range locks are available via fsctl
5583** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5584** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5585** address in the shared range is taken for a SHARED lock, the entire
5586** shared range is taken for an EXCLUSIVE lock):
5587**
5588** PENDING_BYTE 0x40000000
5589** RESERVED_BYTE 0x40000001
5590** SHARED_RANGE 0x40000002 -> 0x40000200
5591**
5592** This works well on the local file system, but shows a nearly 100x
5593** slowdown in read performance on AFP because the AFP client disables
5594** the read cache when byte-range locks are present. Enabling the read
5595** cache exposes a cache coherency problem that is present on all OS X
5596** supported network file systems. NFS and AFP both observe the
5597** close-to-open semantics for ensuring cache coherency
5598** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5599** address the requirements for concurrent database access by multiple
5600** readers and writers
5601** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5602**
5603** To address the performance and cache coherency issues, proxy file locking
5604** changes the way database access is controlled by limiting access to a
5605** single host at a time and moving file locks off of the database file
5606** and onto a proxy file on the local file system.
5607**
5608**
5609** Using proxy locks
5610** -----------------
5611**
5612** C APIs
5613**
5614** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5615** <proxy_path> | ":auto:");
5616** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5617**
5618**
5619** SQL pragmas
5620**
5621** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5622** PRAGMA [database.]lock_proxy_file
5623**
5624** Specifying ":auto:" means that if there is a conch file with a matching
5625** host ID in it, the proxy path in the conch file will be used, otherwise
5626** a proxy path based on the user's temp dir
5627** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5628** actual proxy file name is generated from the name and path of the
5629** database file. For example:
5630**
5631** For database path "/Users/me/foo.db"
5632** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5633**
5634** Once a lock proxy is configured for a database connection, it can not
5635** be removed, however it may be switched to a different proxy path via
5636** the above APIs (assuming the conch file is not being held by another
5637** connection or process).
5638**
5639**
5640** How proxy locking works
5641** -----------------------
5642**
5643** Proxy file locking relies primarily on two new supporting files:
5644**
5645** * conch file to limit access to the database file to a single host
5646** at a time
5647**
5648** * proxy file to act as a proxy for the advisory locks normally
5649** taken on the database
5650**
5651** The conch file - to use a proxy file, sqlite must first "hold the conch"
5652** by taking an sqlite-style shared lock on the conch file, reading the
5653** contents and comparing the host's unique host ID (see below) and lock
5654** proxy path against the values stored in the conch. The conch file is
5655** stored in the same directory as the database file and the file name
5656** is patterned after the database file name as ".<databasename>-conch".
5657** If the conch file does not exist, or it's contents do not match the
5658** host ID and/or proxy path, then the lock is escalated to an exclusive
5659** lock and the conch file contents is updated with the host ID and proxy
5660** path and the lock is downgraded to a shared lock again. If the conch
5661** is held by another process (with a shared lock), the exclusive lock
5662** will fail and SQLITE_BUSY is returned.
5663**
5664** The proxy file - a single-byte file used for all advisory file locks
5665** normally taken on the database file. This allows for safe sharing
5666** of the database file for multiple readers and writers on the same
5667** host (the conch ensures that they all use the same local lock file).
5668**
drh715ff302008-12-03 22:32:44 +00005669** Requesting the lock proxy does not immediately take the conch, it is
5670** only taken when the first request to lock database file is made.
5671** This matches the semantics of the traditional locking behavior, where
5672** opening a connection to a database file does not take a lock on it.
5673** The shared lock and an open file descriptor are maintained until
5674** the connection to the database is closed.
5675**
5676** The proxy file and the lock file are never deleted so they only need
5677** to be created the first time they are used.
5678**
5679** Configuration options
5680** ---------------------
5681**
5682** SQLITE_PREFER_PROXY_LOCKING
5683**
5684** Database files accessed on non-local file systems are
5685** automatically configured for proxy locking, lock files are
5686** named automatically using the same logic as
5687** PRAGMA lock_proxy_file=":auto:"
5688**
5689** SQLITE_PROXY_DEBUG
5690**
5691** Enables the logging of error messages during host id file
5692** retrieval and creation
5693**
drh715ff302008-12-03 22:32:44 +00005694** LOCKPROXYDIR
5695**
5696** Overrides the default directory used for lock proxy files that
5697** are named automatically via the ":auto:" setting
5698**
5699** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5700**
5701** Permissions to use when creating a directory for storing the
5702** lock proxy files, only used when LOCKPROXYDIR is not set.
5703**
5704**
5705** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5706** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5707** force proxy locking to be used for every database file opened, and 0
5708** will force automatic proxy locking to be disabled for all database
5709** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5710** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5711*/
5712
5713/*
5714** Proxy locking is only available on MacOSX
5715*/
drhd2cb50b2009-01-09 21:41:17 +00005716#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005717
drh715ff302008-12-03 22:32:44 +00005718/*
5719** The proxyLockingContext has the path and file structures for the remote
5720** and local proxy files in it
5721*/
5722typedef struct proxyLockingContext proxyLockingContext;
5723struct proxyLockingContext {
5724 unixFile *conchFile; /* Open conch file */
5725 char *conchFilePath; /* Name of the conch file */
5726 unixFile *lockProxy; /* Open proxy lock file */
5727 char *lockProxyPath; /* Name of the proxy lock file */
5728 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005729 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005730 void *oldLockingContext; /* Original lockingcontext to restore on close */
5731 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5732};
5733
drh7ed97b92010-01-20 13:07:21 +00005734/*
5735** The proxy lock file path for the database at dbPath is written into lPath,
5736** which must point to valid, writable memory large enough for a maxLen length
5737** file path.
drh715ff302008-12-03 22:32:44 +00005738*/
drh715ff302008-12-03 22:32:44 +00005739static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5740 int len;
5741 int dbLen;
5742 int i;
5743
5744#ifdef LOCKPROXYDIR
5745 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5746#else
5747# ifdef _CS_DARWIN_USER_TEMP_DIR
5748 {
drh7ed97b92010-01-20 13:07:21 +00005749 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005750 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5751 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005752 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005753 }
drh7ed97b92010-01-20 13:07:21 +00005754 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005755 }
5756# else
5757 len = strlcpy(lPath, "/tmp/", maxLen);
5758# endif
5759#endif
5760
5761 if( lPath[len-1]!='/' ){
5762 len = strlcat(lPath, "/", maxLen);
5763 }
5764
5765 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005766 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005767 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005768 char c = dbPath[i];
5769 lPath[i+len] = (c=='/')?'_':c;
5770 }
5771 lPath[i+len]='\0';
5772 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005773 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005774 return SQLITE_OK;
5775}
5776
drh7ed97b92010-01-20 13:07:21 +00005777/*
5778 ** Creates the lock file and any missing directories in lockPath
5779 */
5780static int proxyCreateLockPath(const char *lockPath){
5781 int i, len;
5782 char buf[MAXPATHLEN];
5783 int start = 0;
5784
5785 assert(lockPath!=NULL);
5786 /* try to create all the intermediate directories */
5787 len = (int)strlen(lockPath);
5788 buf[0] = lockPath[0];
5789 for( i=1; i<len; i++ ){
5790 if( lockPath[i] == '/' && (i - start > 0) ){
5791 /* only mkdir if leaf dir != "." or "/" or ".." */
5792 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5793 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5794 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005795 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005796 int err=errno;
5797 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005798 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005799 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005800 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005801 return err;
5802 }
5803 }
5804 }
5805 start=i+1;
5806 }
5807 buf[i] = lockPath[i];
5808 }
drh308c2a52010-05-14 11:30:18 +00005809 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005810 return 0;
5811}
5812
drh715ff302008-12-03 22:32:44 +00005813/*
5814** Create a new VFS file descriptor (stored in memory obtained from
5815** sqlite3_malloc) and open the file named "path" in the file descriptor.
5816**
5817** The caller is responsible not only for closing the file descriptor
5818** but also for freeing the memory associated with the file descriptor.
5819*/
drh7ed97b92010-01-20 13:07:21 +00005820static int proxyCreateUnixFile(
5821 const char *path, /* path for the new unixFile */
5822 unixFile **ppFile, /* unixFile created and returned by ref */
5823 int islockfile /* if non zero missing dirs will be created */
5824) {
5825 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005826 unixFile *pNew;
5827 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005828 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005829 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005830 int terrno = 0;
5831 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005832
drh7ed97b92010-01-20 13:07:21 +00005833 /* 1. first try to open/create the file
5834 ** 2. if that fails, and this is a lock file (not-conch), try creating
5835 ** the parent directories and then try again.
5836 ** 3. if that fails, try to open the file read-only
5837 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5838 */
5839 pUnused = findReusableFd(path, openFlags);
5840 if( pUnused ){
5841 fd = pUnused->fd;
5842 }else{
5843 pUnused = sqlite3_malloc(sizeof(*pUnused));
5844 if( !pUnused ){
5845 return SQLITE_NOMEM;
5846 }
5847 }
5848 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005849 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005850 terrno = errno;
5851 if( fd<0 && errno==ENOENT && islockfile ){
5852 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005853 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005854 }
5855 }
5856 }
5857 if( fd<0 ){
5858 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005859 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005860 terrno = errno;
5861 }
5862 if( fd<0 ){
5863 if( islockfile ){
5864 return SQLITE_BUSY;
5865 }
5866 switch (terrno) {
5867 case EACCES:
5868 return SQLITE_PERM;
5869 case EIO:
5870 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5871 default:
drh9978c972010-02-23 17:36:32 +00005872 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005873 }
5874 }
5875
5876 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5877 if( pNew==NULL ){
5878 rc = SQLITE_NOMEM;
5879 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005880 }
5881 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005882 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005883 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005884 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005885 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005886 pUnused->fd = fd;
5887 pUnused->flags = openFlags;
5888 pNew->pUnused = pUnused;
5889
drh0059eae2011-08-08 23:48:40 +00005890 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005891 if( rc==SQLITE_OK ){
5892 *ppFile = pNew;
5893 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005894 }
drh7ed97b92010-01-20 13:07:21 +00005895end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005896 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005897 sqlite3_free(pNew);
5898 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005899 return rc;
5900}
5901
drh7ed97b92010-01-20 13:07:21 +00005902#ifdef SQLITE_TEST
5903/* simulate multiple hosts by creating unique hostid file paths */
5904int sqlite3_hostid_num = 0;
5905#endif
5906
5907#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5908
drh0ab216a2010-07-02 17:10:40 +00005909/* Not always defined in the headers as it ought to be */
5910extern int gethostuuid(uuid_t id, const struct timespec *wait);
5911
drh7ed97b92010-01-20 13:07:21 +00005912/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5913** bytes of writable memory.
5914*/
5915static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005916 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5917 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005918#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5919 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005920 {
5921 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5922 if( gethostuuid(pHostID, &timeout) ){
5923 int err = errno;
5924 if( pError ){
5925 *pError = err;
5926 }
5927 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005928 }
drh7ed97b92010-01-20 13:07:21 +00005929 }
drh3d4435b2011-08-26 20:55:50 +00005930#else
5931 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005932#endif
drh7ed97b92010-01-20 13:07:21 +00005933#ifdef SQLITE_TEST
5934 /* simulate multiple hosts by creating unique hostid file paths */
5935 if( sqlite3_hostid_num != 0){
5936 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5937 }
5938#endif
5939
5940 return SQLITE_OK;
5941}
5942
5943/* The conch file contains the header, host id and lock file path
5944 */
5945#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5946#define PROXY_HEADERLEN 1 /* conch file header length */
5947#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5948#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5949
5950/*
5951** Takes an open conch file, copies the contents to a new path and then moves
5952** it back. The newly created file's file descriptor is assigned to the
5953** conch file structure and finally the original conch file descriptor is
5954** closed. Returns zero if successful.
5955*/
5956static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5957 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5958 unixFile *conchFile = pCtx->conchFile;
5959 char tPath[MAXPATHLEN];
5960 char buf[PROXY_MAXCONCHLEN];
5961 char *cPath = pCtx->conchFilePath;
5962 size_t readLen = 0;
5963 size_t pathLen = 0;
5964 char errmsg[64] = "";
5965 int fd = -1;
5966 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005967 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005968
5969 /* create a new path by replace the trailing '-conch' with '-break' */
5970 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5971 if( pathLen>MAXPATHLEN || pathLen<6 ||
5972 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005973 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005974 goto end_breaklock;
5975 }
5976 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005977 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005978 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005979 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005980 goto end_breaklock;
5981 }
5982 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005983 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5984 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005985 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005986 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005987 goto end_breaklock;
5988 }
drhe562be52011-03-02 18:01:10 +00005989 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005990 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005991 goto end_breaklock;
5992 }
5993 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005994 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005995 goto end_breaklock;
5996 }
5997 rc = 0;
5998 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005999 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006000 conchFile->h = fd;
6001 conchFile->openFlags = O_RDWR | O_CREAT;
6002
6003end_breaklock:
6004 if( rc ){
6005 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006006 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006007 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006008 }
6009 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6010 }
6011 return rc;
6012}
6013
6014/* Take the requested lock on the conch file and break a stale lock if the
6015** host id matches.
6016*/
6017static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6018 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6019 unixFile *conchFile = pCtx->conchFile;
6020 int rc = SQLITE_OK;
6021 int nTries = 0;
6022 struct timespec conchModTime;
6023
drh3d4435b2011-08-26 20:55:50 +00006024 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006025 do {
6026 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6027 nTries ++;
6028 if( rc==SQLITE_BUSY ){
6029 /* If the lock failed (busy):
6030 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6031 * 2nd try: fail if the mod time changed or host id is different, wait
6032 * 10 sec and try again
6033 * 3rd try: break the lock unless the mod time has changed.
6034 */
6035 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006036 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006037 pFile->lastErrno = errno;
6038 return SQLITE_IOERR_LOCK;
6039 }
6040
6041 if( nTries==1 ){
6042 conchModTime = buf.st_mtimespec;
6043 usleep(500000); /* wait 0.5 sec and try the lock again*/
6044 continue;
6045 }
6046
6047 assert( nTries>1 );
6048 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6049 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6050 return SQLITE_BUSY;
6051 }
6052
6053 if( nTries==2 ){
6054 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006055 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006056 if( len<0 ){
6057 pFile->lastErrno = errno;
6058 return SQLITE_IOERR_LOCK;
6059 }
6060 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6061 /* don't break the lock if the host id doesn't match */
6062 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6063 return SQLITE_BUSY;
6064 }
6065 }else{
6066 /* don't break the lock on short read or a version mismatch */
6067 return SQLITE_BUSY;
6068 }
6069 usleep(10000000); /* wait 10 sec and try the lock again */
6070 continue;
6071 }
6072
6073 assert( nTries==3 );
6074 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6075 rc = SQLITE_OK;
6076 if( lockType==EXCLUSIVE_LOCK ){
6077 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6078 }
6079 if( !rc ){
6080 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6081 }
6082 }
6083 }
6084 } while( rc==SQLITE_BUSY && nTries<3 );
6085
6086 return rc;
6087}
6088
6089/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006090** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6091** lockPath means that the lockPath in the conch file will be used if the
6092** host IDs match, or a new lock path will be generated automatically
6093** and written to the conch file.
6094*/
6095static int proxyTakeConch(unixFile *pFile){
6096 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6097
drh7ed97b92010-01-20 13:07:21 +00006098 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006099 return SQLITE_OK;
6100 }else{
6101 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006102 uuid_t myHostID;
6103 int pError = 0;
6104 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006105 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006106 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006107 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006108 int createConch = 0;
6109 int hostIdMatch = 0;
6110 int readLen = 0;
6111 int tryOldLockPath = 0;
6112 int forceNewLockPath = 0;
6113
drh308c2a52010-05-14 11:30:18 +00006114 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6115 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006116
drh7ed97b92010-01-20 13:07:21 +00006117 rc = proxyGetHostID(myHostID, &pError);
6118 if( (rc&0xff)==SQLITE_IOERR ){
6119 pFile->lastErrno = pError;
6120 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006121 }
drh7ed97b92010-01-20 13:07:21 +00006122 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006123 if( rc!=SQLITE_OK ){
6124 goto end_takeconch;
6125 }
drh7ed97b92010-01-20 13:07:21 +00006126 /* read the existing conch file */
6127 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6128 if( readLen<0 ){
6129 /* I/O error: lastErrno set by seekAndRead */
6130 pFile->lastErrno = conchFile->lastErrno;
6131 rc = SQLITE_IOERR_READ;
6132 goto end_takeconch;
6133 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6134 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6135 /* a short read or version format mismatch means we need to create a new
6136 ** conch file.
6137 */
6138 createConch = 1;
6139 }
6140 /* if the host id matches and the lock path already exists in the conch
6141 ** we'll try to use the path there, if we can't open that path, we'll
6142 ** retry with a new auto-generated path
6143 */
6144 do { /* in case we need to try again for an :auto: named lock file */
6145
6146 if( !createConch && !forceNewLockPath ){
6147 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6148 PROXY_HOSTIDLEN);
6149 /* if the conch has data compare the contents */
6150 if( !pCtx->lockProxyPath ){
6151 /* for auto-named local lock file, just check the host ID and we'll
6152 ** use the local lock file path that's already in there
6153 */
6154 if( hostIdMatch ){
6155 size_t pathLen = (readLen - PROXY_PATHINDEX);
6156
6157 if( pathLen>=MAXPATHLEN ){
6158 pathLen=MAXPATHLEN-1;
6159 }
6160 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6161 lockPath[pathLen] = 0;
6162 tempLockPath = lockPath;
6163 tryOldLockPath = 1;
6164 /* create a copy of the lock path if the conch is taken */
6165 goto end_takeconch;
6166 }
6167 }else if( hostIdMatch
6168 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6169 readLen-PROXY_PATHINDEX)
6170 ){
6171 /* conch host and lock path match */
6172 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006173 }
drh7ed97b92010-01-20 13:07:21 +00006174 }
6175
6176 /* if the conch isn't writable and doesn't match, we can't take it */
6177 if( (conchFile->openFlags&O_RDWR) == 0 ){
6178 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006179 goto end_takeconch;
6180 }
drh7ed97b92010-01-20 13:07:21 +00006181
6182 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006183 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006184 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6185 tempLockPath = lockPath;
6186 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006187 }
drh7ed97b92010-01-20 13:07:21 +00006188
6189 /* update conch with host and path (this will fail if other process
6190 ** has a shared lock already), if the host id matches, use the big
6191 ** stick.
drh715ff302008-12-03 22:32:44 +00006192 */
drh7ed97b92010-01-20 13:07:21 +00006193 futimes(conchFile->h, NULL);
6194 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006195 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006196 /* We are trying for an exclusive lock but another thread in this
6197 ** same process is still holding a shared lock. */
6198 rc = SQLITE_BUSY;
6199 } else {
6200 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006201 }
drh715ff302008-12-03 22:32:44 +00006202 }else{
drh7ed97b92010-01-20 13:07:21 +00006203 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006204 }
drh7ed97b92010-01-20 13:07:21 +00006205 if( rc==SQLITE_OK ){
6206 char writeBuffer[PROXY_MAXCONCHLEN];
6207 int writeSize = 0;
6208
6209 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6210 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6211 if( pCtx->lockProxyPath!=NULL ){
6212 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6213 }else{
6214 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6215 }
6216 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006217 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006218 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6219 fsync(conchFile->h);
6220 /* If we created a new conch file (not just updated the contents of a
6221 ** valid conch file), try to match the permissions of the database
6222 */
6223 if( rc==SQLITE_OK && createConch ){
6224 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006225 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006226 if( err==0 ){
6227 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6228 S_IROTH|S_IWOTH);
6229 /* try to match the database file R/W permissions, ignore failure */
6230#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006231 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006232#else
drhff812312011-02-23 13:33:46 +00006233 do{
drhe562be52011-03-02 18:01:10 +00006234 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006235 }while( rc==(-1) && errno==EINTR );
6236 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006237 int code = errno;
6238 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6239 cmode, code, strerror(code));
6240 } else {
6241 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6242 }
6243 }else{
6244 int code = errno;
6245 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6246 err, code, strerror(code));
6247#endif
6248 }
drh715ff302008-12-03 22:32:44 +00006249 }
6250 }
drh7ed97b92010-01-20 13:07:21 +00006251 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6252
6253 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006254 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006255 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006256 int fd;
drh7ed97b92010-01-20 13:07:21 +00006257 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006258 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006259 }
6260 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006261 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006262 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006263 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006264 if( fd>=0 ){
6265 pFile->h = fd;
6266 }else{
drh9978c972010-02-23 17:36:32 +00006267 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006268 during locking */
6269 }
6270 }
6271 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6272 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6273 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6274 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6275 /* we couldn't create the proxy lock file with the old lock file path
6276 ** so try again via auto-naming
6277 */
6278 forceNewLockPath = 1;
6279 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006280 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006281 }
6282 }
6283 if( rc==SQLITE_OK ){
6284 /* Need to make a copy of path if we extracted the value
6285 ** from the conch file or the path was allocated on the stack
6286 */
6287 if( tempLockPath ){
6288 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6289 if( !pCtx->lockProxyPath ){
6290 rc = SQLITE_NOMEM;
6291 }
6292 }
6293 }
6294 if( rc==SQLITE_OK ){
6295 pCtx->conchHeld = 1;
6296
6297 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6298 afpLockingContext *afpCtx;
6299 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6300 afpCtx->dbPath = pCtx->lockProxyPath;
6301 }
6302 } else {
6303 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6304 }
drh308c2a52010-05-14 11:30:18 +00006305 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6306 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006307 return rc;
drh308c2a52010-05-14 11:30:18 +00006308 } while (1); /* in case we need to retry the :auto: lock file -
6309 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006310 }
6311}
6312
6313/*
6314** If pFile holds a lock on a conch file, then release that lock.
6315*/
6316static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006317 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006318 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6319 unixFile *conchFile; /* Name of the conch file */
6320
6321 pCtx = (proxyLockingContext *)pFile->lockingContext;
6322 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006323 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006324 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006325 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006326 if( pCtx->conchHeld>0 ){
6327 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6328 }
drh715ff302008-12-03 22:32:44 +00006329 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006330 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6331 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006332 return rc;
6333}
6334
6335/*
6336** Given the name of a database file, compute the name of its conch file.
6337** Store the conch filename in memory obtained from sqlite3_malloc().
6338** Make *pConchPath point to the new name. Return SQLITE_OK on success
6339** or SQLITE_NOMEM if unable to obtain memory.
6340**
6341** The caller is responsible for ensuring that the allocated memory
6342** space is eventually freed.
6343**
6344** *pConchPath is set to NULL if a memory allocation error occurs.
6345*/
6346static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6347 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006348 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006349 char *conchPath; /* buffer in which to construct conch name */
6350
6351 /* Allocate space for the conch filename and initialize the name to
6352 ** the name of the original database file. */
6353 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6354 if( conchPath==0 ){
6355 return SQLITE_NOMEM;
6356 }
6357 memcpy(conchPath, dbPath, len+1);
6358
6359 /* now insert a "." before the last / character */
6360 for( i=(len-1); i>=0; i-- ){
6361 if( conchPath[i]=='/' ){
6362 i++;
6363 break;
6364 }
6365 }
6366 conchPath[i]='.';
6367 while ( i<len ){
6368 conchPath[i+1]=dbPath[i];
6369 i++;
6370 }
6371
6372 /* append the "-conch" suffix to the file */
6373 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006374 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006375
6376 return SQLITE_OK;
6377}
6378
6379
6380/* Takes a fully configured proxy locking-style unix file and switches
6381** the local lock file path
6382*/
6383static int switchLockProxyPath(unixFile *pFile, const char *path) {
6384 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6385 char *oldPath = pCtx->lockProxyPath;
6386 int rc = SQLITE_OK;
6387
drh308c2a52010-05-14 11:30:18 +00006388 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006389 return SQLITE_BUSY;
6390 }
6391
6392 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6393 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6394 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6395 return SQLITE_OK;
6396 }else{
6397 unixFile *lockProxy = pCtx->lockProxy;
6398 pCtx->lockProxy=NULL;
6399 pCtx->conchHeld = 0;
6400 if( lockProxy!=NULL ){
6401 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6402 if( rc ) return rc;
6403 sqlite3_free(lockProxy);
6404 }
6405 sqlite3_free(oldPath);
6406 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6407 }
6408
6409 return rc;
6410}
6411
6412/*
6413** pFile is a file that has been opened by a prior xOpen call. dbPath
6414** is a string buffer at least MAXPATHLEN+1 characters in size.
6415**
6416** This routine find the filename associated with pFile and writes it
6417** int dbPath.
6418*/
6419static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006420#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006421 if( pFile->pMethod == &afpIoMethods ){
6422 /* afp style keeps a reference to the db path in the filePath field
6423 ** of the struct */
drhea678832008-12-10 19:26:22 +00006424 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006425 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6426 } else
drh715ff302008-12-03 22:32:44 +00006427#endif
6428 if( pFile->pMethod == &dotlockIoMethods ){
6429 /* dot lock style uses the locking context to store the dot lock
6430 ** file path */
6431 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6432 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6433 }else{
6434 /* all other styles use the locking context to store the db file path */
6435 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006436 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006437 }
6438 return SQLITE_OK;
6439}
6440
6441/*
6442** Takes an already filled in unix file and alters it so all file locking
6443** will be performed on the local proxy lock file. The following fields
6444** are preserved in the locking context so that they can be restored and
6445** the unix structure properly cleaned up at close time:
6446** ->lockingContext
6447** ->pMethod
6448*/
6449static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6450 proxyLockingContext *pCtx;
6451 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6452 char *lockPath=NULL;
6453 int rc = SQLITE_OK;
6454
drh308c2a52010-05-14 11:30:18 +00006455 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006456 return SQLITE_BUSY;
6457 }
6458 proxyGetDbPathForUnixFile(pFile, dbPath);
6459 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6460 lockPath=NULL;
6461 }else{
6462 lockPath=(char *)path;
6463 }
6464
drh308c2a52010-05-14 11:30:18 +00006465 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6466 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006467
6468 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6469 if( pCtx==0 ){
6470 return SQLITE_NOMEM;
6471 }
6472 memset(pCtx, 0, sizeof(*pCtx));
6473
6474 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6475 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006476 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6477 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6478 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6479 ** (c) the file system is read-only, then enable no-locking access.
6480 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6481 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6482 */
6483 struct statfs fsInfo;
6484 struct stat conchInfo;
6485 int goLockless = 0;
6486
drh99ab3b12011-03-02 15:09:07 +00006487 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006488 int err = errno;
6489 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6490 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6491 }
6492 }
6493 if( goLockless ){
6494 pCtx->conchHeld = -1; /* read only FS/ lockless */
6495 rc = SQLITE_OK;
6496 }
6497 }
drh715ff302008-12-03 22:32:44 +00006498 }
6499 if( rc==SQLITE_OK && lockPath ){
6500 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6501 }
6502
6503 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006504 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6505 if( pCtx->dbPath==NULL ){
6506 rc = SQLITE_NOMEM;
6507 }
6508 }
6509 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006510 /* all memory is allocated, proxys are created and assigned,
6511 ** switch the locking context and pMethod then return.
6512 */
drh715ff302008-12-03 22:32:44 +00006513 pCtx->oldLockingContext = pFile->lockingContext;
6514 pFile->lockingContext = pCtx;
6515 pCtx->pOldMethod = pFile->pMethod;
6516 pFile->pMethod = &proxyIoMethods;
6517 }else{
6518 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006519 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006520 sqlite3_free(pCtx->conchFile);
6521 }
drhd56b1212010-08-11 06:14:15 +00006522 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006523 sqlite3_free(pCtx->conchFilePath);
6524 sqlite3_free(pCtx);
6525 }
drh308c2a52010-05-14 11:30:18 +00006526 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6527 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006528 return rc;
6529}
6530
6531
6532/*
6533** This routine handles sqlite3_file_control() calls that are specific
6534** to proxy locking.
6535*/
6536static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6537 switch( op ){
6538 case SQLITE_GET_LOCKPROXYFILE: {
6539 unixFile *pFile = (unixFile*)id;
6540 if( pFile->pMethod == &proxyIoMethods ){
6541 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6542 proxyTakeConch(pFile);
6543 if( pCtx->lockProxyPath ){
6544 *(const char **)pArg = pCtx->lockProxyPath;
6545 }else{
6546 *(const char **)pArg = ":auto: (not held)";
6547 }
6548 } else {
6549 *(const char **)pArg = NULL;
6550 }
6551 return SQLITE_OK;
6552 }
6553 case SQLITE_SET_LOCKPROXYFILE: {
6554 unixFile *pFile = (unixFile*)id;
6555 int rc = SQLITE_OK;
6556 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6557 if( pArg==NULL || (const char *)pArg==0 ){
6558 if( isProxyStyle ){
6559 /* turn off proxy locking - not supported */
6560 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6561 }else{
6562 /* turn off proxy locking - already off - NOOP */
6563 rc = SQLITE_OK;
6564 }
6565 }else{
6566 const char *proxyPath = (const char *)pArg;
6567 if( isProxyStyle ){
6568 proxyLockingContext *pCtx =
6569 (proxyLockingContext*)pFile->lockingContext;
6570 if( !strcmp(pArg, ":auto:")
6571 || (pCtx->lockProxyPath &&
6572 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6573 ){
6574 rc = SQLITE_OK;
6575 }else{
6576 rc = switchLockProxyPath(pFile, proxyPath);
6577 }
6578 }else{
6579 /* turn on proxy file locking */
6580 rc = proxyTransformUnixFile(pFile, proxyPath);
6581 }
6582 }
6583 return rc;
6584 }
6585 default: {
6586 assert( 0 ); /* The call assures that only valid opcodes are sent */
6587 }
6588 }
6589 /*NOTREACHED*/
6590 return SQLITE_ERROR;
6591}
6592
6593/*
6594** Within this division (the proxying locking implementation) the procedures
6595** above this point are all utilities. The lock-related methods of the
6596** proxy-locking sqlite3_io_method object follow.
6597*/
6598
6599
6600/*
6601** This routine checks if there is a RESERVED lock held on the specified
6602** file by this or any other process. If such a lock is held, set *pResOut
6603** to a non-zero value otherwise *pResOut is set to zero. The return value
6604** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6605*/
6606static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6607 unixFile *pFile = (unixFile*)id;
6608 int rc = proxyTakeConch(pFile);
6609 if( rc==SQLITE_OK ){
6610 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006611 if( pCtx->conchHeld>0 ){
6612 unixFile *proxy = pCtx->lockProxy;
6613 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6614 }else{ /* conchHeld < 0 is lockless */
6615 pResOut=0;
6616 }
drh715ff302008-12-03 22:32:44 +00006617 }
6618 return rc;
6619}
6620
6621/*
drh308c2a52010-05-14 11:30:18 +00006622** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006623** of the following:
6624**
6625** (1) SHARED_LOCK
6626** (2) RESERVED_LOCK
6627** (3) PENDING_LOCK
6628** (4) EXCLUSIVE_LOCK
6629**
6630** Sometimes when requesting one lock state, additional lock states
6631** are inserted in between. The locking might fail on one of the later
6632** transitions leaving the lock state different from what it started but
6633** still short of its goal. The following chart shows the allowed
6634** transitions and the inserted intermediate states:
6635**
6636** UNLOCKED -> SHARED
6637** SHARED -> RESERVED
6638** SHARED -> (PENDING) -> EXCLUSIVE
6639** RESERVED -> (PENDING) -> EXCLUSIVE
6640** PENDING -> EXCLUSIVE
6641**
6642** This routine will only increase a lock. Use the sqlite3OsUnlock()
6643** routine to lower a locking level.
6644*/
drh308c2a52010-05-14 11:30:18 +00006645static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006646 unixFile *pFile = (unixFile*)id;
6647 int rc = proxyTakeConch(pFile);
6648 if( rc==SQLITE_OK ){
6649 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006650 if( pCtx->conchHeld>0 ){
6651 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006652 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6653 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006654 }else{
6655 /* conchHeld < 0 is lockless */
6656 }
drh715ff302008-12-03 22:32:44 +00006657 }
6658 return rc;
6659}
6660
6661
6662/*
drh308c2a52010-05-14 11:30:18 +00006663** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006664** must be either NO_LOCK or SHARED_LOCK.
6665**
6666** If the locking level of the file descriptor is already at or below
6667** the requested locking level, this routine is a no-op.
6668*/
drh308c2a52010-05-14 11:30:18 +00006669static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006670 unixFile *pFile = (unixFile*)id;
6671 int rc = proxyTakeConch(pFile);
6672 if( rc==SQLITE_OK ){
6673 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006674 if( pCtx->conchHeld>0 ){
6675 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006676 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6677 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006678 }else{
6679 /* conchHeld < 0 is lockless */
6680 }
drh715ff302008-12-03 22:32:44 +00006681 }
6682 return rc;
6683}
6684
6685/*
6686** Close a file that uses proxy locks.
6687*/
6688static int proxyClose(sqlite3_file *id) {
6689 if( id ){
6690 unixFile *pFile = (unixFile*)id;
6691 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6692 unixFile *lockProxy = pCtx->lockProxy;
6693 unixFile *conchFile = pCtx->conchFile;
6694 int rc = SQLITE_OK;
6695
6696 if( lockProxy ){
6697 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6698 if( rc ) return rc;
6699 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6700 if( rc ) return rc;
6701 sqlite3_free(lockProxy);
6702 pCtx->lockProxy = 0;
6703 }
6704 if( conchFile ){
6705 if( pCtx->conchHeld ){
6706 rc = proxyReleaseConch(pFile);
6707 if( rc ) return rc;
6708 }
6709 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6710 if( rc ) return rc;
6711 sqlite3_free(conchFile);
6712 }
drhd56b1212010-08-11 06:14:15 +00006713 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006714 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006715 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006716 /* restore the original locking context and pMethod then close it */
6717 pFile->lockingContext = pCtx->oldLockingContext;
6718 pFile->pMethod = pCtx->pOldMethod;
6719 sqlite3_free(pCtx);
6720 return pFile->pMethod->xClose(id);
6721 }
6722 return SQLITE_OK;
6723}
6724
6725
6726
drhd2cb50b2009-01-09 21:41:17 +00006727#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006728/*
6729** The proxy locking style is intended for use with AFP filesystems.
6730** And since AFP is only supported on MacOSX, the proxy locking is also
6731** restricted to MacOSX.
6732**
6733**
6734******************* End of the proxy lock implementation **********************
6735******************************************************************************/
6736
drh734c9862008-11-28 15:37:20 +00006737/*
danielk1977e339d652008-06-28 11:23:00 +00006738** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006739**
6740** This routine registers all VFS implementations for unix-like operating
6741** systems. This routine, and the sqlite3_os_end() routine that follows,
6742** should be the only routines in this file that are visible from other
6743** files.
drh6b9d6dd2008-12-03 19:34:47 +00006744**
6745** This routine is called once during SQLite initialization and by a
6746** single thread. The memory allocation and mutex subsystems have not
6747** necessarily been initialized when this routine is called, and so they
6748** should not be used.
drh153c62c2007-08-24 03:51:33 +00006749*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006750int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006751 /*
6752 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006753 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6754 ** to the "finder" function. (pAppData is a pointer to a pointer because
6755 ** silly C90 rules prohibit a void* from being cast to a function pointer
6756 ** and so we have to go through the intermediate pointer to avoid problems
6757 ** when compiling with -pedantic-errors on GCC.)
6758 **
6759 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006760 ** finder-function. The finder-function returns a pointer to the
6761 ** sqlite_io_methods object that implements the desired locking
6762 ** behaviors. See the division above that contains the IOMETHODS
6763 ** macro for addition information on finder-functions.
6764 **
6765 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6766 ** object. But the "autolockIoFinder" available on MacOSX does a little
6767 ** more than that; it looks at the filesystem type that hosts the
6768 ** database file and tries to choose an locking method appropriate for
6769 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006770 */
drh7708e972008-11-29 00:56:52 +00006771 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006772 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006773 sizeof(unixFile), /* szOsFile */ \
6774 MAX_PATHNAME, /* mxPathname */ \
6775 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006776 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006777 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006778 unixOpen, /* xOpen */ \
6779 unixDelete, /* xDelete */ \
6780 unixAccess, /* xAccess */ \
6781 unixFullPathname, /* xFullPathname */ \
6782 unixDlOpen, /* xDlOpen */ \
6783 unixDlError, /* xDlError */ \
6784 unixDlSym, /* xDlSym */ \
6785 unixDlClose, /* xDlClose */ \
6786 unixRandomness, /* xRandomness */ \
6787 unixSleep, /* xSleep */ \
6788 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006789 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006790 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006791 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006792 unixGetSystemCall, /* xGetSystemCall */ \
6793 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006794 }
6795
drh6b9d6dd2008-12-03 19:34:47 +00006796 /*
6797 ** All default VFSes for unix are contained in the following array.
6798 **
6799 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6800 ** by the SQLite core when the VFS is registered. So the following
6801 ** array cannot be const.
6802 */
danielk1977e339d652008-06-28 11:23:00 +00006803 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006804#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006805 UNIXVFS("unix", autolockIoFinder ),
6806#else
6807 UNIXVFS("unix", posixIoFinder ),
6808#endif
6809 UNIXVFS("unix-none", nolockIoFinder ),
6810 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006811 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006812#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006813 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006814#endif
6815#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006816 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006817#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006818 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006819#endif
chw78a13182009-04-07 05:35:03 +00006820#endif
drhd2cb50b2009-01-09 21:41:17 +00006821#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006822 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006823 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006824 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006825#endif
drh153c62c2007-08-24 03:51:33 +00006826 };
drh6b9d6dd2008-12-03 19:34:47 +00006827 unsigned int i; /* Loop counter */
6828
drh2aa5a002011-04-13 13:42:25 +00006829 /* Double-check that the aSyscall[] array has been constructed
6830 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh1da88f02011-12-17 16:09:16 +00006831 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00006832
drh6b9d6dd2008-12-03 19:34:47 +00006833 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006834 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006835 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006836 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006837 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006838}
danielk1977e339d652008-06-28 11:23:00 +00006839
6840/*
drh6b9d6dd2008-12-03 19:34:47 +00006841** Shutdown the operating system interface.
6842**
6843** Some operating systems might need to do some cleanup in this routine,
6844** to release dynamically allocated objects. But not on unix.
6845** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006846*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006847int sqlite3_os_end(void){
6848 return SQLITE_OK;
6849}
drhdce8bdb2007-08-16 13:01:44 +00006850
danielk197729bafea2008-06-26 10:41:19 +00006851#endif /* SQLITE_OS_UNIX */