blob: e0a39882e136142f7c00b36c2909d265a17e9b4f [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
danielk1977e339d652008-06-28 11:23:00 +0000126
drh40bbb0a2008-09-23 10:23:26 +0000127#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000128# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000129# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000130# include <semaphore.h>
131# include <limits.h>
132# else
drh9b35ea62008-11-29 02:20:26 +0000133# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000134# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000135# endif
drhbfe66312006-10-03 17:40:40 +0000136#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000137
drhf8b4d8c2010-03-05 13:53:22 +0000138#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000139# include <sys/mount.h>
140#endif
141
drhdbe4b882011-06-20 18:00:17 +0000142#ifdef HAVE_UTIME
143# include <utime.h>
144#endif
145
drh9cbe6352005-11-29 03:13:21 +0000146/*
drh7ed97b92010-01-20 13:07:21 +0000147** Allowed values of unixFile.fsFlags
148*/
149#define SQLITE_FSFLAGS_IS_MSDOS 0x1
150
151/*
drhf1a221e2006-01-15 17:27:17 +0000152** If we are to be thread-safe, include the pthreads header and define
153** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000154*/
drhd677b3d2007-08-20 22:48:41 +0000155#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000156# include <pthread.h>
157# define SQLITE_UNIX_THREADS 1
158#endif
159
160/*
161** Default permissions when creating a new file
162*/
163#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
164# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
165#endif
166
danielk1977b4b47412007-08-17 15:53:36 +0000167/*
aswiftaebf4132008-11-21 00:10:35 +0000168 ** Default permissions when creating auto proxy dir
169 */
170#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
171# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
172#endif
173
174/*
danielk1977b4b47412007-08-17 15:53:36 +0000175** Maximum supported path-length.
176*/
177#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000178
drh734c9862008-11-28 15:37:20 +0000179/*
drh734c9862008-11-28 15:37:20 +0000180** Only set the lastErrno if the error code is a real error and not
181** a normal expected return code of SQLITE_BUSY or SQLITE_OK
182*/
183#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
184
drhd91c68f2010-05-14 14:52:25 +0000185/* Forward references */
186typedef struct unixShm unixShm; /* Connection shared memory */
187typedef struct unixShmNode unixShmNode; /* Shared memory instance */
188typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
189typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000190
191/*
dane946c392009-08-22 11:39:46 +0000192** Sometimes, after a file handle is closed by SQLite, the file descriptor
193** cannot be closed immediately. In these cases, instances of the following
194** structure are used to store the file descriptor while waiting for an
195** opportunity to either close or reuse it.
196*/
dane946c392009-08-22 11:39:46 +0000197struct UnixUnusedFd {
198 int fd; /* File descriptor to close */
199 int flags; /* Flags this file descriptor was opened with */
200 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
201};
202
203/*
drh9b35ea62008-11-29 02:20:26 +0000204** The unixFile structure is subclass of sqlite3_file specific to the unix
205** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000206*/
drh054889e2005-11-30 03:20:31 +0000207typedef struct unixFile unixFile;
208struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000209 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000210 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000211 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000212 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000213 unsigned char eFileLock; /* The type of lock held on this fd */
drha7e61d82011-03-12 17:02:57 +0000214 unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000215 int lastErrno; /* The unix errno from last I/O error */
216 void *lockingContext; /* Locking style specific state */
217 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000218 const char *zPath; /* Name of the file */
219 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000220 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh08c6d442009-02-09 17:34:07 +0000221#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000222 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000223#endif
drh7ed97b92010-01-20 13:07:21 +0000224#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000225 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000226#endif
227#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000228 int isDelete; /* Delete on close if true */
229 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000230#endif
drh8f941bc2009-01-14 23:03:40 +0000231#ifndef NDEBUG
232 /* The next group of variables are used to track whether or not the
233 ** transaction counter in bytes 24-27 of database files are updated
234 ** whenever any part of the database changes. An assertion fault will
235 ** occur if a file is updated without also updating the transaction
236 ** counter. This test is made to avoid new problems similar to the
237 ** one described by ticket #3584.
238 */
239 unsigned char transCntrChng; /* True if the transaction counter changed */
240 unsigned char dbUpdate; /* True if any part of database file changed */
241 unsigned char inNormalWrite; /* True if in a normal write operation */
242#endif
danielk1977967a4a12007-08-20 14:23:44 +0000243#ifdef SQLITE_TEST
244 /* In test mode, increase the size of this structure a bit so that
245 ** it is larger than the struct CrashFile defined in test6.c.
246 */
247 char aPadding[32];
248#endif
drh9cbe6352005-11-29 03:13:21 +0000249};
250
drh0ccebe72005-06-07 22:22:50 +0000251/*
drha7e61d82011-03-12 17:02:57 +0000252** Allowed values for the unixFile.ctrlFlags bitmask:
253*/
drhf0b190d2011-07-26 16:03:07 +0000254#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
255#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
256#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000257#ifndef SQLITE_DISABLE_DIRSYNC
258# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
259#else
260# define UNIXFILE_DIRSYNC 0x00
261#endif
drhcb15f352011-12-23 01:04:17 +0000262#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drha7e61d82011-03-12 17:02:57 +0000263
264/*
drh198bf392006-01-06 21:52:49 +0000265** Include code that is common to all os_*.c files
266*/
267#include "os_common.h"
268
269/*
drh0ccebe72005-06-07 22:22:50 +0000270** Define various macros that are missing from some systems.
271*/
drhbbd42a62004-05-22 17:41:58 +0000272#ifndef O_LARGEFILE
273# define O_LARGEFILE 0
274#endif
275#ifdef SQLITE_DISABLE_LFS
276# undef O_LARGEFILE
277# define O_LARGEFILE 0
278#endif
279#ifndef O_NOFOLLOW
280# define O_NOFOLLOW 0
281#endif
282#ifndef O_BINARY
283# define O_BINARY 0
284#endif
285
286/*
drh2b4b5962005-06-15 17:47:55 +0000287** The threadid macro resolves to the thread-id or to 0. Used for
288** testing and debugging only.
289*/
drhd677b3d2007-08-20 22:48:41 +0000290#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000291#define threadid pthread_self()
292#else
293#define threadid 0
294#endif
295
drh99ab3b12011-03-02 15:09:07 +0000296/*
drh9a3baf12011-04-25 18:01:27 +0000297** Different Unix systems declare open() in different ways. Same use
298** open(const char*,int,mode_t). Others use open(const char*,int,...).
299** The difference is important when using a pointer to the function.
300**
301** The safest way to deal with the problem is to always use this wrapper
302** which always has the same well-defined interface.
303*/
304static int posixOpen(const char *zFile, int flags, int mode){
305 return open(zFile, flags, mode);
306}
307
drh90315a22011-08-10 01:52:12 +0000308/* Forward reference */
309static int openDirectory(const char*, int*);
310
drh9a3baf12011-04-25 18:01:27 +0000311/*
drh99ab3b12011-03-02 15:09:07 +0000312** Many system calls are accessed through pointer-to-functions so that
313** they may be overridden at runtime to facilitate fault injection during
314** testing and sandboxing. The following array holds the names and pointers
315** to all overrideable system calls.
316*/
317static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000318 const char *zName; /* Name of the sytem call */
319 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
320 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000321} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000322 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
323#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000324
drh58ad5802011-03-23 22:02:23 +0000325 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000326#define osClose ((int(*)(int))aSyscall[1].pCurrent)
327
drh58ad5802011-03-23 22:02:23 +0000328 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000329#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
330
drh58ad5802011-03-23 22:02:23 +0000331 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000332#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
333
drh58ad5802011-03-23 22:02:23 +0000334 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000335#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
336
337/*
338** The DJGPP compiler environment looks mostly like Unix, but it
339** lacks the fcntl() system call. So redefine fcntl() to be something
340** that always succeeds. This means that locking does not occur under
341** DJGPP. But it is DOS - what did you expect?
342*/
343#ifdef __DJGPP__
344 { "fstat", 0, 0 },
345#define osFstat(a,b,c) 0
346#else
drh58ad5802011-03-23 22:02:23 +0000347 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
349#endif
350
drh58ad5802011-03-23 22:02:23 +0000351 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
353
drh58ad5802011-03-23 22:02:23 +0000354 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000356
drh58ad5802011-03-23 22:02:23 +0000357 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000358#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
359
drhd4a80312011-04-15 14:33:20 +0000360#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000361 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000362#else
drh58ad5802011-03-23 22:02:23 +0000363 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000364#endif
365#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
366
367#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000368 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000369#else
drh58ad5802011-03-23 22:02:23 +0000370 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000371#endif
372#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
373
drh58ad5802011-03-23 22:02:23 +0000374 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000375#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
376
drhd4a80312011-04-15 14:33:20 +0000377#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000378 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000379#else
drh58ad5802011-03-23 22:02:23 +0000380 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000381#endif
382#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
383 aSyscall[12].pCurrent)
384
385#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000386 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000387#else
drh58ad5802011-03-23 22:02:23 +0000388 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000389#endif
390#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
391 aSyscall[13].pCurrent)
392
drha6c47492011-04-11 18:35:09 +0000393#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000394 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000395#else
396 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000397#endif
drh2aa5a002011-04-13 13:42:25 +0000398#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000399
400#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000401 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000402#else
drh58ad5802011-03-23 22:02:23 +0000403 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000404#endif
dan0fd7d862011-03-29 10:04:23 +0000405#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000406
drh036ac7f2011-08-08 23:18:05 +0000407 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
408#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
409
drh90315a22011-08-10 01:52:12 +0000410 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
411#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
412
drh9ef6bc42011-11-04 02:24:02 +0000413 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
414#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
415
416 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
417#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
418
drhe562be52011-03-02 18:01:10 +0000419}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000420
421/*
422** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000423** "unix" VFSes. Return SQLITE_OK opon successfully updating the
424** system call pointer, or SQLITE_NOTFOUND if there is no configurable
425** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000426*/
427static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000428 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
429 const char *zName, /* Name of system call to override */
430 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000431){
drh58ad5802011-03-23 22:02:23 +0000432 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000433 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000434
435 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000436 if( zName==0 ){
437 /* If no zName is given, restore all system calls to their default
438 ** settings and return NULL
439 */
dan51438a72011-04-02 17:00:47 +0000440 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000441 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
442 if( aSyscall[i].pDefault ){
443 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000444 }
445 }
446 }else{
447 /* If zName is specified, operate on only the one system call
448 ** specified.
449 */
450 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
451 if( strcmp(zName, aSyscall[i].zName)==0 ){
452 if( aSyscall[i].pDefault==0 ){
453 aSyscall[i].pDefault = aSyscall[i].pCurrent;
454 }
drh1df30962011-03-02 19:06:42 +0000455 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000456 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
457 aSyscall[i].pCurrent = pNewFunc;
458 break;
459 }
460 }
461 }
462 return rc;
463}
464
drh1df30962011-03-02 19:06:42 +0000465/*
466** Return the value of a system call. Return NULL if zName is not a
467** recognized system call name. NULL is also returned if the system call
468** is currently undefined.
469*/
drh58ad5802011-03-23 22:02:23 +0000470static sqlite3_syscall_ptr unixGetSystemCall(
471 sqlite3_vfs *pNotUsed,
472 const char *zName
473){
474 unsigned int i;
475
476 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000477 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
478 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
479 }
480 return 0;
481}
482
483/*
484** Return the name of the first system call after zName. If zName==NULL
485** then return the name of the first system call. Return NULL if zName
486** is the last system call or if zName is not the name of a valid
487** system call.
488*/
489static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000490 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000491
492 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000493 if( zName ){
494 for(i=0; i<ArraySize(aSyscall)-1; i++){
495 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000496 }
497 }
dan0fd7d862011-03-29 10:04:23 +0000498 for(i++; i<ArraySize(aSyscall); i++){
499 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000500 }
501 return 0;
502}
503
drhad4f1e52011-03-04 15:43:57 +0000504/*
505** Retry open() calls that fail due to EINTR
506*/
507static int robust_open(const char *z, int f, int m){
508 int rc;
509 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
510 return rc;
511}
danielk197713adf8a2004-06-03 16:08:41 +0000512
drh107886a2008-11-21 22:21:50 +0000513/*
dan9359c7b2009-08-21 08:29:10 +0000514** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000515** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000516** vxworksFileId objects used by this file, all of which may be
517** shared by multiple threads.
518**
519** Function unixMutexHeld() is used to assert() that the global mutex
520** is held when required. This function is only used as part of assert()
521** statements. e.g.
522**
523** unixEnterMutex()
524** assert( unixMutexHeld() );
525** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000526*/
527static void unixEnterMutex(void){
528 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
529}
530static void unixLeaveMutex(void){
531 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
532}
dan9359c7b2009-08-21 08:29:10 +0000533#ifdef SQLITE_DEBUG
534static int unixMutexHeld(void) {
535 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
536}
537#endif
drh107886a2008-11-21 22:21:50 +0000538
drh734c9862008-11-28 15:37:20 +0000539
drh30ddce62011-10-15 00:16:30 +0000540#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000541/*
542** Helper function for printing out trace information from debugging
543** binaries. This returns the string represetation of the supplied
544** integer lock-type.
545*/
drh308c2a52010-05-14 11:30:18 +0000546static const char *azFileLock(int eFileLock){
547 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000548 case NO_LOCK: return "NONE";
549 case SHARED_LOCK: return "SHARED";
550 case RESERVED_LOCK: return "RESERVED";
551 case PENDING_LOCK: return "PENDING";
552 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000553 }
554 return "ERROR";
555}
556#endif
557
558#ifdef SQLITE_LOCK_TRACE
559/*
560** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000561**
drh734c9862008-11-28 15:37:20 +0000562** This routine is used for troubleshooting locks on multithreaded
563** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
564** command-line option on the compiler. This code is normally
565** turned off.
566*/
567static int lockTrace(int fd, int op, struct flock *p){
568 char *zOpName, *zType;
569 int s;
570 int savedErrno;
571 if( op==F_GETLK ){
572 zOpName = "GETLK";
573 }else if( op==F_SETLK ){
574 zOpName = "SETLK";
575 }else{
drh99ab3b12011-03-02 15:09:07 +0000576 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000577 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
578 return s;
579 }
580 if( p->l_type==F_RDLCK ){
581 zType = "RDLCK";
582 }else if( p->l_type==F_WRLCK ){
583 zType = "WRLCK";
584 }else if( p->l_type==F_UNLCK ){
585 zType = "UNLCK";
586 }else{
587 assert( 0 );
588 }
589 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000590 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000591 savedErrno = errno;
592 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
593 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
594 (int)p->l_pid, s);
595 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
596 struct flock l2;
597 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000598 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000599 if( l2.l_type==F_RDLCK ){
600 zType = "RDLCK";
601 }else if( l2.l_type==F_WRLCK ){
602 zType = "WRLCK";
603 }else if( l2.l_type==F_UNLCK ){
604 zType = "UNLCK";
605 }else{
606 assert( 0 );
607 }
608 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
609 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
610 }
611 errno = savedErrno;
612 return s;
613}
drh99ab3b12011-03-02 15:09:07 +0000614#undef osFcntl
615#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000616#endif /* SQLITE_LOCK_TRACE */
617
drhff812312011-02-23 13:33:46 +0000618/*
619** Retry ftruncate() calls that fail due to EINTR
620*/
drhff812312011-02-23 13:33:46 +0000621static int robust_ftruncate(int h, sqlite3_int64 sz){
622 int rc;
drh99ab3b12011-03-02 15:09:07 +0000623 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000624 return rc;
625}
drh734c9862008-11-28 15:37:20 +0000626
627/*
628** This routine translates a standard POSIX errno code into something
629** useful to the clients of the sqlite3 functions. Specifically, it is
630** intended to translate a variety of "try again" errors into SQLITE_BUSY
631** and a variety of "please close the file descriptor NOW" errors into
632** SQLITE_IOERR
633**
634** Errors during initialization of locks, or file system support for locks,
635** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
636*/
637static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
638 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000639#if 0
640 /* At one point this code was not commented out. In theory, this branch
641 ** should never be hit, as this function should only be called after
642 ** a locking-related function (i.e. fcntl()) has returned non-zero with
643 ** the value of errno as the first argument. Since a system call has failed,
644 ** errno should be non-zero.
645 **
646 ** Despite this, if errno really is zero, we still don't want to return
647 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
648 ** propagated back to the caller. Commenting this branch out means errno==0
649 ** will be handled by the "default:" case below.
650 */
drh734c9862008-11-28 15:37:20 +0000651 case 0:
652 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000653#endif
654
drh734c9862008-11-28 15:37:20 +0000655 case EAGAIN:
656 case ETIMEDOUT:
657 case EBUSY:
658 case EINTR:
659 case ENOLCK:
660 /* random NFS retry error, unless during file system support
661 * introspection, in which it actually means what it says */
662 return SQLITE_BUSY;
663
664 case EACCES:
665 /* EACCES is like EAGAIN during locking operations, but not any other time*/
666 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
667 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
668 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
669 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
670 return SQLITE_BUSY;
671 }
672 /* else fall through */
673 case EPERM:
674 return SQLITE_PERM;
675
danea83bc62011-04-01 11:56:32 +0000676 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
677 ** this module never makes such a call. And the code in SQLite itself
678 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
679 ** this case is also commented out. If the system does set errno to EDEADLK,
680 ** the default SQLITE_IOERR_XXX code will be returned. */
681#if 0
drh734c9862008-11-28 15:37:20 +0000682 case EDEADLK:
683 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000684#endif
drh734c9862008-11-28 15:37:20 +0000685
686#if EOPNOTSUPP!=ENOTSUP
687 case EOPNOTSUPP:
688 /* something went terribly awry, unless during file system support
689 * introspection, in which it actually means what it says */
690#endif
691#ifdef ENOTSUP
692 case ENOTSUP:
693 /* invalid fd, unless during file system support introspection, in which
694 * it actually means what it says */
695#endif
696 case EIO:
697 case EBADF:
698 case EINVAL:
699 case ENOTCONN:
700 case ENODEV:
701 case ENXIO:
702 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000703#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000704 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000705#endif
drh734c9862008-11-28 15:37:20 +0000706 case ENOSYS:
707 /* these should force the client to close the file and reconnect */
708
709 default:
710 return sqliteIOErr;
711 }
712}
713
714
715
716/******************************************************************************
717****************** Begin Unique File ID Utility Used By VxWorks ***************
718**
719** On most versions of unix, we can get a unique ID for a file by concatenating
720** the device number and the inode number. But this does not work on VxWorks.
721** On VxWorks, a unique file id must be based on the canonical filename.
722**
723** A pointer to an instance of the following structure can be used as a
724** unique file ID in VxWorks. Each instance of this structure contains
725** a copy of the canonical filename. There is also a reference count.
726** The structure is reclaimed when the number of pointers to it drops to
727** zero.
728**
729** There are never very many files open at one time and lookups are not
730** a performance-critical path, so it is sufficient to put these
731** structures on a linked list.
732*/
733struct vxworksFileId {
734 struct vxworksFileId *pNext; /* Next in a list of them all */
735 int nRef; /* Number of references to this one */
736 int nName; /* Length of the zCanonicalName[] string */
737 char *zCanonicalName; /* Canonical filename */
738};
739
740#if OS_VXWORKS
741/*
drh9b35ea62008-11-29 02:20:26 +0000742** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000743** variable:
744*/
745static struct vxworksFileId *vxworksFileList = 0;
746
747/*
748** Simplify a filename into its canonical form
749** by making the following changes:
750**
751** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000752** * convert /./ into just /
753** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000754**
755** Changes are made in-place. Return the new name length.
756**
757** The original filename is in z[0..n-1]. Return the number of
758** characters in the simplified name.
759*/
760static int vxworksSimplifyName(char *z, int n){
761 int i, j;
762 while( n>1 && z[n-1]=='/' ){ n--; }
763 for(i=j=0; i<n; i++){
764 if( z[i]=='/' ){
765 if( z[i+1]=='/' ) continue;
766 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
767 i += 1;
768 continue;
769 }
770 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
771 while( j>0 && z[j-1]!='/' ){ j--; }
772 if( j>0 ){ j--; }
773 i += 2;
774 continue;
775 }
776 }
777 z[j++] = z[i];
778 }
779 z[j] = 0;
780 return j;
781}
782
783/*
784** Find a unique file ID for the given absolute pathname. Return
785** a pointer to the vxworksFileId object. This pointer is the unique
786** file ID.
787**
788** The nRef field of the vxworksFileId object is incremented before
789** the object is returned. A new vxworksFileId object is created
790** and added to the global list if necessary.
791**
792** If a memory allocation error occurs, return NULL.
793*/
794static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
795 struct vxworksFileId *pNew; /* search key and new file ID */
796 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
797 int n; /* Length of zAbsoluteName string */
798
799 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000800 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000801 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
802 if( pNew==0 ) return 0;
803 pNew->zCanonicalName = (char*)&pNew[1];
804 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
805 n = vxworksSimplifyName(pNew->zCanonicalName, n);
806
807 /* Search for an existing entry that matching the canonical name.
808 ** If found, increment the reference count and return a pointer to
809 ** the existing file ID.
810 */
811 unixEnterMutex();
812 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
813 if( pCandidate->nName==n
814 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
815 ){
816 sqlite3_free(pNew);
817 pCandidate->nRef++;
818 unixLeaveMutex();
819 return pCandidate;
820 }
821 }
822
823 /* No match was found. We will make a new file ID */
824 pNew->nRef = 1;
825 pNew->nName = n;
826 pNew->pNext = vxworksFileList;
827 vxworksFileList = pNew;
828 unixLeaveMutex();
829 return pNew;
830}
831
832/*
833** Decrement the reference count on a vxworksFileId object. Free
834** the object when the reference count reaches zero.
835*/
836static void vxworksReleaseFileId(struct vxworksFileId *pId){
837 unixEnterMutex();
838 assert( pId->nRef>0 );
839 pId->nRef--;
840 if( pId->nRef==0 ){
841 struct vxworksFileId **pp;
842 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
843 assert( *pp==pId );
844 *pp = pId->pNext;
845 sqlite3_free(pId);
846 }
847 unixLeaveMutex();
848}
849#endif /* OS_VXWORKS */
850/*************** End of Unique File ID Utility Used By VxWorks ****************
851******************************************************************************/
852
853
854/******************************************************************************
855*************************** Posix Advisory Locking ****************************
856**
drh9b35ea62008-11-29 02:20:26 +0000857** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000858** section 6.5.2.2 lines 483 through 490 specify that when a process
859** sets or clears a lock, that operation overrides any prior locks set
860** by the same process. It does not explicitly say so, but this implies
861** that it overrides locks set by the same process using a different
862** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000863**
864** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000865** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
866**
867** Suppose ./file1 and ./file2 are really the same file (because
868** one is a hard or symbolic link to the other) then if you set
869** an exclusive lock on fd1, then try to get an exclusive lock
870** on fd2, it works. I would have expected the second lock to
871** fail since there was already a lock on the file due to fd1.
872** But not so. Since both locks came from the same process, the
873** second overrides the first, even though they were on different
874** file descriptors opened on different file names.
875**
drh734c9862008-11-28 15:37:20 +0000876** This means that we cannot use POSIX locks to synchronize file access
877** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000878** to synchronize access for threads in separate processes, but not
879** threads within the same process.
880**
881** To work around the problem, SQLite has to manage file locks internally
882** on its own. Whenever a new database is opened, we have to find the
883** specific inode of the database file (the inode is determined by the
884** st_dev and st_ino fields of the stat structure that fstat() fills in)
885** and check for locks already existing on that inode. When locks are
886** created or removed, we have to look at our own internal record of the
887** locks to see if another thread has previously set a lock on that same
888** inode.
889**
drh9b35ea62008-11-29 02:20:26 +0000890** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
891** For VxWorks, we have to use the alternative unique ID system based on
892** canonical filename and implemented in the previous division.)
893**
danielk1977ad94b582007-08-20 06:44:22 +0000894** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000895** descriptor. It is now a structure that holds the integer file
896** descriptor and a pointer to a structure that describes the internal
897** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000898** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000899** point to the same locking structure. The locking structure keeps
900** a reference count (so we will know when to delete it) and a "cnt"
901** field that tells us its internal lock status. cnt==0 means the
902** file is unlocked. cnt==-1 means the file has an exclusive lock.
903** cnt>0 means there are cnt shared locks on the file.
904**
905** Any attempt to lock or unlock a file first checks the locking
906** structure. The fcntl() system call is only invoked to set a
907** POSIX lock if the internal lock structure transitions between
908** a locked and an unlocked state.
909**
drh734c9862008-11-28 15:37:20 +0000910** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000911**
912** If you close a file descriptor that points to a file that has locks,
913** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000914** released. To work around this problem, each unixInodeInfo object
915** maintains a count of the number of pending locks on tha inode.
916** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000917** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000918** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000919** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000920** be closed and that list is walked (and cleared) when the last lock
921** clears.
922**
drh9b35ea62008-11-29 02:20:26 +0000923** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000924**
drh9b35ea62008-11-29 02:20:26 +0000925** Many older versions of linux use the LinuxThreads library which is
926** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000927** A cannot be modified or overridden by a different thread B.
928** Only thread A can modify the lock. Locking behavior is correct
929** if the appliation uses the newer Native Posix Thread Library (NPTL)
930** on linux - with NPTL a lock created by thread A can override locks
931** in thread B. But there is no way to know at compile-time which
932** threading library is being used. So there is no way to know at
933** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000934** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000935** current process.
drh5fdae772004-06-29 03:29:00 +0000936**
drh8af6c222010-05-14 12:43:01 +0000937** SQLite used to support LinuxThreads. But support for LinuxThreads
938** was dropped beginning with version 3.7.0. SQLite will still work with
939** LinuxThreads provided that (1) there is no more than one connection
940** per database file in the same process and (2) database connections
941** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000942*/
943
944/*
945** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000946** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000947*/
948struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000949 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000950#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000951 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000952#else
drh107886a2008-11-21 22:21:50 +0000953 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000954#endif
955};
956
957/*
drhbbd42a62004-05-22 17:41:58 +0000958** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000959** inode. Or, on LinuxThreads, there is one of these structures for
960** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000961**
danielk1977ad94b582007-08-20 06:44:22 +0000962** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000963** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000964** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000965*/
drh8af6c222010-05-14 12:43:01 +0000966struct unixInodeInfo {
967 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000968 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000969 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
970 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000971 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000972 unixShmNode *pShmNode; /* Shared memory associated with this inode */
973 int nLock; /* Number of outstanding file locks */
974 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
975 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
976 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000977#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000978 unsigned long long sharedByte; /* for AFP simulated shared lock */
979#endif
drh6c7d5c52008-11-21 20:32:33 +0000980#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000981 sem_t *pSem; /* Named POSIX semaphore */
982 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000983#endif
drhbbd42a62004-05-22 17:41:58 +0000984};
985
drhda0e7682008-07-30 15:27:54 +0000986/*
drh8af6c222010-05-14 12:43:01 +0000987** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000988*/
drhd91c68f2010-05-14 14:52:25 +0000989static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000990
drh5fdae772004-06-29 03:29:00 +0000991/*
dane18d4952011-02-21 11:46:24 +0000992**
993** This function - unixLogError_x(), is only ever called via the macro
994** unixLogError().
995**
996** It is invoked after an error occurs in an OS function and errno has been
997** set. It logs a message using sqlite3_log() containing the current value of
998** errno and, if possible, the human-readable equivalent from strerror() or
999** strerror_r().
1000**
1001** The first argument passed to the macro should be the error code that
1002** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1003** The two subsequent arguments should be the name of the OS function that
1004** failed (e.g. "unlink", "open") and the the associated file-system path,
1005** if any.
1006*/
drh0e9365c2011-03-02 02:08:13 +00001007#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1008static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001009 int errcode, /* SQLite error code */
1010 const char *zFunc, /* Name of OS function that failed */
1011 const char *zPath, /* File path associated with error */
1012 int iLine /* Source line number where error occurred */
1013){
1014 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001015 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001016
1017 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1018 ** the strerror() function to obtain the human-readable error message
1019 ** equivalent to errno. Otherwise, use strerror_r().
1020 */
1021#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1022 char aErr[80];
1023 memset(aErr, 0, sizeof(aErr));
1024 zErr = aErr;
1025
1026 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1027 ** assume that the system provides the the GNU version of strerror_r() that
1028 ** returns a pointer to a buffer containing the error message. That pointer
1029 ** may point to aErr[], or it may point to some static storage somewhere.
1030 ** Otherwise, assume that the system provides the POSIX version of
1031 ** strerror_r(), which always writes an error message into aErr[].
1032 **
1033 ** If the code incorrectly assumes that it is the POSIX version that is
1034 ** available, the error message will often be an empty string. Not a
1035 ** huge problem. Incorrectly concluding that the GNU version is available
1036 ** could lead to a segfault though.
1037 */
1038#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1039 zErr =
1040# endif
drh0e9365c2011-03-02 02:08:13 +00001041 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001042
1043#elif SQLITE_THREADSAFE
1044 /* This is a threadsafe build, but strerror_r() is not available. */
1045 zErr = "";
1046#else
1047 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001048 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001049#endif
1050
1051 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001052 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001053 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001054 "os_unix.c:%d: (%d) %s(%s) - %s",
1055 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001056 );
1057
1058 return errcode;
1059}
1060
drh0e9365c2011-03-02 02:08:13 +00001061/*
1062** Close a file descriptor.
1063**
1064** We assume that close() almost always works, since it is only in a
1065** very sick application or on a very sick platform that it might fail.
1066** If it does fail, simply leak the file descriptor, but do log the
1067** error.
1068**
1069** Note that it is not safe to retry close() after EINTR since the
1070** file descriptor might have already been reused by another thread.
1071** So we don't even try to recover from an EINTR. Just log the error
1072** and move on.
1073*/
1074static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001075 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001076 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1077 pFile ? pFile->zPath : 0, lineno);
1078 }
1079}
dane18d4952011-02-21 11:46:24 +00001080
1081/*
danb0ac3e32010-06-16 10:55:42 +00001082** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001083*/
drh0e9365c2011-03-02 02:08:13 +00001084static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001085 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001086 UnixUnusedFd *p;
1087 UnixUnusedFd *pNext;
1088 for(p=pInode->pUnused; p; p=pNext){
1089 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001090 robust_close(pFile, p->fd, __LINE__);
1091 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001092 }
drh0e9365c2011-03-02 02:08:13 +00001093 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001094}
1095
1096/*
drh8af6c222010-05-14 12:43:01 +00001097** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001098**
1099** The mutex entered using the unixEnterMutex() function must be held
1100** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001101*/
danb0ac3e32010-06-16 10:55:42 +00001102static void releaseInodeInfo(unixFile *pFile){
1103 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001104 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001105 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001106 pInode->nRef--;
1107 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001108 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001109 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001110 if( pInode->pPrev ){
1111 assert( pInode->pPrev->pNext==pInode );
1112 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001113 }else{
drh8af6c222010-05-14 12:43:01 +00001114 assert( inodeList==pInode );
1115 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001116 }
drh8af6c222010-05-14 12:43:01 +00001117 if( pInode->pNext ){
1118 assert( pInode->pNext->pPrev==pInode );
1119 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001120 }
drh8af6c222010-05-14 12:43:01 +00001121 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001122 }
drhbbd42a62004-05-22 17:41:58 +00001123 }
1124}
1125
1126/*
drh8af6c222010-05-14 12:43:01 +00001127** Given a file descriptor, locate the unixInodeInfo object that
1128** describes that file descriptor. Create a new one if necessary. The
1129** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001130**
dan9359c7b2009-08-21 08:29:10 +00001131** The mutex entered using the unixEnterMutex() function must be held
1132** when this function is called.
1133**
drh6c7d5c52008-11-21 20:32:33 +00001134** Return an appropriate error code.
1135*/
drh8af6c222010-05-14 12:43:01 +00001136static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001137 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001138 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001139){
1140 int rc; /* System call return code */
1141 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001142 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1143 struct stat statbuf; /* Low-level file information */
1144 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001145
dan9359c7b2009-08-21 08:29:10 +00001146 assert( unixMutexHeld() );
1147
drh6c7d5c52008-11-21 20:32:33 +00001148 /* Get low-level information about the file that we can used to
1149 ** create a unique name for the file.
1150 */
1151 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001152 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001153 if( rc!=0 ){
1154 pFile->lastErrno = errno;
1155#ifdef EOVERFLOW
1156 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1157#endif
1158 return SQLITE_IOERR;
1159 }
1160
drheb0d74f2009-02-03 15:27:02 +00001161#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001162 /* On OS X on an msdos filesystem, the inode number is reported
1163 ** incorrectly for zero-size files. See ticket #3260. To work
1164 ** around this problem (we consider it a bug in OS X, not SQLite)
1165 ** we always increase the file size to 1 by writing a single byte
1166 ** prior to accessing the inode number. The one byte written is
1167 ** an ASCII 'S' character which also happens to be the first byte
1168 ** in the header of every SQLite database. In this way, if there
1169 ** is a race condition such that another thread has already populated
1170 ** the first page of the database, no damage is done.
1171 */
drh7ed97b92010-01-20 13:07:21 +00001172 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001173 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001174 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001175 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001176 return SQLITE_IOERR;
1177 }
drh99ab3b12011-03-02 15:09:07 +00001178 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001179 if( rc!=0 ){
1180 pFile->lastErrno = errno;
1181 return SQLITE_IOERR;
1182 }
1183 }
drheb0d74f2009-02-03 15:27:02 +00001184#endif
drh6c7d5c52008-11-21 20:32:33 +00001185
drh8af6c222010-05-14 12:43:01 +00001186 memset(&fileId, 0, sizeof(fileId));
1187 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001188#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001189 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001190#else
drh8af6c222010-05-14 12:43:01 +00001191 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001192#endif
drh8af6c222010-05-14 12:43:01 +00001193 pInode = inodeList;
1194 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1195 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001196 }
drh8af6c222010-05-14 12:43:01 +00001197 if( pInode==0 ){
1198 pInode = sqlite3_malloc( sizeof(*pInode) );
1199 if( pInode==0 ){
1200 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001201 }
drh8af6c222010-05-14 12:43:01 +00001202 memset(pInode, 0, sizeof(*pInode));
1203 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1204 pInode->nRef = 1;
1205 pInode->pNext = inodeList;
1206 pInode->pPrev = 0;
1207 if( inodeList ) inodeList->pPrev = pInode;
1208 inodeList = pInode;
1209 }else{
1210 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001211 }
drh8af6c222010-05-14 12:43:01 +00001212 *ppInode = pInode;
1213 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001214}
drh6c7d5c52008-11-21 20:32:33 +00001215
aswift5b1a2562008-08-22 00:22:35 +00001216
1217/*
danielk197713adf8a2004-06-03 16:08:41 +00001218** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001219** file by this or any other process. If such a lock is held, set *pResOut
1220** to a non-zero value otherwise *pResOut is set to zero. The return value
1221** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001222*/
danielk1977861f7452008-06-05 11:39:11 +00001223static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001224 int rc = SQLITE_OK;
1225 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001226 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001227
danielk1977861f7452008-06-05 11:39:11 +00001228 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1229
drh054889e2005-11-30 03:20:31 +00001230 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001231 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001232
1233 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001234 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001235 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001236 }
1237
drh2ac3ee92004-06-07 16:27:46 +00001238 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001239 */
danielk197709480a92009-02-09 05:32:32 +00001240#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001241 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001242 struct flock lock;
1243 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001244 lock.l_start = RESERVED_BYTE;
1245 lock.l_len = 1;
1246 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001247 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1248 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1249 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001250 } else if( lock.l_type!=F_UNLCK ){
1251 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001252 }
1253 }
danielk197709480a92009-02-09 05:32:32 +00001254#endif
danielk197713adf8a2004-06-03 16:08:41 +00001255
drh6c7d5c52008-11-21 20:32:33 +00001256 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001257 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001258
aswift5b1a2562008-08-22 00:22:35 +00001259 *pResOut = reserved;
1260 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001261}
1262
1263/*
drha7e61d82011-03-12 17:02:57 +00001264** Attempt to set a system-lock on the file pFile. The lock is
1265** described by pLock.
1266**
drh77197112011-03-15 19:08:48 +00001267** If the pFile was opened read/write from unix-excl, then the only lock
1268** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001269** the first time any lock is attempted. All subsequent system locking
1270** operations become no-ops. Locking operations still happen internally,
1271** in order to coordinate access between separate database connections
1272** within this process, but all of that is handled in memory and the
1273** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001274**
1275** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1276** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1277** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001278**
1279** Zero is returned if the call completes successfully, or -1 if a call
1280** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001281*/
1282static int unixFileLock(unixFile *pFile, struct flock *pLock){
1283 int rc;
drh3cb93392011-03-12 18:10:44 +00001284 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001285 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001286 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001287 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1288 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1289 ){
drh3cb93392011-03-12 18:10:44 +00001290 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001291 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001292 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001293 lock.l_whence = SEEK_SET;
1294 lock.l_start = SHARED_FIRST;
1295 lock.l_len = SHARED_SIZE;
1296 lock.l_type = F_WRLCK;
1297 rc = osFcntl(pFile->h, F_SETLK, &lock);
1298 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001299 pInode->bProcessLock = 1;
1300 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001301 }else{
1302 rc = 0;
1303 }
1304 }else{
1305 rc = osFcntl(pFile->h, F_SETLK, pLock);
1306 }
1307 return rc;
1308}
1309
1310/*
drh308c2a52010-05-14 11:30:18 +00001311** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001312** of the following:
1313**
drh2ac3ee92004-06-07 16:27:46 +00001314** (1) SHARED_LOCK
1315** (2) RESERVED_LOCK
1316** (3) PENDING_LOCK
1317** (4) EXCLUSIVE_LOCK
1318**
drhb3e04342004-06-08 00:47:47 +00001319** Sometimes when requesting one lock state, additional lock states
1320** are inserted in between. The locking might fail on one of the later
1321** transitions leaving the lock state different from what it started but
1322** still short of its goal. The following chart shows the allowed
1323** transitions and the inserted intermediate states:
1324**
1325** UNLOCKED -> SHARED
1326** SHARED -> RESERVED
1327** SHARED -> (PENDING) -> EXCLUSIVE
1328** RESERVED -> (PENDING) -> EXCLUSIVE
1329** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001330**
drha6abd042004-06-09 17:37:22 +00001331** This routine will only increase a lock. Use the sqlite3OsUnlock()
1332** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001333*/
drh308c2a52010-05-14 11:30:18 +00001334static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001335 /* The following describes the implementation of the various locks and
1336 ** lock transitions in terms of the POSIX advisory shared and exclusive
1337 ** lock primitives (called read-locks and write-locks below, to avoid
1338 ** confusion with SQLite lock names). The algorithms are complicated
1339 ** slightly in order to be compatible with windows systems simultaneously
1340 ** accessing the same database file, in case that is ever required.
1341 **
1342 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1343 ** byte', each single bytes at well known offsets, and the 'shared byte
1344 ** range', a range of 510 bytes at a well known offset.
1345 **
1346 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1347 ** byte'. If this is successful, a random byte from the 'shared byte
1348 ** range' is read-locked and the lock on the 'pending byte' released.
1349 **
danielk197790ba3bd2004-06-25 08:32:25 +00001350 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1351 ** A RESERVED lock is implemented by grabbing a write-lock on the
1352 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001353 **
1354 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001355 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1356 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1357 ** obtained, but existing SHARED locks are allowed to persist. A process
1358 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1359 ** This property is used by the algorithm for rolling back a journal file
1360 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001361 **
danielk197790ba3bd2004-06-25 08:32:25 +00001362 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1363 ** implemented by obtaining a write-lock on the entire 'shared byte
1364 ** range'. Since all other locks require a read-lock on one of the bytes
1365 ** within this range, this ensures that no other locks are held on the
1366 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001367 **
1368 ** The reason a single byte cannot be used instead of the 'shared byte
1369 ** range' is that some versions of windows do not support read-locks. By
1370 ** locking a random byte from a range, concurrent SHARED locks may exist
1371 ** even if the locking primitive used is always a write-lock.
1372 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001373 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001374 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001375 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001376 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001377 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001378
drh054889e2005-11-30 03:20:31 +00001379 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001380 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1381 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001382 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001383
1384 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001385 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001386 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001387 */
drh308c2a52010-05-14 11:30:18 +00001388 if( pFile->eFileLock>=eFileLock ){
1389 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1390 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001391 return SQLITE_OK;
1392 }
1393
drh0c2694b2009-09-03 16:23:44 +00001394 /* Make sure the locking sequence is correct.
1395 ** (1) We never move from unlocked to anything higher than shared lock.
1396 ** (2) SQLite never explicitly requests a pendig lock.
1397 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001398 */
drh308c2a52010-05-14 11:30:18 +00001399 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1400 assert( eFileLock!=PENDING_LOCK );
1401 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001402
drh8af6c222010-05-14 12:43:01 +00001403 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001404 */
drh6c7d5c52008-11-21 20:32:33 +00001405 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001406 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001407
danielk1977ad94b582007-08-20 06:44:22 +00001408 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001409 ** handle that precludes the requested lock, return BUSY.
1410 */
drh8af6c222010-05-14 12:43:01 +00001411 if( (pFile->eFileLock!=pInode->eFileLock &&
1412 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001413 ){
1414 rc = SQLITE_BUSY;
1415 goto end_lock;
1416 }
1417
1418 /* If a SHARED lock is requested, and some thread using this PID already
1419 ** has a SHARED or RESERVED lock, then increment reference counts and
1420 ** return SQLITE_OK.
1421 */
drh308c2a52010-05-14 11:30:18 +00001422 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001423 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001424 assert( eFileLock==SHARED_LOCK );
1425 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001426 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001427 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001428 pInode->nShared++;
1429 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001430 goto end_lock;
1431 }
1432
danielk19779a1d0ab2004-06-01 14:09:28 +00001433
drh3cde3bb2004-06-12 02:17:14 +00001434 /* A PENDING lock is needed before acquiring a SHARED lock and before
1435 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1436 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001437 */
drh0c2694b2009-09-03 16:23:44 +00001438 lock.l_len = 1L;
1439 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001440 if( eFileLock==SHARED_LOCK
1441 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001442 ){
drh308c2a52010-05-14 11:30:18 +00001443 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001444 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001445 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001446 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001447 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001448 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001449 pFile->lastErrno = tErrno;
1450 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001451 goto end_lock;
1452 }
drh3cde3bb2004-06-12 02:17:14 +00001453 }
1454
1455
1456 /* If control gets to this point, then actually go ahead and make
1457 ** operating system calls for the specified lock.
1458 */
drh308c2a52010-05-14 11:30:18 +00001459 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001460 assert( pInode->nShared==0 );
1461 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001462 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001463
drh2ac3ee92004-06-07 16:27:46 +00001464 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001465 lock.l_start = SHARED_FIRST;
1466 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001467 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001468 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001469 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001470 }
dan661d71a2011-03-30 19:08:03 +00001471
drh2ac3ee92004-06-07 16:27:46 +00001472 /* Drop the temporary PENDING lock */
1473 lock.l_start = PENDING_BYTE;
1474 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001475 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001476 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1477 /* This could happen with a network mount */
1478 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001479 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001480 }
dan661d71a2011-03-30 19:08:03 +00001481
1482 if( rc ){
1483 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001484 pFile->lastErrno = tErrno;
1485 }
dan661d71a2011-03-30 19:08:03 +00001486 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001487 }else{
drh308c2a52010-05-14 11:30:18 +00001488 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001489 pInode->nLock++;
1490 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001491 }
drh8af6c222010-05-14 12:43:01 +00001492 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001493 /* We are trying for an exclusive lock but another thread in this
1494 ** same process is still holding a shared lock. */
1495 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001496 }else{
drh3cde3bb2004-06-12 02:17:14 +00001497 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001498 ** assumed that there is a SHARED or greater lock on the file
1499 ** already.
1500 */
drh308c2a52010-05-14 11:30:18 +00001501 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001502 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001503
1504 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1505 if( eFileLock==RESERVED_LOCK ){
1506 lock.l_start = RESERVED_BYTE;
1507 lock.l_len = 1L;
1508 }else{
1509 lock.l_start = SHARED_FIRST;
1510 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001511 }
dan661d71a2011-03-30 19:08:03 +00001512
1513 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001514 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001515 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001516 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001517 pFile->lastErrno = tErrno;
1518 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001519 }
drhbbd42a62004-05-22 17:41:58 +00001520 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001521
drh8f941bc2009-01-14 23:03:40 +00001522
1523#ifndef NDEBUG
1524 /* Set up the transaction-counter change checking flags when
1525 ** transitioning from a SHARED to a RESERVED lock. The change
1526 ** from SHARED to RESERVED marks the beginning of a normal
1527 ** write operation (not a hot journal rollback).
1528 */
1529 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001530 && pFile->eFileLock<=SHARED_LOCK
1531 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001532 ){
1533 pFile->transCntrChng = 0;
1534 pFile->dbUpdate = 0;
1535 pFile->inNormalWrite = 1;
1536 }
1537#endif
1538
1539
danielk1977ecb2a962004-06-02 06:30:16 +00001540 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001541 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001542 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001543 }else if( eFileLock==EXCLUSIVE_LOCK ){
1544 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001545 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001546 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001547
1548end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001549 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001550 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1551 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001552 return rc;
1553}
1554
1555/*
dan08da86a2009-08-21 17:18:03 +00001556** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001557** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001558*/
1559static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001560 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001561 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001562 p->pNext = pInode->pUnused;
1563 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001564 pFile->h = -1;
1565 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001566}
1567
1568/*
drh308c2a52010-05-14 11:30:18 +00001569** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001570** must be either NO_LOCK or SHARED_LOCK.
1571**
1572** If the locking level of the file descriptor is already at or below
1573** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001574**
1575** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1576** the byte range is divided into 2 parts and the first part is unlocked then
1577** set to a read lock, then the other part is simply unlocked. This works
1578** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1579** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001580*/
drha7e61d82011-03-12 17:02:57 +00001581static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001582 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001583 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001584 struct flock lock;
1585 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001586
drh054889e2005-11-30 03:20:31 +00001587 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001588 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001589 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001590 getpid()));
drha6abd042004-06-09 17:37:22 +00001591
drh308c2a52010-05-14 11:30:18 +00001592 assert( eFileLock<=SHARED_LOCK );
1593 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001594 return SQLITE_OK;
1595 }
drh6c7d5c52008-11-21 20:32:33 +00001596 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001597 pInode = pFile->pInode;
1598 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001599 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001600 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001601
1602#ifndef NDEBUG
1603 /* When reducing a lock such that other processes can start
1604 ** reading the database file again, make sure that the
1605 ** transaction counter was updated if any part of the database
1606 ** file changed. If the transaction counter is not updated,
1607 ** other connections to the same file might not realize that
1608 ** the file has changed and hence might not know to flush their
1609 ** cache. The use of a stale cache can lead to database corruption.
1610 */
drh8f941bc2009-01-14 23:03:40 +00001611 pFile->inNormalWrite = 0;
1612#endif
1613
drh7ed97b92010-01-20 13:07:21 +00001614 /* downgrading to a shared lock on NFS involves clearing the write lock
1615 ** before establishing the readlock - to avoid a race condition we downgrade
1616 ** the lock in 2 blocks, so that part of the range will be covered by a
1617 ** write lock until the rest is covered by a read lock:
1618 ** 1: [WWWWW]
1619 ** 2: [....W]
1620 ** 3: [RRRRW]
1621 ** 4: [RRRR.]
1622 */
drh308c2a52010-05-14 11:30:18 +00001623 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001624
1625#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001626 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001627 assert( handleNFSUnlock==0 );
1628#endif
1629#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001630 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001631 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001632 off_t divSize = SHARED_SIZE - 1;
1633
1634 lock.l_type = F_UNLCK;
1635 lock.l_whence = SEEK_SET;
1636 lock.l_start = SHARED_FIRST;
1637 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001638 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001639 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001640 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001641 if( IS_LOCK_ERROR(rc) ){
1642 pFile->lastErrno = tErrno;
1643 }
1644 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001645 }
drh7ed97b92010-01-20 13:07:21 +00001646 lock.l_type = F_RDLCK;
1647 lock.l_whence = SEEK_SET;
1648 lock.l_start = SHARED_FIRST;
1649 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001650 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001651 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001652 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1653 if( IS_LOCK_ERROR(rc) ){
1654 pFile->lastErrno = tErrno;
1655 }
1656 goto end_unlock;
1657 }
1658 lock.l_type = F_UNLCK;
1659 lock.l_whence = SEEK_SET;
1660 lock.l_start = SHARED_FIRST+divSize;
1661 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001662 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001663 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001664 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001665 if( IS_LOCK_ERROR(rc) ){
1666 pFile->lastErrno = tErrno;
1667 }
1668 goto end_unlock;
1669 }
drh30f776f2011-02-25 03:25:07 +00001670 }else
1671#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1672 {
drh7ed97b92010-01-20 13:07:21 +00001673 lock.l_type = F_RDLCK;
1674 lock.l_whence = SEEK_SET;
1675 lock.l_start = SHARED_FIRST;
1676 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001677 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001678 /* In theory, the call to unixFileLock() cannot fail because another
1679 ** process is holding an incompatible lock. If it does, this
1680 ** indicates that the other process is not following the locking
1681 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1682 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1683 ** an assert to fail). */
1684 rc = SQLITE_IOERR_RDLOCK;
1685 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001686 goto end_unlock;
1687 }
drh9c105bb2004-10-02 20:38:28 +00001688 }
1689 }
drhbbd42a62004-05-22 17:41:58 +00001690 lock.l_type = F_UNLCK;
1691 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001692 lock.l_start = PENDING_BYTE;
1693 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001694 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001695 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001696 }else{
danea83bc62011-04-01 11:56:32 +00001697 rc = SQLITE_IOERR_UNLOCK;
1698 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001699 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001700 }
drhbbd42a62004-05-22 17:41:58 +00001701 }
drh308c2a52010-05-14 11:30:18 +00001702 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001703 /* Decrement the shared lock counter. Release the lock using an
1704 ** OS call only when all threads in this same process have released
1705 ** the lock.
1706 */
drh8af6c222010-05-14 12:43:01 +00001707 pInode->nShared--;
1708 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001709 lock.l_type = F_UNLCK;
1710 lock.l_whence = SEEK_SET;
1711 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001712 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001713 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001714 }else{
danea83bc62011-04-01 11:56:32 +00001715 rc = SQLITE_IOERR_UNLOCK;
1716 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001717 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001718 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001719 }
drha6abd042004-06-09 17:37:22 +00001720 }
1721
drhbbd42a62004-05-22 17:41:58 +00001722 /* Decrement the count of locks against this same file. When the
1723 ** count reaches zero, close any other file descriptors whose close
1724 ** was deferred because of outstanding locks.
1725 */
drh8af6c222010-05-14 12:43:01 +00001726 pInode->nLock--;
1727 assert( pInode->nLock>=0 );
1728 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001729 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001730 }
1731 }
aswift5b1a2562008-08-22 00:22:35 +00001732
1733end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001735 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001736 return rc;
drhbbd42a62004-05-22 17:41:58 +00001737}
1738
1739/*
drh308c2a52010-05-14 11:30:18 +00001740** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001741** must be either NO_LOCK or SHARED_LOCK.
1742**
1743** If the locking level of the file descriptor is already at or below
1744** the requested locking level, this routine is a no-op.
1745*/
drh308c2a52010-05-14 11:30:18 +00001746static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001747 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001748}
1749
1750/*
danielk1977e339d652008-06-28 11:23:00 +00001751** This function performs the parts of the "close file" operation
1752** common to all locking schemes. It closes the directory and file
1753** handles, if they are valid, and sets all fields of the unixFile
1754** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001755**
1756** It is *not* necessary to hold the mutex when this routine is called,
1757** even on VxWorks. A mutex will be acquired on VxWorks by the
1758** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001759*/
1760static int closeUnixFile(sqlite3_file *id){
1761 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001762 if( pFile->h>=0 ){
1763 robust_close(pFile, pFile->h, __LINE__);
1764 pFile->h = -1;
1765 }
1766#if OS_VXWORKS
1767 if( pFile->pId ){
1768 if( pFile->isDelete ){
drh036ac7f2011-08-08 23:18:05 +00001769 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001770 }
1771 vxworksReleaseFileId(pFile->pId);
1772 pFile->pId = 0;
1773 }
1774#endif
1775 OSTRACE(("CLOSE %-3d\n", pFile->h));
1776 OpenCounter(-1);
1777 sqlite3_free(pFile->pUnused);
1778 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001779 return SQLITE_OK;
1780}
1781
1782/*
danielk1977e3026632004-06-22 11:29:02 +00001783** Close a file.
1784*/
danielk197762079062007-08-15 17:08:46 +00001785static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001786 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001787 unixFile *pFile = (unixFile *)id;
1788 unixUnlock(id, NO_LOCK);
1789 unixEnterMutex();
1790
1791 /* unixFile.pInode is always valid here. Otherwise, a different close
1792 ** routine (e.g. nolockClose()) would be called instead.
1793 */
1794 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1795 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1796 /* If there are outstanding locks, do not actually close the file just
1797 ** yet because that would clear those locks. Instead, add the file
1798 ** descriptor to pInode->pUnused list. It will be automatically closed
1799 ** when the last lock is cleared.
1800 */
1801 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001802 }
dan661d71a2011-03-30 19:08:03 +00001803 releaseInodeInfo(pFile);
1804 rc = closeUnixFile(id);
1805 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001806 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001807}
1808
drh734c9862008-11-28 15:37:20 +00001809/************** End of the posix advisory lock implementation *****************
1810******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001811
drh734c9862008-11-28 15:37:20 +00001812/******************************************************************************
1813****************************** No-op Locking **********************************
1814**
1815** Of the various locking implementations available, this is by far the
1816** simplest: locking is ignored. No attempt is made to lock the database
1817** file for reading or writing.
1818**
1819** This locking mode is appropriate for use on read-only databases
1820** (ex: databases that are burned into CD-ROM, for example.) It can
1821** also be used if the application employs some external mechanism to
1822** prevent simultaneous access of the same database by two or more
1823** database connections. But there is a serious risk of database
1824** corruption if this locking mode is used in situations where multiple
1825** database connections are accessing the same database file at the same
1826** time and one or more of those connections are writing.
1827*/
drhbfe66312006-10-03 17:40:40 +00001828
drh734c9862008-11-28 15:37:20 +00001829static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1830 UNUSED_PARAMETER(NotUsed);
1831 *pResOut = 0;
1832 return SQLITE_OK;
1833}
drh734c9862008-11-28 15:37:20 +00001834static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1835 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1836 return SQLITE_OK;
1837}
drh734c9862008-11-28 15:37:20 +00001838static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1839 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1840 return SQLITE_OK;
1841}
1842
1843/*
drh9b35ea62008-11-29 02:20:26 +00001844** Close the file.
drh734c9862008-11-28 15:37:20 +00001845*/
1846static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001847 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001848}
1849
1850/******************* End of the no-op lock implementation *********************
1851******************************************************************************/
1852
1853/******************************************************************************
1854************************* Begin dot-file Locking ******************************
1855**
drh0c2694b2009-09-03 16:23:44 +00001856** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001857** files (really a directory) to control access to the database. This works
1858** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001859**
1860** (1) There is zero concurrency. A single reader blocks all other
1861** connections from reading or writing the database.
1862**
1863** (2) An application crash or power loss can leave stale lock files
1864** sitting around that need to be cleared manually.
1865**
1866** Nevertheless, a dotlock is an appropriate locking mode for use if no
1867** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001868**
drh9ef6bc42011-11-04 02:24:02 +00001869** Dotfile locking works by creating a subdirectory in the same directory as
1870** the database and with the same name but with a ".lock" extension added.
1871** The existance of a lock directory implies an EXCLUSIVE lock. All other
1872** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001873*/
1874
1875/*
1876** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001877** lock directory.
drh734c9862008-11-28 15:37:20 +00001878*/
1879#define DOTLOCK_SUFFIX ".lock"
1880
drh7708e972008-11-29 00:56:52 +00001881/*
1882** This routine checks if there is a RESERVED lock held on the specified
1883** file by this or any other process. If such a lock is held, set *pResOut
1884** to a non-zero value otherwise *pResOut is set to zero. The return value
1885** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1886**
1887** In dotfile locking, either a lock exists or it does not. So in this
1888** variation of CheckReservedLock(), *pResOut is set to true if any lock
1889** is held on the file and false if the file is unlocked.
1890*/
drh734c9862008-11-28 15:37:20 +00001891static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1892 int rc = SQLITE_OK;
1893 int reserved = 0;
1894 unixFile *pFile = (unixFile*)id;
1895
1896 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1897
1898 assert( pFile );
1899
1900 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001901 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001902 /* Either this connection or some other connection in the same process
1903 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001904 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001905 }else{
1906 /* The lock is held if and only if the lockfile exists */
1907 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001908 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001909 }
drh308c2a52010-05-14 11:30:18 +00001910 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001911 *pResOut = reserved;
1912 return rc;
1913}
1914
drh7708e972008-11-29 00:56:52 +00001915/*
drh308c2a52010-05-14 11:30:18 +00001916** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001917** of the following:
1918**
1919** (1) SHARED_LOCK
1920** (2) RESERVED_LOCK
1921** (3) PENDING_LOCK
1922** (4) EXCLUSIVE_LOCK
1923**
1924** Sometimes when requesting one lock state, additional lock states
1925** are inserted in between. The locking might fail on one of the later
1926** transitions leaving the lock state different from what it started but
1927** still short of its goal. The following chart shows the allowed
1928** transitions and the inserted intermediate states:
1929**
1930** UNLOCKED -> SHARED
1931** SHARED -> RESERVED
1932** SHARED -> (PENDING) -> EXCLUSIVE
1933** RESERVED -> (PENDING) -> EXCLUSIVE
1934** PENDING -> EXCLUSIVE
1935**
1936** This routine will only increase a lock. Use the sqlite3OsUnlock()
1937** routine to lower a locking level.
1938**
1939** With dotfile locking, we really only support state (4): EXCLUSIVE.
1940** But we track the other locking levels internally.
1941*/
drh308c2a52010-05-14 11:30:18 +00001942static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001943 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001944 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001945 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001946
drh7708e972008-11-29 00:56:52 +00001947
1948 /* If we have any lock, then the lock file already exists. All we have
1949 ** to do is adjust our internal record of the lock level.
1950 */
drh308c2a52010-05-14 11:30:18 +00001951 if( pFile->eFileLock > NO_LOCK ){
1952 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001953 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001954#ifdef HAVE_UTIME
1955 utime(zLockFile, NULL);
1956#else
drh734c9862008-11-28 15:37:20 +00001957 utimes(zLockFile, NULL);
1958#endif
drh7708e972008-11-29 00:56:52 +00001959 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001960 }
1961
1962 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001963 rc = osMkdir(zLockFile, 0777);
1964 if( rc<0 ){
1965 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001966 int tErrno = errno;
1967 if( EEXIST == tErrno ){
1968 rc = SQLITE_BUSY;
1969 } else {
1970 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1971 if( IS_LOCK_ERROR(rc) ){
1972 pFile->lastErrno = tErrno;
1973 }
1974 }
drh7708e972008-11-29 00:56:52 +00001975 return rc;
drh734c9862008-11-28 15:37:20 +00001976 }
drh734c9862008-11-28 15:37:20 +00001977
1978 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001979 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001980 return rc;
1981}
1982
drh7708e972008-11-29 00:56:52 +00001983/*
drh308c2a52010-05-14 11:30:18 +00001984** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001985** must be either NO_LOCK or SHARED_LOCK.
1986**
1987** If the locking level of the file descriptor is already at or below
1988** the requested locking level, this routine is a no-op.
1989**
1990** When the locking level reaches NO_LOCK, delete the lock file.
1991*/
drh308c2a52010-05-14 11:30:18 +00001992static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001993 unixFile *pFile = (unixFile*)id;
1994 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00001995 int rc;
drh734c9862008-11-28 15:37:20 +00001996
1997 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001998 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1999 pFile->eFileLock, getpid()));
2000 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002001
2002 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002003 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002004 return SQLITE_OK;
2005 }
drh7708e972008-11-29 00:56:52 +00002006
2007 /* To downgrade to shared, simply update our internal notion of the
2008 ** lock state. No need to mess with the file on disk.
2009 */
drh308c2a52010-05-14 11:30:18 +00002010 if( eFileLock==SHARED_LOCK ){
2011 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002012 return SQLITE_OK;
2013 }
2014
drh7708e972008-11-29 00:56:52 +00002015 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002016 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002017 rc = osRmdir(zLockFile);
2018 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2019 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002020 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002021 rc = 0;
drh734c9862008-11-28 15:37:20 +00002022 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002023 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002024 }
2025 if( IS_LOCK_ERROR(rc) ){
2026 pFile->lastErrno = tErrno;
2027 }
2028 return rc;
2029 }
drh308c2a52010-05-14 11:30:18 +00002030 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002031 return SQLITE_OK;
2032}
2033
2034/*
drh9b35ea62008-11-29 02:20:26 +00002035** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002036*/
2037static int dotlockClose(sqlite3_file *id) {
2038 int rc;
2039 if( id ){
2040 unixFile *pFile = (unixFile*)id;
2041 dotlockUnlock(id, NO_LOCK);
2042 sqlite3_free(pFile->lockingContext);
2043 }
drh734c9862008-11-28 15:37:20 +00002044 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002045 return rc;
2046}
2047/****************** End of the dot-file lock implementation *******************
2048******************************************************************************/
2049
2050/******************************************************************************
2051************************** Begin flock Locking ********************************
2052**
2053** Use the flock() system call to do file locking.
2054**
drh6b9d6dd2008-12-03 19:34:47 +00002055** flock() locking is like dot-file locking in that the various
2056** fine-grain locking levels supported by SQLite are collapsed into
2057** a single exclusive lock. In other words, SHARED, RESERVED, and
2058** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2059** still works when you do this, but concurrency is reduced since
2060** only a single process can be reading the database at a time.
2061**
drh734c9862008-11-28 15:37:20 +00002062** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2063** compiling for VXWORKS.
2064*/
2065#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002066
drh6b9d6dd2008-12-03 19:34:47 +00002067/*
drhff812312011-02-23 13:33:46 +00002068** Retry flock() calls that fail with EINTR
2069*/
2070#ifdef EINTR
2071static int robust_flock(int fd, int op){
2072 int rc;
2073 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2074 return rc;
2075}
2076#else
drh5c819272011-02-23 14:00:12 +00002077# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002078#endif
2079
2080
2081/*
drh6b9d6dd2008-12-03 19:34:47 +00002082** This routine checks if there is a RESERVED lock held on the specified
2083** file by this or any other process. If such a lock is held, set *pResOut
2084** to a non-zero value otherwise *pResOut is set to zero. The return value
2085** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2086*/
drh734c9862008-11-28 15:37:20 +00002087static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2088 int rc = SQLITE_OK;
2089 int reserved = 0;
2090 unixFile *pFile = (unixFile*)id;
2091
2092 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2093
2094 assert( pFile );
2095
2096 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002097 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002098 reserved = 1;
2099 }
2100
2101 /* Otherwise see if some other process holds it. */
2102 if( !reserved ){
2103 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002104 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002105 if( !lrc ){
2106 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002107 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002108 if ( lrc ) {
2109 int tErrno = errno;
2110 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002111 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002112 if( IS_LOCK_ERROR(lrc) ){
2113 pFile->lastErrno = tErrno;
2114 rc = lrc;
2115 }
2116 }
2117 } else {
2118 int tErrno = errno;
2119 reserved = 1;
2120 /* someone else might have it reserved */
2121 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2122 if( IS_LOCK_ERROR(lrc) ){
2123 pFile->lastErrno = tErrno;
2124 rc = lrc;
2125 }
2126 }
2127 }
drh308c2a52010-05-14 11:30:18 +00002128 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002129
2130#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2131 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2132 rc = SQLITE_OK;
2133 reserved=1;
2134 }
2135#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2136 *pResOut = reserved;
2137 return rc;
2138}
2139
drh6b9d6dd2008-12-03 19:34:47 +00002140/*
drh308c2a52010-05-14 11:30:18 +00002141** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002142** of the following:
2143**
2144** (1) SHARED_LOCK
2145** (2) RESERVED_LOCK
2146** (3) PENDING_LOCK
2147** (4) EXCLUSIVE_LOCK
2148**
2149** Sometimes when requesting one lock state, additional lock states
2150** are inserted in between. The locking might fail on one of the later
2151** transitions leaving the lock state different from what it started but
2152** still short of its goal. The following chart shows the allowed
2153** transitions and the inserted intermediate states:
2154**
2155** UNLOCKED -> SHARED
2156** SHARED -> RESERVED
2157** SHARED -> (PENDING) -> EXCLUSIVE
2158** RESERVED -> (PENDING) -> EXCLUSIVE
2159** PENDING -> EXCLUSIVE
2160**
2161** flock() only really support EXCLUSIVE locks. We track intermediate
2162** lock states in the sqlite3_file structure, but all locks SHARED or
2163** above are really EXCLUSIVE locks and exclude all other processes from
2164** access the file.
2165**
2166** This routine will only increase a lock. Use the sqlite3OsUnlock()
2167** routine to lower a locking level.
2168*/
drh308c2a52010-05-14 11:30:18 +00002169static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002170 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002171 unixFile *pFile = (unixFile*)id;
2172
2173 assert( pFile );
2174
2175 /* if we already have a lock, it is exclusive.
2176 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002177 if (pFile->eFileLock > NO_LOCK) {
2178 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002179 return SQLITE_OK;
2180 }
2181
2182 /* grab an exclusive lock */
2183
drhff812312011-02-23 13:33:46 +00002184 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002185 int tErrno = errno;
2186 /* didn't get, must be busy */
2187 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2188 if( IS_LOCK_ERROR(rc) ){
2189 pFile->lastErrno = tErrno;
2190 }
2191 } else {
2192 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002193 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002194 }
drh308c2a52010-05-14 11:30:18 +00002195 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2196 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002197#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2198 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2199 rc = SQLITE_BUSY;
2200 }
2201#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2202 return rc;
2203}
2204
drh6b9d6dd2008-12-03 19:34:47 +00002205
2206/*
drh308c2a52010-05-14 11:30:18 +00002207** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002208** must be either NO_LOCK or SHARED_LOCK.
2209**
2210** If the locking level of the file descriptor is already at or below
2211** the requested locking level, this routine is a no-op.
2212*/
drh308c2a52010-05-14 11:30:18 +00002213static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002214 unixFile *pFile = (unixFile*)id;
2215
2216 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002217 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2218 pFile->eFileLock, getpid()));
2219 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002220
2221 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002222 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002223 return SQLITE_OK;
2224 }
2225
2226 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002227 if (eFileLock==SHARED_LOCK) {
2228 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002229 return SQLITE_OK;
2230 }
2231
2232 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002233 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002234#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002235 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002236#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002237 return SQLITE_IOERR_UNLOCK;
2238 }else{
drh308c2a52010-05-14 11:30:18 +00002239 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002240 return SQLITE_OK;
2241 }
2242}
2243
2244/*
2245** Close a file.
2246*/
2247static int flockClose(sqlite3_file *id) {
2248 if( id ){
2249 flockUnlock(id, NO_LOCK);
2250 }
2251 return closeUnixFile(id);
2252}
2253
2254#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2255
2256/******************* End of the flock lock implementation *********************
2257******************************************************************************/
2258
2259/******************************************************************************
2260************************ Begin Named Semaphore Locking ************************
2261**
2262** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002263**
2264** Semaphore locking is like dot-lock and flock in that it really only
2265** supports EXCLUSIVE locking. Only a single process can read or write
2266** the database file at a time. This reduces potential concurrency, but
2267** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002268*/
2269#if OS_VXWORKS
2270
drh6b9d6dd2008-12-03 19:34:47 +00002271/*
2272** This routine checks if there is a RESERVED lock held on the specified
2273** file by this or any other process. If such a lock is held, set *pResOut
2274** to a non-zero value otherwise *pResOut is set to zero. The return value
2275** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2276*/
drh734c9862008-11-28 15:37:20 +00002277static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2278 int rc = SQLITE_OK;
2279 int reserved = 0;
2280 unixFile *pFile = (unixFile*)id;
2281
2282 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2283
2284 assert( pFile );
2285
2286 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002287 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002288 reserved = 1;
2289 }
2290
2291 /* Otherwise see if some other process holds it. */
2292 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002293 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002294 struct stat statBuf;
2295
2296 if( sem_trywait(pSem)==-1 ){
2297 int tErrno = errno;
2298 if( EAGAIN != tErrno ){
2299 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2300 pFile->lastErrno = tErrno;
2301 } else {
2302 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002303 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002304 }
2305 }else{
2306 /* we could have it if we want it */
2307 sem_post(pSem);
2308 }
2309 }
drh308c2a52010-05-14 11:30:18 +00002310 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002311
2312 *pResOut = reserved;
2313 return rc;
2314}
2315
drh6b9d6dd2008-12-03 19:34:47 +00002316/*
drh308c2a52010-05-14 11:30:18 +00002317** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002318** of the following:
2319**
2320** (1) SHARED_LOCK
2321** (2) RESERVED_LOCK
2322** (3) PENDING_LOCK
2323** (4) EXCLUSIVE_LOCK
2324**
2325** Sometimes when requesting one lock state, additional lock states
2326** are inserted in between. The locking might fail on one of the later
2327** transitions leaving the lock state different from what it started but
2328** still short of its goal. The following chart shows the allowed
2329** transitions and the inserted intermediate states:
2330**
2331** UNLOCKED -> SHARED
2332** SHARED -> RESERVED
2333** SHARED -> (PENDING) -> EXCLUSIVE
2334** RESERVED -> (PENDING) -> EXCLUSIVE
2335** PENDING -> EXCLUSIVE
2336**
2337** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2338** lock states in the sqlite3_file structure, but all locks SHARED or
2339** above are really EXCLUSIVE locks and exclude all other processes from
2340** access the file.
2341**
2342** This routine will only increase a lock. Use the sqlite3OsUnlock()
2343** routine to lower a locking level.
2344*/
drh308c2a52010-05-14 11:30:18 +00002345static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002346 unixFile *pFile = (unixFile*)id;
2347 int fd;
drh8af6c222010-05-14 12:43:01 +00002348 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002349 int rc = SQLITE_OK;
2350
2351 /* if we already have a lock, it is exclusive.
2352 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002353 if (pFile->eFileLock > NO_LOCK) {
2354 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002355 rc = SQLITE_OK;
2356 goto sem_end_lock;
2357 }
2358
2359 /* lock semaphore now but bail out when already locked. */
2360 if( sem_trywait(pSem)==-1 ){
2361 rc = SQLITE_BUSY;
2362 goto sem_end_lock;
2363 }
2364
2365 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002366 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002367
2368 sem_end_lock:
2369 return rc;
2370}
2371
drh6b9d6dd2008-12-03 19:34:47 +00002372/*
drh308c2a52010-05-14 11:30:18 +00002373** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002374** must be either NO_LOCK or SHARED_LOCK.
2375**
2376** If the locking level of the file descriptor is already at or below
2377** the requested locking level, this routine is a no-op.
2378*/
drh308c2a52010-05-14 11:30:18 +00002379static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002380 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002381 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002382
2383 assert( pFile );
2384 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002385 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2386 pFile->eFileLock, getpid()));
2387 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002388
2389 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002390 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002391 return SQLITE_OK;
2392 }
2393
2394 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002395 if (eFileLock==SHARED_LOCK) {
2396 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002397 return SQLITE_OK;
2398 }
2399
2400 /* no, really unlock. */
2401 if ( sem_post(pSem)==-1 ) {
2402 int rc, tErrno = errno;
2403 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2404 if( IS_LOCK_ERROR(rc) ){
2405 pFile->lastErrno = tErrno;
2406 }
2407 return rc;
2408 }
drh308c2a52010-05-14 11:30:18 +00002409 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002410 return SQLITE_OK;
2411}
2412
2413/*
2414 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002415 */
drh734c9862008-11-28 15:37:20 +00002416static int semClose(sqlite3_file *id) {
2417 if( id ){
2418 unixFile *pFile = (unixFile*)id;
2419 semUnlock(id, NO_LOCK);
2420 assert( pFile );
2421 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002422 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002423 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002424 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002425 }
2426 return SQLITE_OK;
2427}
2428
2429#endif /* OS_VXWORKS */
2430/*
2431** Named semaphore locking is only available on VxWorks.
2432**
2433*************** End of the named semaphore lock implementation ****************
2434******************************************************************************/
2435
2436
2437/******************************************************************************
2438*************************** Begin AFP Locking *********************************
2439**
2440** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2441** on Apple Macintosh computers - both OS9 and OSX.
2442**
2443** Third-party implementations of AFP are available. But this code here
2444** only works on OSX.
2445*/
2446
drhd2cb50b2009-01-09 21:41:17 +00002447#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002448/*
2449** The afpLockingContext structure contains all afp lock specific state
2450*/
drhbfe66312006-10-03 17:40:40 +00002451typedef struct afpLockingContext afpLockingContext;
2452struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002453 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002454 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002455};
2456
2457struct ByteRangeLockPB2
2458{
2459 unsigned long long offset; /* offset to first byte to lock */
2460 unsigned long long length; /* nbr of bytes to lock */
2461 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2462 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2463 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2464 int fd; /* file desc to assoc this lock with */
2465};
2466
drhfd131da2007-08-07 17:13:03 +00002467#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002468
drh6b9d6dd2008-12-03 19:34:47 +00002469/*
2470** This is a utility for setting or clearing a bit-range lock on an
2471** AFP filesystem.
2472**
2473** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2474*/
2475static int afpSetLock(
2476 const char *path, /* Name of the file to be locked or unlocked */
2477 unixFile *pFile, /* Open file descriptor on path */
2478 unsigned long long offset, /* First byte to be locked */
2479 unsigned long long length, /* Number of bytes to lock */
2480 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002481){
drh6b9d6dd2008-12-03 19:34:47 +00002482 struct ByteRangeLockPB2 pb;
2483 int err;
drhbfe66312006-10-03 17:40:40 +00002484
2485 pb.unLockFlag = setLockFlag ? 0 : 1;
2486 pb.startEndFlag = 0;
2487 pb.offset = offset;
2488 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002489 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002490
drh308c2a52010-05-14 11:30:18 +00002491 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002492 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002493 offset, length));
drhbfe66312006-10-03 17:40:40 +00002494 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2495 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002496 int rc;
2497 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002498 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2499 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002500#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2501 rc = SQLITE_BUSY;
2502#else
drh734c9862008-11-28 15:37:20 +00002503 rc = sqliteErrorFromPosixError(tErrno,
2504 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002505#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002506 if( IS_LOCK_ERROR(rc) ){
2507 pFile->lastErrno = tErrno;
2508 }
2509 return rc;
drhbfe66312006-10-03 17:40:40 +00002510 } else {
aswift5b1a2562008-08-22 00:22:35 +00002511 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002512 }
2513}
2514
drh6b9d6dd2008-12-03 19:34:47 +00002515/*
2516** This routine checks if there is a RESERVED lock held on the specified
2517** file by this or any other process. If such a lock is held, set *pResOut
2518** to a non-zero value otherwise *pResOut is set to zero. The return value
2519** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2520*/
danielk1977e339d652008-06-28 11:23:00 +00002521static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002522 int rc = SQLITE_OK;
2523 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002524 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002525 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002526
aswift5b1a2562008-08-22 00:22:35 +00002527 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2528
2529 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002530 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002531 if( context->reserved ){
2532 *pResOut = 1;
2533 return SQLITE_OK;
2534 }
drh8af6c222010-05-14 12:43:01 +00002535 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002536
2537 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002538 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002539 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002540 }
2541
2542 /* Otherwise see if some other process holds it.
2543 */
aswift5b1a2562008-08-22 00:22:35 +00002544 if( !reserved ){
2545 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002546 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002547 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002548 /* if we succeeded in taking the reserved lock, unlock it to restore
2549 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002550 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002551 } else {
2552 /* if we failed to get the lock then someone else must have it */
2553 reserved = 1;
2554 }
2555 if( IS_LOCK_ERROR(lrc) ){
2556 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002557 }
2558 }
drhbfe66312006-10-03 17:40:40 +00002559
drh7ed97b92010-01-20 13:07:21 +00002560 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002561 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002562
2563 *pResOut = reserved;
2564 return rc;
drhbfe66312006-10-03 17:40:40 +00002565}
2566
drh6b9d6dd2008-12-03 19:34:47 +00002567/*
drh308c2a52010-05-14 11:30:18 +00002568** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002569** of the following:
2570**
2571** (1) SHARED_LOCK
2572** (2) RESERVED_LOCK
2573** (3) PENDING_LOCK
2574** (4) EXCLUSIVE_LOCK
2575**
2576** Sometimes when requesting one lock state, additional lock states
2577** are inserted in between. The locking might fail on one of the later
2578** transitions leaving the lock state different from what it started but
2579** still short of its goal. The following chart shows the allowed
2580** transitions and the inserted intermediate states:
2581**
2582** UNLOCKED -> SHARED
2583** SHARED -> RESERVED
2584** SHARED -> (PENDING) -> EXCLUSIVE
2585** RESERVED -> (PENDING) -> EXCLUSIVE
2586** PENDING -> EXCLUSIVE
2587**
2588** This routine will only increase a lock. Use the sqlite3OsUnlock()
2589** routine to lower a locking level.
2590*/
drh308c2a52010-05-14 11:30:18 +00002591static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002592 int rc = SQLITE_OK;
2593 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002594 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002595 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002596
2597 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002598 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2599 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002600 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002601
drhbfe66312006-10-03 17:40:40 +00002602 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002603 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002604 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002605 */
drh308c2a52010-05-14 11:30:18 +00002606 if( pFile->eFileLock>=eFileLock ){
2607 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2608 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002609 return SQLITE_OK;
2610 }
2611
2612 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002613 ** (1) We never move from unlocked to anything higher than shared lock.
2614 ** (2) SQLite never explicitly requests a pendig lock.
2615 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002616 */
drh308c2a52010-05-14 11:30:18 +00002617 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2618 assert( eFileLock!=PENDING_LOCK );
2619 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002620
drh8af6c222010-05-14 12:43:01 +00002621 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002622 */
drh6c7d5c52008-11-21 20:32:33 +00002623 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002624 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002625
2626 /* If some thread using this PID has a lock via a different unixFile*
2627 ** handle that precludes the requested lock, return BUSY.
2628 */
drh8af6c222010-05-14 12:43:01 +00002629 if( (pFile->eFileLock!=pInode->eFileLock &&
2630 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002631 ){
2632 rc = SQLITE_BUSY;
2633 goto afp_end_lock;
2634 }
2635
2636 /* If a SHARED lock is requested, and some thread using this PID already
2637 ** has a SHARED or RESERVED lock, then increment reference counts and
2638 ** return SQLITE_OK.
2639 */
drh308c2a52010-05-14 11:30:18 +00002640 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002641 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002642 assert( eFileLock==SHARED_LOCK );
2643 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002644 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002645 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002646 pInode->nShared++;
2647 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002648 goto afp_end_lock;
2649 }
drhbfe66312006-10-03 17:40:40 +00002650
2651 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002652 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2653 ** be released.
2654 */
drh308c2a52010-05-14 11:30:18 +00002655 if( eFileLock==SHARED_LOCK
2656 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002657 ){
2658 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002659 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002660 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002661 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002662 goto afp_end_lock;
2663 }
2664 }
2665
2666 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002667 ** operating system calls for the specified lock.
2668 */
drh308c2a52010-05-14 11:30:18 +00002669 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002670 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002671 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002672
drh8af6c222010-05-14 12:43:01 +00002673 assert( pInode->nShared==0 );
2674 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002675
2676 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002677 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002678 /* note that the quality of the randomness doesn't matter that much */
2679 lk = random();
drh8af6c222010-05-14 12:43:01 +00002680 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002681 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002682 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002683 if( IS_LOCK_ERROR(lrc1) ){
2684 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002685 }
aswift5b1a2562008-08-22 00:22:35 +00002686 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002687 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002688
aswift5b1a2562008-08-22 00:22:35 +00002689 if( IS_LOCK_ERROR(lrc1) ) {
2690 pFile->lastErrno = lrc1Errno;
2691 rc = lrc1;
2692 goto afp_end_lock;
2693 } else if( IS_LOCK_ERROR(lrc2) ){
2694 rc = lrc2;
2695 goto afp_end_lock;
2696 } else if( lrc1 != SQLITE_OK ) {
2697 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002698 } else {
drh308c2a52010-05-14 11:30:18 +00002699 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002700 pInode->nLock++;
2701 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002702 }
drh8af6c222010-05-14 12:43:01 +00002703 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002704 /* We are trying for an exclusive lock but another thread in this
2705 ** same process is still holding a shared lock. */
2706 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002707 }else{
2708 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2709 ** assumed that there is a SHARED or greater lock on the file
2710 ** already.
2711 */
2712 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002713 assert( 0!=pFile->eFileLock );
2714 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002715 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002716 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002717 if( !failed ){
2718 context->reserved = 1;
2719 }
drhbfe66312006-10-03 17:40:40 +00002720 }
drh308c2a52010-05-14 11:30:18 +00002721 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002722 /* Acquire an EXCLUSIVE lock */
2723
2724 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002725 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002726 */
drh6b9d6dd2008-12-03 19:34:47 +00002727 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002728 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002729 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002730 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002731 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002732 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002733 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002734 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002735 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2736 ** a critical I/O error
2737 */
2738 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2739 SQLITE_IOERR_LOCK;
2740 goto afp_end_lock;
2741 }
2742 }else{
aswift5b1a2562008-08-22 00:22:35 +00002743 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002744 }
2745 }
aswift5b1a2562008-08-22 00:22:35 +00002746 if( failed ){
2747 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002748 }
2749 }
2750
2751 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002752 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002753 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002754 }else if( eFileLock==EXCLUSIVE_LOCK ){
2755 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002756 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002757 }
2758
2759afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002760 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002761 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2762 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002763 return rc;
2764}
2765
2766/*
drh308c2a52010-05-14 11:30:18 +00002767** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002768** must be either NO_LOCK or SHARED_LOCK.
2769**
2770** If the locking level of the file descriptor is already at or below
2771** the requested locking level, this routine is a no-op.
2772*/
drh308c2a52010-05-14 11:30:18 +00002773static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002774 int rc = SQLITE_OK;
2775 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002776 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002777 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2778 int skipShared = 0;
2779#ifdef SQLITE_TEST
2780 int h = pFile->h;
2781#endif
drhbfe66312006-10-03 17:40:40 +00002782
2783 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002784 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002785 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002786 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002787
drh308c2a52010-05-14 11:30:18 +00002788 assert( eFileLock<=SHARED_LOCK );
2789 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002790 return SQLITE_OK;
2791 }
drh6c7d5c52008-11-21 20:32:33 +00002792 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002793 pInode = pFile->pInode;
2794 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002795 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002796 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002797 SimulateIOErrorBenign(1);
2798 SimulateIOError( h=(-1) )
2799 SimulateIOErrorBenign(0);
2800
2801#ifndef NDEBUG
2802 /* When reducing a lock such that other processes can start
2803 ** reading the database file again, make sure that the
2804 ** transaction counter was updated if any part of the database
2805 ** file changed. If the transaction counter is not updated,
2806 ** other connections to the same file might not realize that
2807 ** the file has changed and hence might not know to flush their
2808 ** cache. The use of a stale cache can lead to database corruption.
2809 */
2810 assert( pFile->inNormalWrite==0
2811 || pFile->dbUpdate==0
2812 || pFile->transCntrChng==1 );
2813 pFile->inNormalWrite = 0;
2814#endif
aswiftaebf4132008-11-21 00:10:35 +00002815
drh308c2a52010-05-14 11:30:18 +00002816 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002817 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002818 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002819 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002820 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002821 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2822 } else {
2823 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002824 }
2825 }
drh308c2a52010-05-14 11:30:18 +00002826 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002827 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002828 }
drh308c2a52010-05-14 11:30:18 +00002829 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002830 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2831 if( !rc ){
2832 context->reserved = 0;
2833 }
aswiftaebf4132008-11-21 00:10:35 +00002834 }
drh8af6c222010-05-14 12:43:01 +00002835 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2836 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002837 }
aswiftaebf4132008-11-21 00:10:35 +00002838 }
drh308c2a52010-05-14 11:30:18 +00002839 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002840
drh7ed97b92010-01-20 13:07:21 +00002841 /* Decrement the shared lock counter. Release the lock using an
2842 ** OS call only when all threads in this same process have released
2843 ** the lock.
2844 */
drh8af6c222010-05-14 12:43:01 +00002845 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2846 pInode->nShared--;
2847 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002848 SimulateIOErrorBenign(1);
2849 SimulateIOError( h=(-1) )
2850 SimulateIOErrorBenign(0);
2851 if( !skipShared ){
2852 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2853 }
2854 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002855 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002856 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002857 }
2858 }
2859 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002860 pInode->nLock--;
2861 assert( pInode->nLock>=0 );
2862 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002863 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002864 }
2865 }
drhbfe66312006-10-03 17:40:40 +00002866 }
drh7ed97b92010-01-20 13:07:21 +00002867
drh6c7d5c52008-11-21 20:32:33 +00002868 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002869 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002870 return rc;
2871}
2872
2873/*
drh339eb0b2008-03-07 15:34:11 +00002874** Close a file & cleanup AFP specific locking context
2875*/
danielk1977e339d652008-06-28 11:23:00 +00002876static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002877 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002878 if( id ){
2879 unixFile *pFile = (unixFile*)id;
2880 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002881 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002882 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002883 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002884 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002885 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002886 ** the last lock is cleared.
2887 */
dan08da86a2009-08-21 17:18:03 +00002888 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002889 }
danb0ac3e32010-06-16 10:55:42 +00002890 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002891 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002892 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002893 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002894 }
drh7ed97b92010-01-20 13:07:21 +00002895 return rc;
drhbfe66312006-10-03 17:40:40 +00002896}
2897
drhd2cb50b2009-01-09 21:41:17 +00002898#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002899/*
2900** The code above is the AFP lock implementation. The code is specific
2901** to MacOSX and does not work on other unix platforms. No alternative
2902** is available. If you don't compile for a mac, then the "unix-afp"
2903** VFS is not available.
2904**
2905********************* End of the AFP lock implementation **********************
2906******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002907
drh7ed97b92010-01-20 13:07:21 +00002908/******************************************************************************
2909*************************** Begin NFS Locking ********************************/
2910
2911#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2912/*
drh308c2a52010-05-14 11:30:18 +00002913 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002914 ** must be either NO_LOCK or SHARED_LOCK.
2915 **
2916 ** If the locking level of the file descriptor is already at or below
2917 ** the requested locking level, this routine is a no-op.
2918 */
drh308c2a52010-05-14 11:30:18 +00002919static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002920 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002921}
2922
2923#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2924/*
2925** The code above is the NFS lock implementation. The code is specific
2926** to MacOSX and does not work on other unix platforms. No alternative
2927** is available.
2928**
2929********************* End of the NFS lock implementation **********************
2930******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002931
2932/******************************************************************************
2933**************** Non-locking sqlite3_file methods *****************************
2934**
2935** The next division contains implementations for all methods of the
2936** sqlite3_file object other than the locking methods. The locking
2937** methods were defined in divisions above (one locking method per
2938** division). Those methods that are common to all locking modes
2939** are gather together into this division.
2940*/
drhbfe66312006-10-03 17:40:40 +00002941
2942/*
drh734c9862008-11-28 15:37:20 +00002943** Seek to the offset passed as the second argument, then read cnt
2944** bytes into pBuf. Return the number of bytes actually read.
2945**
2946** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2947** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2948** one system to another. Since SQLite does not define USE_PREAD
2949** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2950** See tickets #2741 and #2681.
2951**
2952** To avoid stomping the errno value on a failed read the lastErrno value
2953** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002954*/
drh734c9862008-11-28 15:37:20 +00002955static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2956 int got;
drh58024642011-11-07 18:16:00 +00002957 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002958#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002959 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002960#endif
drh734c9862008-11-28 15:37:20 +00002961 TIMER_START;
drh58024642011-11-07 18:16:00 +00002962 do{
drh734c9862008-11-28 15:37:20 +00002963#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002964 got = osPread(id->h, pBuf, cnt, offset);
2965 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002966#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00002967 got = osPread64(id->h, pBuf, cnt, offset);
2968 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002969#else
drh58024642011-11-07 18:16:00 +00002970 newOffset = lseek(id->h, offset, SEEK_SET);
2971 SimulateIOError( newOffset-- );
2972 if( newOffset!=offset ){
2973 if( newOffset == -1 ){
2974 ((unixFile*)id)->lastErrno = errno;
2975 }else{
2976 ((unixFile*)id)->lastErrno = 0;
2977 }
2978 return -1;
drh734c9862008-11-28 15:37:20 +00002979 }
drh58024642011-11-07 18:16:00 +00002980 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00002981#endif
drh58024642011-11-07 18:16:00 +00002982 if( got==cnt ) break;
2983 if( got<0 ){
2984 if( errno==EINTR ){ got = 1; continue; }
2985 prior = 0;
2986 ((unixFile*)id)->lastErrno = errno;
2987 break;
2988 }else if( got>0 ){
2989 cnt -= got;
2990 offset += got;
2991 prior += got;
2992 pBuf = (void*)(got + (char*)pBuf);
2993 }
2994 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00002995 TIMER_END;
drh58024642011-11-07 18:16:00 +00002996 OSTRACE(("READ %-3d %5d %7lld %llu\n",
2997 id->h, got+prior, offset-prior, TIMER_ELAPSED));
2998 return got+prior;
drhbfe66312006-10-03 17:40:40 +00002999}
3000
3001/*
drh734c9862008-11-28 15:37:20 +00003002** Read data from a file into a buffer. Return SQLITE_OK if all
3003** bytes were read successfully and SQLITE_IOERR if anything goes
3004** wrong.
drh339eb0b2008-03-07 15:34:11 +00003005*/
drh734c9862008-11-28 15:37:20 +00003006static int unixRead(
3007 sqlite3_file *id,
3008 void *pBuf,
3009 int amt,
3010 sqlite3_int64 offset
3011){
dan08da86a2009-08-21 17:18:03 +00003012 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003013 int got;
3014 assert( id );
drh08c6d442009-02-09 17:34:07 +00003015
dan08da86a2009-08-21 17:18:03 +00003016 /* If this is a database file (not a journal, master-journal or temp
3017 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003018#if 0
dane946c392009-08-22 11:39:46 +00003019 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003020 || offset>=PENDING_BYTE+512
3021 || offset+amt<=PENDING_BYTE
3022 );
dan7c246102010-04-12 19:00:29 +00003023#endif
drh08c6d442009-02-09 17:34:07 +00003024
dan08da86a2009-08-21 17:18:03 +00003025 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003026 if( got==amt ){
3027 return SQLITE_OK;
3028 }else if( got<0 ){
3029 /* lastErrno set by seekAndRead */
3030 return SQLITE_IOERR_READ;
3031 }else{
dan08da86a2009-08-21 17:18:03 +00003032 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003033 /* Unread parts of the buffer must be zero-filled */
3034 memset(&((char*)pBuf)[got], 0, amt-got);
3035 return SQLITE_IOERR_SHORT_READ;
3036 }
3037}
3038
3039/*
3040** Seek to the offset in id->offset then read cnt bytes into pBuf.
3041** Return the number of bytes actually read. Update the offset.
3042**
3043** To avoid stomping the errno value on a failed write the lastErrno value
3044** is set before returning.
3045*/
3046static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3047 int got;
drh7ed97b92010-01-20 13:07:21 +00003048#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003049 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003050#endif
drh734c9862008-11-28 15:37:20 +00003051 TIMER_START;
3052#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003053 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003054#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003055 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003056#else
drhbd1e50c2011-08-19 14:54:12 +00003057 do{
3058 newOffset = lseek(id->h, offset, SEEK_SET);
3059 SimulateIOError( newOffset-- );
3060 if( newOffset!=offset ){
3061 if( newOffset == -1 ){
3062 ((unixFile*)id)->lastErrno = errno;
3063 }else{
3064 ((unixFile*)id)->lastErrno = 0;
3065 }
3066 return -1;
drh734c9862008-11-28 15:37:20 +00003067 }
drhbd1e50c2011-08-19 14:54:12 +00003068 got = osWrite(id->h, pBuf, cnt);
3069 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003070#endif
3071 TIMER_END;
3072 if( got<0 ){
3073 ((unixFile*)id)->lastErrno = errno;
3074 }
3075
drh308c2a52010-05-14 11:30:18 +00003076 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003077 return got;
3078}
3079
3080
3081/*
3082** Write data from a buffer into a file. Return SQLITE_OK on success
3083** or some other error code on failure.
3084*/
3085static int unixWrite(
3086 sqlite3_file *id,
3087 const void *pBuf,
3088 int amt,
3089 sqlite3_int64 offset
3090){
dan08da86a2009-08-21 17:18:03 +00003091 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003092 int wrote = 0;
3093 assert( id );
3094 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003095
dan08da86a2009-08-21 17:18:03 +00003096 /* If this is a database file (not a journal, master-journal or temp
3097 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003098#if 0
dane946c392009-08-22 11:39:46 +00003099 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003100 || offset>=PENDING_BYTE+512
3101 || offset+amt<=PENDING_BYTE
3102 );
dan7c246102010-04-12 19:00:29 +00003103#endif
drh08c6d442009-02-09 17:34:07 +00003104
drh8f941bc2009-01-14 23:03:40 +00003105#ifndef NDEBUG
3106 /* If we are doing a normal write to a database file (as opposed to
3107 ** doing a hot-journal rollback or a write to some file other than a
3108 ** normal database file) then record the fact that the database
3109 ** has changed. If the transaction counter is modified, record that
3110 ** fact too.
3111 */
dan08da86a2009-08-21 17:18:03 +00003112 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003113 pFile->dbUpdate = 1; /* The database has been modified */
3114 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003115 int rc;
drh8f941bc2009-01-14 23:03:40 +00003116 char oldCntr[4];
3117 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003118 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003119 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003120 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003121 pFile->transCntrChng = 1; /* The transaction counter has changed */
3122 }
3123 }
3124 }
3125#endif
3126
dan08da86a2009-08-21 17:18:03 +00003127 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003128 amt -= wrote;
3129 offset += wrote;
3130 pBuf = &((char*)pBuf)[wrote];
3131 }
3132 SimulateIOError(( wrote=(-1), amt=1 ));
3133 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003134
drh734c9862008-11-28 15:37:20 +00003135 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003136 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003137 /* lastErrno set by seekAndWrite */
3138 return SQLITE_IOERR_WRITE;
3139 }else{
dan08da86a2009-08-21 17:18:03 +00003140 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003141 return SQLITE_FULL;
3142 }
3143 }
dan6e09d692010-07-27 18:34:15 +00003144
drh734c9862008-11-28 15:37:20 +00003145 return SQLITE_OK;
3146}
3147
3148#ifdef SQLITE_TEST
3149/*
3150** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003151** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003152*/
3153int sqlite3_sync_count = 0;
3154int sqlite3_fullsync_count = 0;
3155#endif
3156
3157/*
drh89240432009-03-25 01:06:01 +00003158** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003159** Others do no. To be safe, we will stick with the (slightly slower)
3160** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003161** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003162*/
drh20f8e132011-08-31 21:01:55 +00003163#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003164# define fdatasync fsync
3165#endif
3166
3167/*
3168** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3169** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3170** only available on Mac OS X. But that could change.
3171*/
3172#ifdef F_FULLFSYNC
3173# define HAVE_FULLFSYNC 1
3174#else
3175# define HAVE_FULLFSYNC 0
3176#endif
3177
3178
3179/*
3180** The fsync() system call does not work as advertised on many
3181** unix systems. The following procedure is an attempt to make
3182** it work better.
3183**
3184** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3185** for testing when we want to run through the test suite quickly.
3186** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3187** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3188** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003189**
3190** SQLite sets the dataOnly flag if the size of the file is unchanged.
3191** The idea behind dataOnly is that it should only write the file content
3192** to disk, not the inode. We only set dataOnly if the file size is
3193** unchanged since the file size is part of the inode. However,
3194** Ted Ts'o tells us that fdatasync() will also write the inode if the
3195** file size has changed. The only real difference between fdatasync()
3196** and fsync(), Ted tells us, is that fdatasync() will not flush the
3197** inode if the mtime or owner or other inode attributes have changed.
3198** We only care about the file size, not the other file attributes, so
3199** as far as SQLite is concerned, an fdatasync() is always adequate.
3200** So, we always use fdatasync() if it is available, regardless of
3201** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003202*/
3203static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003204 int rc;
drh734c9862008-11-28 15:37:20 +00003205
3206 /* The following "ifdef/elif/else/" block has the same structure as
3207 ** the one below. It is replicated here solely to avoid cluttering
3208 ** up the real code with the UNUSED_PARAMETER() macros.
3209 */
3210#ifdef SQLITE_NO_SYNC
3211 UNUSED_PARAMETER(fd);
3212 UNUSED_PARAMETER(fullSync);
3213 UNUSED_PARAMETER(dataOnly);
3214#elif HAVE_FULLFSYNC
3215 UNUSED_PARAMETER(dataOnly);
3216#else
3217 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003218 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003219#endif
3220
3221 /* Record the number of times that we do a normal fsync() and
3222 ** FULLSYNC. This is used during testing to verify that this procedure
3223 ** gets called with the correct arguments.
3224 */
3225#ifdef SQLITE_TEST
3226 if( fullSync ) sqlite3_fullsync_count++;
3227 sqlite3_sync_count++;
3228#endif
3229
3230 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3231 ** no-op
3232 */
3233#ifdef SQLITE_NO_SYNC
3234 rc = SQLITE_OK;
3235#elif HAVE_FULLFSYNC
3236 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003237 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003238 }else{
3239 rc = 1;
3240 }
3241 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003242 ** It shouldn't be possible for fullfsync to fail on the local
3243 ** file system (on OSX), so failure indicates that FULLFSYNC
3244 ** isn't supported for this file system. So, attempt an fsync
3245 ** and (for now) ignore the overhead of a superfluous fcntl call.
3246 ** It'd be better to detect fullfsync support once and avoid
3247 ** the fcntl call every time sync is called.
3248 */
drh734c9862008-11-28 15:37:20 +00003249 if( rc ) rc = fsync(fd);
3250
drh7ed97b92010-01-20 13:07:21 +00003251#elif defined(__APPLE__)
3252 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3253 ** so currently we default to the macro that redefines fdatasync to fsync
3254 */
3255 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003256#else
drh0b647ff2009-03-21 14:41:04 +00003257 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003258#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003259 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003260 rc = fsync(fd);
3261 }
drh0b647ff2009-03-21 14:41:04 +00003262#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003263#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3264
3265 if( OS_VXWORKS && rc!= -1 ){
3266 rc = 0;
3267 }
chw97185482008-11-17 08:05:31 +00003268 return rc;
drhbfe66312006-10-03 17:40:40 +00003269}
3270
drh734c9862008-11-28 15:37:20 +00003271/*
drh0059eae2011-08-08 23:48:40 +00003272** Open a file descriptor to the directory containing file zFilename.
3273** If successful, *pFd is set to the opened file descriptor and
3274** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3275** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3276** value.
3277**
drh90315a22011-08-10 01:52:12 +00003278** The directory file descriptor is used for only one thing - to
3279** fsync() a directory to make sure file creation and deletion events
3280** are flushed to disk. Such fsyncs are not needed on newer
3281** journaling filesystems, but are required on older filesystems.
3282**
3283** This routine can be overridden using the xSetSysCall interface.
3284** The ability to override this routine was added in support of the
3285** chromium sandbox. Opening a directory is a security risk (we are
3286** told) so making it overrideable allows the chromium sandbox to
3287** replace this routine with a harmless no-op. To make this routine
3288** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3289** *pFd set to a negative number.
3290**
drh0059eae2011-08-08 23:48:40 +00003291** If SQLITE_OK is returned, the caller is responsible for closing
3292** the file descriptor *pFd using close().
3293*/
3294static int openDirectory(const char *zFilename, int *pFd){
3295 int ii;
3296 int fd = -1;
3297 char zDirname[MAX_PATHNAME+1];
3298
3299 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3300 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3301 if( ii>0 ){
3302 zDirname[ii] = '\0';
3303 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3304 if( fd>=0 ){
3305#ifdef FD_CLOEXEC
3306 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3307#endif
3308 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3309 }
3310 }
3311 *pFd = fd;
3312 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3313}
3314
3315/*
drh734c9862008-11-28 15:37:20 +00003316** Make sure all writes to a particular file are committed to disk.
3317**
3318** If dataOnly==0 then both the file itself and its metadata (file
3319** size, access time, etc) are synced. If dataOnly!=0 then only the
3320** file data is synced.
3321**
3322** Under Unix, also make sure that the directory entry for the file
3323** has been created by fsync-ing the directory that contains the file.
3324** If we do not do this and we encounter a power failure, the directory
3325** entry for the journal might not exist after we reboot. The next
3326** SQLite to access the file will not know that the journal exists (because
3327** the directory entry for the journal was never created) and the transaction
3328** will not roll back - possibly leading to database corruption.
3329*/
3330static int unixSync(sqlite3_file *id, int flags){
3331 int rc;
3332 unixFile *pFile = (unixFile*)id;
3333
3334 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3335 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3336
3337 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3338 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3339 || (flags&0x0F)==SQLITE_SYNC_FULL
3340 );
3341
3342 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3343 ** line is to test that doing so does not cause any problems.
3344 */
3345 SimulateDiskfullError( return SQLITE_FULL );
3346
3347 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003348 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003349 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3350 SimulateIOError( rc=1 );
3351 if( rc ){
3352 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003353 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003354 }
drh0059eae2011-08-08 23:48:40 +00003355
3356 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003357 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3358 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003359 */
3360 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3361 int dirfd;
3362 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003363 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003364 rc = osOpenDirectory(pFile->zPath, &dirfd);
3365 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003366 full_fsync(dirfd, 0, 0);
3367 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003368 }else if( rc==SQLITE_CANTOPEN ){
3369 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003370 }
drh0059eae2011-08-08 23:48:40 +00003371 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003372 }
3373 return rc;
3374}
3375
3376/*
3377** Truncate an open file to a specified size
3378*/
3379static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003380 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003381 int rc;
dan6e09d692010-07-27 18:34:15 +00003382 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003383 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003384
3385 /* If the user has configured a chunk-size for this file, truncate the
3386 ** file so that it consists of an integer number of chunks (i.e. the
3387 ** actual file size after the operation may be larger than the requested
3388 ** size).
3389 */
3390 if( pFile->szChunk ){
3391 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3392 }
3393
drhff812312011-02-23 13:33:46 +00003394 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003395 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003396 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003397 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003398 }else{
drh3313b142009-11-06 04:13:18 +00003399#ifndef NDEBUG
3400 /* If we are doing a normal write to a database file (as opposed to
3401 ** doing a hot-journal rollback or a write to some file other than a
3402 ** normal database file) and we truncate the file to zero length,
3403 ** that effectively updates the change counter. This might happen
3404 ** when restoring a database using the backup API from a zero-length
3405 ** source.
3406 */
dan6e09d692010-07-27 18:34:15 +00003407 if( pFile->inNormalWrite && nByte==0 ){
3408 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003409 }
3410#endif
3411
drh734c9862008-11-28 15:37:20 +00003412 return SQLITE_OK;
3413 }
3414}
3415
3416/*
3417** Determine the current size of a file in bytes
3418*/
3419static int unixFileSize(sqlite3_file *id, i64 *pSize){
3420 int rc;
3421 struct stat buf;
3422 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003423 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003424 SimulateIOError( rc=1 );
3425 if( rc!=0 ){
3426 ((unixFile*)id)->lastErrno = errno;
3427 return SQLITE_IOERR_FSTAT;
3428 }
3429 *pSize = buf.st_size;
3430
drh8af6c222010-05-14 12:43:01 +00003431 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003432 ** writes a single byte into that file in order to work around a bug
3433 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3434 ** layers, we need to report this file size as zero even though it is
3435 ** really 1. Ticket #3260.
3436 */
3437 if( *pSize==1 ) *pSize = 0;
3438
3439
3440 return SQLITE_OK;
3441}
3442
drhd2cb50b2009-01-09 21:41:17 +00003443#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003444/*
3445** Handler for proxy-locking file-control verbs. Defined below in the
3446** proxying locking division.
3447*/
3448static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003449#endif
drh715ff302008-12-03 22:32:44 +00003450
dan502019c2010-07-28 14:26:17 +00003451/*
3452** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003453** file-control operation. Enlarge the database to nBytes in size
3454** (rounded up to the next chunk-size). If the database is already
3455** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003456*/
3457static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003458 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003459 i64 nSize; /* Required file size */
3460 struct stat buf; /* Used to hold return values of fstat() */
3461
drh99ab3b12011-03-02 15:09:07 +00003462 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003463
3464 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3465 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003466
dan502019c2010-07-28 14:26:17 +00003467#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003468 /* The code below is handling the return value of osFallocate()
3469 ** correctly. posix_fallocate() is defined to "returns zero on success,
3470 ** or an error number on failure". See the manpage for details. */
3471 int err;
drhff812312011-02-23 13:33:46 +00003472 do{
dan661d71a2011-03-30 19:08:03 +00003473 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3474 }while( err==EINTR );
3475 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003476#else
3477 /* If the OS does not have posix_fallocate(), fake it. First use
3478 ** ftruncate() to set the file size, then write a single byte to
3479 ** the last byte in each block within the extended region. This
3480 ** is the same technique used by glibc to implement posix_fallocate()
3481 ** on systems that do not have a real fallocate() system call.
3482 */
3483 int nBlk = buf.st_blksize; /* File-system block size */
3484 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003485
drhff812312011-02-23 13:33:46 +00003486 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003487 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003488 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003489 }
3490 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003491 while( iWrite<nSize ){
3492 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3493 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003494 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003495 }
dan502019c2010-07-28 14:26:17 +00003496#endif
3497 }
3498 }
3499
3500 return SQLITE_OK;
3501}
danielk1977ad94b582007-08-20 06:44:22 +00003502
danielk1977e3026632004-06-22 11:29:02 +00003503/*
drhf12b3f62011-12-21 14:42:29 +00003504** If *pArg is inititially negative then this is a query. Set *pArg to
3505** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3506**
3507** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3508*/
3509static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3510 if( *pArg<0 ){
3511 *pArg = (pFile->ctrlFlags & mask)!=0;
3512 }else if( (*pArg)==0 ){
3513 pFile->ctrlFlags &= ~mask;
3514 }else{
3515 pFile->ctrlFlags |= mask;
3516 }
3517}
3518
3519/*
drh9e33c2c2007-08-31 18:34:59 +00003520** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003521*/
drhcc6bb3e2007-08-31 16:11:35 +00003522static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003523 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003524 switch( op ){
3525 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003526 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003527 return SQLITE_OK;
3528 }
drh7708e972008-11-29 00:56:52 +00003529 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003530 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003531 return SQLITE_OK;
3532 }
dan6e09d692010-07-27 18:34:15 +00003533 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003534 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003535 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003536 }
drh9ff27ec2010-05-19 19:26:05 +00003537 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003538 int rc;
3539 SimulateIOErrorBenign(1);
3540 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3541 SimulateIOErrorBenign(0);
3542 return rc;
drhf0b190d2011-07-26 16:03:07 +00003543 }
3544 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003545 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3546 return SQLITE_OK;
3547 }
drhcb15f352011-12-23 01:04:17 +00003548 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3549 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003550 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003551 }
drhde60fc22011-12-14 17:53:36 +00003552 case SQLITE_FCNTL_VFSNAME: {
3553 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3554 return SQLITE_OK;
3555 }
drh8f941bc2009-01-14 23:03:40 +00003556#ifndef NDEBUG
3557 /* The pager calls this method to signal that it has done
3558 ** a rollback and that the database is therefore unchanged and
3559 ** it hence it is OK for the transaction change counter to be
3560 ** unchanged.
3561 */
3562 case SQLITE_FCNTL_DB_UNCHANGED: {
3563 ((unixFile*)id)->dbUpdate = 0;
3564 return SQLITE_OK;
3565 }
3566#endif
drhd2cb50b2009-01-09 21:41:17 +00003567#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003568 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003569 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003570 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003571 }
drhd2cb50b2009-01-09 21:41:17 +00003572#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh0b52b7d2011-01-26 19:46:22 +00003573 case SQLITE_FCNTL_SYNC_OMITTED: {
3574 return SQLITE_OK; /* A no-op */
3575 }
drh9e33c2c2007-08-31 18:34:59 +00003576 }
drh0b52b7d2011-01-26 19:46:22 +00003577 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003578}
3579
3580/*
danielk1977a3d4c882007-03-23 10:08:38 +00003581** Return the sector size in bytes of the underlying block device for
3582** the specified file. This is almost always 512 bytes, but may be
3583** larger for some devices.
3584**
3585** SQLite code assumes this function cannot fail. It also assumes that
3586** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003587** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003588** same for both.
3589*/
drh1da88f02011-12-17 16:09:16 +00003590static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003591 (void)pFile;
3592 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003593}
3594
danielk197790949c22007-08-17 16:50:38 +00003595/*
drhf12b3f62011-12-21 14:42:29 +00003596** Return the device characteristics for the file.
3597**
drhcb15f352011-12-23 01:04:17 +00003598** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3599** However, that choice is contraversial since technically the underlying
3600** file system does not always provide powersafe overwrites. (In other
3601** words, after a power-loss event, parts of the file that were never
3602** written might end up being altered.) However, non-PSOW behavior is very,
3603** very rare. And asserting PSOW makes a large reduction in the amount
3604** of required I/O for journaling, since a lot of padding is eliminated.
3605** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3606** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003607*/
drhf12b3f62011-12-21 14:42:29 +00003608static int unixDeviceCharacteristics(sqlite3_file *id){
3609 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003610 if( p->ctrlFlags & UNIXFILE_PSOW ){
3611 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3612 }else{
3613 return 0;
3614 }
danielk197762079062007-08-15 17:08:46 +00003615}
3616
drhd9e5c4f2010-05-12 18:01:39 +00003617#ifndef SQLITE_OMIT_WAL
3618
3619
3620/*
drhd91c68f2010-05-14 14:52:25 +00003621** Object used to represent an shared memory buffer.
3622**
3623** When multiple threads all reference the same wal-index, each thread
3624** has its own unixShm object, but they all point to a single instance
3625** of this unixShmNode object. In other words, each wal-index is opened
3626** only once per process.
3627**
3628** Each unixShmNode object is connected to a single unixInodeInfo object.
3629** We could coalesce this object into unixInodeInfo, but that would mean
3630** every open file that does not use shared memory (in other words, most
3631** open files) would have to carry around this extra information. So
3632** the unixInodeInfo object contains a pointer to this unixShmNode object
3633** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003634**
3635** unixMutexHeld() must be true when creating or destroying
3636** this object or while reading or writing the following fields:
3637**
3638** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003639**
3640** The following fields are read-only after the object is created:
3641**
3642** fid
3643** zFilename
3644**
drhd91c68f2010-05-14 14:52:25 +00003645** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003646** unixMutexHeld() is true when reading or writing any other field
3647** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003648*/
drhd91c68f2010-05-14 14:52:25 +00003649struct unixShmNode {
3650 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003651 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003652 char *zFilename; /* Name of the mmapped file */
3653 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003654 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003655 u16 nRegion; /* Size of array apRegion */
3656 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003657 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003658 int nRef; /* Number of unixShm objects pointing to this */
3659 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003660#ifdef SQLITE_DEBUG
3661 u8 exclMask; /* Mask of exclusive locks held */
3662 u8 sharedMask; /* Mask of shared locks held */
3663 u8 nextShmId; /* Next available unixShm.id value */
3664#endif
3665};
3666
3667/*
drhd9e5c4f2010-05-12 18:01:39 +00003668** Structure used internally by this VFS to record the state of an
3669** open shared memory connection.
3670**
drhd91c68f2010-05-14 14:52:25 +00003671** The following fields are initialized when this object is created and
3672** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003673**
drhd91c68f2010-05-14 14:52:25 +00003674** unixShm.pFile
3675** unixShm.id
3676**
3677** All other fields are read/write. The unixShm.pFile->mutex must be held
3678** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003679*/
3680struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003681 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3682 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003683 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003684 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003685 u16 sharedMask; /* Mask of shared locks held */
3686 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003687};
3688
3689/*
drhd9e5c4f2010-05-12 18:01:39 +00003690** Constants used for locking
3691*/
drhbd9676c2010-06-23 17:58:38 +00003692#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003693#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003694
drhd9e5c4f2010-05-12 18:01:39 +00003695/*
drh73b64e42010-05-30 19:55:15 +00003696** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003697**
3698** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3699** otherwise.
3700*/
3701static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003702 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3703 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003704 int ofst, /* First byte of the locking range */
3705 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003706){
3707 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003708 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003709
drhd91c68f2010-05-14 14:52:25 +00003710 /* Access to the unixShmNode object is serialized by the caller */
3711 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003712
drh73b64e42010-05-30 19:55:15 +00003713 /* Shared locks never span more than one byte */
3714 assert( n==1 || lockType!=F_RDLCK );
3715
3716 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003717 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003718
drh3cb93392011-03-12 18:10:44 +00003719 if( pShmNode->h>=0 ){
3720 /* Initialize the locking parameters */
3721 memset(&f, 0, sizeof(f));
3722 f.l_type = lockType;
3723 f.l_whence = SEEK_SET;
3724 f.l_start = ofst;
3725 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003726
drh3cb93392011-03-12 18:10:44 +00003727 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3728 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3729 }
drhd9e5c4f2010-05-12 18:01:39 +00003730
3731 /* Update the global lock state and do debug tracing */
3732#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003733 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003734 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003735 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003736 if( rc==SQLITE_OK ){
3737 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003738 OSTRACE(("unlock %d ok", ofst));
3739 pShmNode->exclMask &= ~mask;
3740 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003741 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003742 OSTRACE(("read-lock %d ok", ofst));
3743 pShmNode->exclMask &= ~mask;
3744 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003745 }else{
3746 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003747 OSTRACE(("write-lock %d ok", ofst));
3748 pShmNode->exclMask |= mask;
3749 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003750 }
3751 }else{
3752 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003753 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003754 }else if( lockType==F_RDLCK ){
3755 OSTRACE(("read-lock failed"));
3756 }else{
3757 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003758 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003759 }
3760 }
drh20e1f082010-05-31 16:10:12 +00003761 OSTRACE((" - afterwards %03x,%03x\n",
3762 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003763 }
drhd9e5c4f2010-05-12 18:01:39 +00003764#endif
3765
3766 return rc;
3767}
3768
drhd9e5c4f2010-05-12 18:01:39 +00003769
3770/*
drhd91c68f2010-05-14 14:52:25 +00003771** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003772**
3773** This is not a VFS shared-memory method; it is a utility function called
3774** by VFS shared-memory methods.
3775*/
drhd91c68f2010-05-14 14:52:25 +00003776static void unixShmPurge(unixFile *pFd){
3777 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003778 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003779 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003780 int i;
drhd91c68f2010-05-14 14:52:25 +00003781 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003782 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003783 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003784 if( p->h>=0 ){
3785 munmap(p->apRegion[i], p->szRegion);
3786 }else{
3787 sqlite3_free(p->apRegion[i]);
3788 }
dan13a3cb82010-06-11 19:04:21 +00003789 }
dan18801912010-06-14 14:07:50 +00003790 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003791 if( p->h>=0 ){
3792 robust_close(pFd, p->h, __LINE__);
3793 p->h = -1;
3794 }
drhd91c68f2010-05-14 14:52:25 +00003795 p->pInode->pShmNode = 0;
3796 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003797 }
3798}
3799
3800/*
danda9fe0c2010-07-13 18:44:03 +00003801** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003802** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003803**
drh7234c6d2010-06-19 15:10:09 +00003804** The file used to implement shared-memory is in the same directory
3805** as the open database file and has the same name as the open database
3806** file with the "-shm" suffix added. For example, if the database file
3807** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003808** for shared memory will be called "/home/user1/config.db-shm".
3809**
3810** Another approach to is to use files in /dev/shm or /dev/tmp or an
3811** some other tmpfs mount. But if a file in a different directory
3812** from the database file is used, then differing access permissions
3813** or a chroot() might cause two different processes on the same
3814** database to end up using different files for shared memory -
3815** meaning that their memory would not really be shared - resulting
3816** in database corruption. Nevertheless, this tmpfs file usage
3817** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3818** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3819** option results in an incompatible build of SQLite; builds of SQLite
3820** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3821** same database file at the same time, database corruption will likely
3822** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3823** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003824**
3825** When opening a new shared-memory file, if no other instances of that
3826** file are currently open, in this process or in other processes, then
3827** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003828**
3829** If the original database file (pDbFd) is using the "unix-excl" VFS
3830** that means that an exclusive lock is held on the database file and
3831** that no other processes are able to read or write the database. In
3832** that case, we do not really need shared memory. No shared memory
3833** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003834*/
danda9fe0c2010-07-13 18:44:03 +00003835static int unixOpenSharedMemory(unixFile *pDbFd){
3836 struct unixShm *p = 0; /* The connection to be opened */
3837 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3838 int rc; /* Result code */
3839 unixInodeInfo *pInode; /* The inode of fd */
3840 char *zShmFilename; /* Name of the file used for SHM */
3841 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003842
danda9fe0c2010-07-13 18:44:03 +00003843 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003844 p = sqlite3_malloc( sizeof(*p) );
3845 if( p==0 ) return SQLITE_NOMEM;
3846 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003847 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003848
danda9fe0c2010-07-13 18:44:03 +00003849 /* Check to see if a unixShmNode object already exists. Reuse an existing
3850 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003851 */
3852 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003853 pInode = pDbFd->pInode;
3854 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003855 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003856 struct stat sStat; /* fstat() info for database file */
3857
3858 /* Call fstat() to figure out the permissions on the database file. If
3859 ** a new *-shm file is created, an attempt will be made to create it
3860 ** with the same permissions. The actual permissions the file is created
3861 ** with are subject to the current umask setting.
3862 */
drh3cb93392011-03-12 18:10:44 +00003863 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003864 rc = SQLITE_IOERR_FSTAT;
3865 goto shm_open_err;
3866 }
3867
drha4ced192010-07-15 18:32:40 +00003868#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003869 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003870#else
drh52bcde02012-01-03 14:50:45 +00003871 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003872#endif
drh7234c6d2010-06-19 15:10:09 +00003873 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003874 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003875 rc = SQLITE_NOMEM;
3876 goto shm_open_err;
3877 }
drhd91c68f2010-05-14 14:52:25 +00003878 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003879 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003880#ifdef SQLITE_SHM_DIRECTORY
3881 sqlite3_snprintf(nShmFilename, zShmFilename,
3882 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3883 (u32)sStat.st_ino, (u32)sStat.st_dev);
3884#else
drh7234c6d2010-06-19 15:10:09 +00003885 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003886 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003887#endif
drhd91c68f2010-05-14 14:52:25 +00003888 pShmNode->h = -1;
3889 pDbFd->pInode->pShmNode = pShmNode;
3890 pShmNode->pInode = pDbFd->pInode;
3891 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3892 if( pShmNode->mutex==0 ){
3893 rc = SQLITE_NOMEM;
3894 goto shm_open_err;
3895 }
drhd9e5c4f2010-05-12 18:01:39 +00003896
drh3cb93392011-03-12 18:10:44 +00003897 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003898 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003899 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003900 openFlags = O_RDONLY;
3901 pShmNode->isReadonly = 1;
3902 }
3903 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003904 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003905 if( pShmNode->h<0 ){
3906 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3907 goto shm_open_err;
3908 }
drhd9e5c4f2010-05-12 18:01:39 +00003909 }
drh3cb93392011-03-12 18:10:44 +00003910
3911 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003912 ** If not, truncate the file to zero length.
3913 */
3914 rc = SQLITE_OK;
3915 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3916 if( robust_ftruncate(pShmNode->h, 0) ){
3917 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003918 }
3919 }
drh66dfec8b2011-06-01 20:01:49 +00003920 if( rc==SQLITE_OK ){
3921 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3922 }
3923 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003924 }
drhd9e5c4f2010-05-12 18:01:39 +00003925 }
3926
drhd91c68f2010-05-14 14:52:25 +00003927 /* Make the new connection a child of the unixShmNode */
3928 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003929#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003930 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003931#endif
drhd91c68f2010-05-14 14:52:25 +00003932 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003933 pDbFd->pShm = p;
3934 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003935
3936 /* The reference count on pShmNode has already been incremented under
3937 ** the cover of the unixEnterMutex() mutex and the pointer from the
3938 ** new (struct unixShm) object to the pShmNode has been set. All that is
3939 ** left to do is to link the new object into the linked list starting
3940 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3941 ** mutex.
3942 */
3943 sqlite3_mutex_enter(pShmNode->mutex);
3944 p->pNext = pShmNode->pFirst;
3945 pShmNode->pFirst = p;
3946 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003947 return SQLITE_OK;
3948
3949 /* Jump here on any error */
3950shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003951 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003952 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003953 unixLeaveMutex();
3954 return rc;
3955}
3956
3957/*
danda9fe0c2010-07-13 18:44:03 +00003958** This function is called to obtain a pointer to region iRegion of the
3959** shared-memory associated with the database file fd. Shared-memory regions
3960** are numbered starting from zero. Each shared-memory region is szRegion
3961** bytes in size.
3962**
3963** If an error occurs, an error code is returned and *pp is set to NULL.
3964**
3965** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3966** region has not been allocated (by any client, including one running in a
3967** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3968** bExtend is non-zero and the requested shared-memory region has not yet
3969** been allocated, it is allocated by this function.
3970**
3971** If the shared-memory region has already been allocated or is allocated by
3972** this call as described above, then it is mapped into this processes
3973** address space (if it is not already), *pp is set to point to the mapped
3974** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003975*/
danda9fe0c2010-07-13 18:44:03 +00003976static int unixShmMap(
3977 sqlite3_file *fd, /* Handle open on database file */
3978 int iRegion, /* Region to retrieve */
3979 int szRegion, /* Size of regions */
3980 int bExtend, /* True to extend file if necessary */
3981 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003982){
danda9fe0c2010-07-13 18:44:03 +00003983 unixFile *pDbFd = (unixFile*)fd;
3984 unixShm *p;
3985 unixShmNode *pShmNode;
3986 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003987
danda9fe0c2010-07-13 18:44:03 +00003988 /* If the shared-memory file has not yet been opened, open it now. */
3989 if( pDbFd->pShm==0 ){
3990 rc = unixOpenSharedMemory(pDbFd);
3991 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003992 }
drhd9e5c4f2010-05-12 18:01:39 +00003993
danda9fe0c2010-07-13 18:44:03 +00003994 p = pDbFd->pShm;
3995 pShmNode = p->pShmNode;
3996 sqlite3_mutex_enter(pShmNode->mutex);
3997 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003998 assert( pShmNode->pInode==pDbFd->pInode );
3999 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4000 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004001
4002 if( pShmNode->nRegion<=iRegion ){
4003 char **apNew; /* New apRegion[] array */
4004 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4005 struct stat sStat; /* Used by fstat() */
4006
4007 pShmNode->szRegion = szRegion;
4008
drh3cb93392011-03-12 18:10:44 +00004009 if( pShmNode->h>=0 ){
4010 /* The requested region is not mapped into this processes address space.
4011 ** Check to see if it has been allocated (i.e. if the wal-index file is
4012 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004013 */
drh3cb93392011-03-12 18:10:44 +00004014 if( osFstat(pShmNode->h, &sStat) ){
4015 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004016 goto shmpage_out;
4017 }
drh3cb93392011-03-12 18:10:44 +00004018
4019 if( sStat.st_size<nByte ){
4020 /* The requested memory region does not exist. If bExtend is set to
4021 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4022 **
4023 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4024 ** the requested memory region.
4025 */
4026 if( !bExtend ) goto shmpage_out;
4027 if( robust_ftruncate(pShmNode->h, nByte) ){
4028 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4029 pShmNode->zFilename);
4030 goto shmpage_out;
4031 }
4032 }
danda9fe0c2010-07-13 18:44:03 +00004033 }
4034
4035 /* Map the requested memory region into this processes address space. */
4036 apNew = (char **)sqlite3_realloc(
4037 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4038 );
4039 if( !apNew ){
4040 rc = SQLITE_IOERR_NOMEM;
4041 goto shmpage_out;
4042 }
4043 pShmNode->apRegion = apNew;
4044 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004045 void *pMem;
4046 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004047 pMem = mmap(0, szRegion,
4048 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004049 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4050 );
4051 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004052 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004053 goto shmpage_out;
4054 }
4055 }else{
4056 pMem = sqlite3_malloc(szRegion);
4057 if( pMem==0 ){
4058 rc = SQLITE_NOMEM;
4059 goto shmpage_out;
4060 }
4061 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004062 }
4063 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4064 pShmNode->nRegion++;
4065 }
4066 }
4067
4068shmpage_out:
4069 if( pShmNode->nRegion>iRegion ){
4070 *pp = pShmNode->apRegion[iRegion];
4071 }else{
4072 *pp = 0;
4073 }
drh66dfec8b2011-06-01 20:01:49 +00004074 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004075 sqlite3_mutex_leave(pShmNode->mutex);
4076 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004077}
4078
4079/*
drhd9e5c4f2010-05-12 18:01:39 +00004080** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004081**
4082** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4083** different here than in posix. In xShmLock(), one can go from unlocked
4084** to shared and back or from unlocked to exclusive and back. But one may
4085** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004086*/
4087static int unixShmLock(
4088 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004089 int ofst, /* First lock to acquire or release */
4090 int n, /* Number of locks to acquire or release */
4091 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004092){
drh73b64e42010-05-30 19:55:15 +00004093 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4094 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4095 unixShm *pX; /* For looping over all siblings */
4096 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4097 int rc = SQLITE_OK; /* Result code */
4098 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004099
drhd91c68f2010-05-14 14:52:25 +00004100 assert( pShmNode==pDbFd->pInode->pShmNode );
4101 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004102 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004103 assert( n>=1 );
4104 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4105 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4106 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4107 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4108 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004109 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4110 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004111
drhc99597c2010-05-31 01:41:15 +00004112 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004113 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004114 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004115 if( flags & SQLITE_SHM_UNLOCK ){
4116 u16 allMask = 0; /* Mask of locks held by siblings */
4117
4118 /* See if any siblings hold this same lock */
4119 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4120 if( pX==p ) continue;
4121 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4122 allMask |= pX->sharedMask;
4123 }
4124
4125 /* Unlock the system-level locks */
4126 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004127 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004128 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004129 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004130 }
drh73b64e42010-05-30 19:55:15 +00004131
4132 /* Undo the local locks */
4133 if( rc==SQLITE_OK ){
4134 p->exclMask &= ~mask;
4135 p->sharedMask &= ~mask;
4136 }
4137 }else if( flags & SQLITE_SHM_SHARED ){
4138 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4139
4140 /* Find out which shared locks are already held by sibling connections.
4141 ** If any sibling already holds an exclusive lock, go ahead and return
4142 ** SQLITE_BUSY.
4143 */
4144 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004145 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004146 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004147 break;
4148 }
4149 allShared |= pX->sharedMask;
4150 }
4151
4152 /* Get shared locks at the system level, if necessary */
4153 if( rc==SQLITE_OK ){
4154 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004155 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004156 }else{
drh73b64e42010-05-30 19:55:15 +00004157 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004158 }
drhd9e5c4f2010-05-12 18:01:39 +00004159 }
drh73b64e42010-05-30 19:55:15 +00004160
4161 /* Get the local shared locks */
4162 if( rc==SQLITE_OK ){
4163 p->sharedMask |= mask;
4164 }
4165 }else{
4166 /* Make sure no sibling connections hold locks that will block this
4167 ** lock. If any do, return SQLITE_BUSY right away.
4168 */
4169 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004170 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4171 rc = SQLITE_BUSY;
4172 break;
4173 }
4174 }
4175
4176 /* Get the exclusive locks at the system level. Then if successful
4177 ** also mark the local connection as being locked.
4178 */
4179 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004180 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004181 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004182 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004183 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004184 }
drhd9e5c4f2010-05-12 18:01:39 +00004185 }
4186 }
drhd91c68f2010-05-14 14:52:25 +00004187 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004188 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4189 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004190 return rc;
4191}
4192
drh286a2882010-05-20 23:51:06 +00004193/*
4194** Implement a memory barrier or memory fence on shared memory.
4195**
4196** All loads and stores begun before the barrier must complete before
4197** any load or store begun after the barrier.
4198*/
4199static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004200 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004201){
drhff828942010-06-26 21:34:06 +00004202 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004203 unixEnterMutex();
4204 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004205}
4206
dan18801912010-06-14 14:07:50 +00004207/*
danda9fe0c2010-07-13 18:44:03 +00004208** Close a connection to shared-memory. Delete the underlying
4209** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004210**
4211** If there is no shared memory associated with the connection then this
4212** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004213*/
danda9fe0c2010-07-13 18:44:03 +00004214static int unixShmUnmap(
4215 sqlite3_file *fd, /* The underlying database file */
4216 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004217){
danda9fe0c2010-07-13 18:44:03 +00004218 unixShm *p; /* The connection to be closed */
4219 unixShmNode *pShmNode; /* The underlying shared-memory file */
4220 unixShm **pp; /* For looping over sibling connections */
4221 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004222
danda9fe0c2010-07-13 18:44:03 +00004223 pDbFd = (unixFile*)fd;
4224 p = pDbFd->pShm;
4225 if( p==0 ) return SQLITE_OK;
4226 pShmNode = p->pShmNode;
4227
4228 assert( pShmNode==pDbFd->pInode->pShmNode );
4229 assert( pShmNode->pInode==pDbFd->pInode );
4230
4231 /* Remove connection p from the set of connections associated
4232 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004233 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004234 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4235 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004236
danda9fe0c2010-07-13 18:44:03 +00004237 /* Free the connection p */
4238 sqlite3_free(p);
4239 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004240 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004241
4242 /* If pShmNode->nRef has reached 0, then close the underlying
4243 ** shared-memory file, too */
4244 unixEnterMutex();
4245 assert( pShmNode->nRef>0 );
4246 pShmNode->nRef--;
4247 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004248 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004249 unixShmPurge(pDbFd);
4250 }
4251 unixLeaveMutex();
4252
4253 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004254}
drh286a2882010-05-20 23:51:06 +00004255
danda9fe0c2010-07-13 18:44:03 +00004256
drhd9e5c4f2010-05-12 18:01:39 +00004257#else
drh6b017cc2010-06-14 18:01:46 +00004258# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004259# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004260# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004261# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004262#endif /* #ifndef SQLITE_OMIT_WAL */
4263
drh734c9862008-11-28 15:37:20 +00004264/*
4265** Here ends the implementation of all sqlite3_file methods.
4266**
4267********************** End sqlite3_file Methods *******************************
4268******************************************************************************/
4269
4270/*
drh6b9d6dd2008-12-03 19:34:47 +00004271** This division contains definitions of sqlite3_io_methods objects that
4272** implement various file locking strategies. It also contains definitions
4273** of "finder" functions. A finder-function is used to locate the appropriate
4274** sqlite3_io_methods object for a particular database file. The pAppData
4275** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4276** the correct finder-function for that VFS.
4277**
4278** Most finder functions return a pointer to a fixed sqlite3_io_methods
4279** object. The only interesting finder-function is autolockIoFinder, which
4280** looks at the filesystem type and tries to guess the best locking
4281** strategy from that.
4282**
drh1875f7a2008-12-08 18:19:17 +00004283** For finder-funtion F, two objects are created:
4284**
4285** (1) The real finder-function named "FImpt()".
4286**
dane946c392009-08-22 11:39:46 +00004287** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004288**
4289**
4290** A pointer to the F pointer is used as the pAppData value for VFS
4291** objects. We have to do this instead of letting pAppData point
4292** directly at the finder-function since C90 rules prevent a void*
4293** from be cast into a function pointer.
4294**
drh6b9d6dd2008-12-03 19:34:47 +00004295**
drh7708e972008-11-29 00:56:52 +00004296** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004297**
drh7708e972008-11-29 00:56:52 +00004298** * A constant sqlite3_io_methods object call METHOD that has locking
4299** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4300**
4301** * An I/O method finder function called FINDER that returns a pointer
4302** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004303*/
drhd9e5c4f2010-05-12 18:01:39 +00004304#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004305static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004306 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004307 CLOSE, /* xClose */ \
4308 unixRead, /* xRead */ \
4309 unixWrite, /* xWrite */ \
4310 unixTruncate, /* xTruncate */ \
4311 unixSync, /* xSync */ \
4312 unixFileSize, /* xFileSize */ \
4313 LOCK, /* xLock */ \
4314 UNLOCK, /* xUnlock */ \
4315 CKLOCK, /* xCheckReservedLock */ \
4316 unixFileControl, /* xFileControl */ \
4317 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004318 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004319 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004320 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004321 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004322 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004323}; \
drh0c2694b2009-09-03 16:23:44 +00004324static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4325 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004326 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004327} \
drh0c2694b2009-09-03 16:23:44 +00004328static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004329 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004330
4331/*
4332** Here are all of the sqlite3_io_methods objects for each of the
4333** locking strategies. Functions that return pointers to these methods
4334** are also created.
4335*/
4336IOMETHODS(
4337 posixIoFinder, /* Finder function name */
4338 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004339 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004340 unixClose, /* xClose method */
4341 unixLock, /* xLock method */
4342 unixUnlock, /* xUnlock method */
4343 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004344)
drh7708e972008-11-29 00:56:52 +00004345IOMETHODS(
4346 nolockIoFinder, /* Finder function name */
4347 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004348 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004349 nolockClose, /* xClose method */
4350 nolockLock, /* xLock method */
4351 nolockUnlock, /* xUnlock method */
4352 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004353)
drh7708e972008-11-29 00:56:52 +00004354IOMETHODS(
4355 dotlockIoFinder, /* Finder function name */
4356 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004357 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004358 dotlockClose, /* xClose method */
4359 dotlockLock, /* xLock method */
4360 dotlockUnlock, /* xUnlock method */
4361 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004362)
drh7708e972008-11-29 00:56:52 +00004363
chw78a13182009-04-07 05:35:03 +00004364#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004365IOMETHODS(
4366 flockIoFinder, /* Finder function name */
4367 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004368 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004369 flockClose, /* xClose method */
4370 flockLock, /* xLock method */
4371 flockUnlock, /* xUnlock method */
4372 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004373)
drh7708e972008-11-29 00:56:52 +00004374#endif
4375
drh6c7d5c52008-11-21 20:32:33 +00004376#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004377IOMETHODS(
4378 semIoFinder, /* Finder function name */
4379 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004380 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004381 semClose, /* xClose method */
4382 semLock, /* xLock method */
4383 semUnlock, /* xUnlock method */
4384 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004385)
aswiftaebf4132008-11-21 00:10:35 +00004386#endif
drh7708e972008-11-29 00:56:52 +00004387
drhd2cb50b2009-01-09 21:41:17 +00004388#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004389IOMETHODS(
4390 afpIoFinder, /* Finder function name */
4391 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004392 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004393 afpClose, /* xClose method */
4394 afpLock, /* xLock method */
4395 afpUnlock, /* xUnlock method */
4396 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004397)
drh715ff302008-12-03 22:32:44 +00004398#endif
4399
4400/*
4401** The proxy locking method is a "super-method" in the sense that it
4402** opens secondary file descriptors for the conch and lock files and
4403** it uses proxy, dot-file, AFP, and flock() locking methods on those
4404** secondary files. For this reason, the division that implements
4405** proxy locking is located much further down in the file. But we need
4406** to go ahead and define the sqlite3_io_methods and finder function
4407** for proxy locking here. So we forward declare the I/O methods.
4408*/
drhd2cb50b2009-01-09 21:41:17 +00004409#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004410static int proxyClose(sqlite3_file*);
4411static int proxyLock(sqlite3_file*, int);
4412static int proxyUnlock(sqlite3_file*, int);
4413static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004414IOMETHODS(
4415 proxyIoFinder, /* Finder function name */
4416 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004417 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004418 proxyClose, /* xClose method */
4419 proxyLock, /* xLock method */
4420 proxyUnlock, /* xUnlock method */
4421 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004422)
aswiftaebf4132008-11-21 00:10:35 +00004423#endif
drh7708e972008-11-29 00:56:52 +00004424
drh7ed97b92010-01-20 13:07:21 +00004425/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4426#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4427IOMETHODS(
4428 nfsIoFinder, /* Finder function name */
4429 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004430 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004431 unixClose, /* xClose method */
4432 unixLock, /* xLock method */
4433 nfsUnlock, /* xUnlock method */
4434 unixCheckReservedLock /* xCheckReservedLock method */
4435)
4436#endif
drh7708e972008-11-29 00:56:52 +00004437
drhd2cb50b2009-01-09 21:41:17 +00004438#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004439/*
drh6b9d6dd2008-12-03 19:34:47 +00004440** This "finder" function attempts to determine the best locking strategy
4441** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004442** object that implements that strategy.
4443**
4444** This is for MacOSX only.
4445*/
drh1875f7a2008-12-08 18:19:17 +00004446static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004447 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004448 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004449){
4450 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004451 const char *zFilesystem; /* Filesystem type name */
4452 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004453 } aMap[] = {
4454 { "hfs", &posixIoMethods },
4455 { "ufs", &posixIoMethods },
4456 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004457 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004458 { "webdav", &nolockIoMethods },
4459 { 0, 0 }
4460 };
4461 int i;
4462 struct statfs fsInfo;
4463 struct flock lockInfo;
4464
4465 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004466 /* If filePath==NULL that means we are dealing with a transient file
4467 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004468 return &nolockIoMethods;
4469 }
4470 if( statfs(filePath, &fsInfo) != -1 ){
4471 if( fsInfo.f_flags & MNT_RDONLY ){
4472 return &nolockIoMethods;
4473 }
4474 for(i=0; aMap[i].zFilesystem; i++){
4475 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4476 return aMap[i].pMethods;
4477 }
4478 }
4479 }
4480
4481 /* Default case. Handles, amongst others, "nfs".
4482 ** Test byte-range lock using fcntl(). If the call succeeds,
4483 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004484 */
drh7708e972008-11-29 00:56:52 +00004485 lockInfo.l_len = 1;
4486 lockInfo.l_start = 0;
4487 lockInfo.l_whence = SEEK_SET;
4488 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004489 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004490 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4491 return &nfsIoMethods;
4492 } else {
4493 return &posixIoMethods;
4494 }
drh7708e972008-11-29 00:56:52 +00004495 }else{
4496 return &dotlockIoMethods;
4497 }
4498}
drh0c2694b2009-09-03 16:23:44 +00004499static const sqlite3_io_methods
4500 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004501
drhd2cb50b2009-01-09 21:41:17 +00004502#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004503
chw78a13182009-04-07 05:35:03 +00004504#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4505/*
4506** This "finder" function attempts to determine the best locking strategy
4507** for the database file "filePath". It then returns the sqlite3_io_methods
4508** object that implements that strategy.
4509**
4510** This is for VXWorks only.
4511*/
4512static const sqlite3_io_methods *autolockIoFinderImpl(
4513 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004514 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004515){
4516 struct flock lockInfo;
4517
4518 if( !filePath ){
4519 /* If filePath==NULL that means we are dealing with a transient file
4520 ** that does not need to be locked. */
4521 return &nolockIoMethods;
4522 }
4523
4524 /* Test if fcntl() is supported and use POSIX style locks.
4525 ** Otherwise fall back to the named semaphore method.
4526 */
4527 lockInfo.l_len = 1;
4528 lockInfo.l_start = 0;
4529 lockInfo.l_whence = SEEK_SET;
4530 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004531 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004532 return &posixIoMethods;
4533 }else{
4534 return &semIoMethods;
4535 }
4536}
drh0c2694b2009-09-03 16:23:44 +00004537static const sqlite3_io_methods
4538 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004539
4540#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4541
drh7708e972008-11-29 00:56:52 +00004542/*
4543** An abstract type for a pointer to a IO method finder function:
4544*/
drh0c2694b2009-09-03 16:23:44 +00004545typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004546
aswiftaebf4132008-11-21 00:10:35 +00004547
drh734c9862008-11-28 15:37:20 +00004548/****************************************************************************
4549**************************** sqlite3_vfs methods ****************************
4550**
4551** This division contains the implementation of methods on the
4552** sqlite3_vfs object.
4553*/
4554
danielk1977a3d4c882007-03-23 10:08:38 +00004555/*
danielk1977e339d652008-06-28 11:23:00 +00004556** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004557*/
4558static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004559 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004560 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004561 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004562 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004563 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004564 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004565 int isDelete, /* Delete on close if true */
4566 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004567){
drh7708e972008-11-29 00:56:52 +00004568 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004569 unixFile *pNew = (unixFile *)pId;
4570 int rc = SQLITE_OK;
4571
drh8af6c222010-05-14 12:43:01 +00004572 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004573
dane946c392009-08-22 11:39:46 +00004574 /* Parameter isDelete is only used on vxworks. Express this explicitly
4575 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004576 */
drh7708e972008-11-29 00:56:52 +00004577 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004578
dan00157392010-10-05 11:33:15 +00004579 /* Usually the path zFilename should not be a relative pathname. The
4580 ** exception is when opening the proxy "conch" file in builds that
4581 ** include the special Apple locking styles.
4582 */
dan00157392010-10-05 11:33:15 +00004583#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004584 assert( zFilename==0 || zFilename[0]=='/'
4585 || pVfs->pAppData==(void*)&autolockIoFinder );
4586#else
4587 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004588#endif
dan00157392010-10-05 11:33:15 +00004589
drhb07028f2011-10-14 21:49:18 +00004590 /* No locking occurs in temporary files */
4591 assert( zFilename!=0 || noLock );
4592
drh308c2a52010-05-14 11:30:18 +00004593 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004594 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004595 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004596 pNew->zPath = zFilename;
drhbec7c972011-12-23 00:25:02 +00004597 pNew->ctrlFlags = 0;
drhcb15f352011-12-23 01:04:17 +00004598 if( sqlite3_uri_boolean(zFilename, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
4599 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004600 }
drha7e61d82011-03-12 17:02:57 +00004601 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004602 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004603 }
drh77197112011-03-15 19:08:48 +00004604 if( isReadOnly ){
4605 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4606 }
drh0059eae2011-08-08 23:48:40 +00004607 if( syncDir ){
4608 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4609 }
drh339eb0b2008-03-07 15:34:11 +00004610
drh6c7d5c52008-11-21 20:32:33 +00004611#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004612 pNew->pId = vxworksFindFileId(zFilename);
4613 if( pNew->pId==0 ){
4614 noLock = 1;
4615 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004616 }
4617#endif
4618
drhda0e7682008-07-30 15:27:54 +00004619 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004620 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004621 }else{
drh0c2694b2009-09-03 16:23:44 +00004622 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004623#if SQLITE_ENABLE_LOCKING_STYLE
4624 /* Cache zFilename in the locking context (AFP and dotlock override) for
4625 ** proxyLock activation is possible (remote proxy is based on db name)
4626 ** zFilename remains valid until file is closed, to support */
4627 pNew->lockingContext = (void*)zFilename;
4628#endif
drhda0e7682008-07-30 15:27:54 +00004629 }
danielk1977e339d652008-06-28 11:23:00 +00004630
drh7ed97b92010-01-20 13:07:21 +00004631 if( pLockingStyle == &posixIoMethods
4632#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4633 || pLockingStyle == &nfsIoMethods
4634#endif
4635 ){
drh7708e972008-11-29 00:56:52 +00004636 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004637 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004638 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004639 /* If an error occured in findInodeInfo(), close the file descriptor
4640 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004641 ** in two scenarios:
4642 **
4643 ** (a) A call to fstat() failed.
4644 ** (b) A malloc failed.
4645 **
4646 ** Scenario (b) may only occur if the process is holding no other
4647 ** file descriptors open on the same file. If there were other file
4648 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004649 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004650 ** handle h - as it is guaranteed that no posix locks will be released
4651 ** by doing so.
4652 **
4653 ** If scenario (a) caused the error then things are not so safe. The
4654 ** implicit assumption here is that if fstat() fails, things are in
4655 ** such bad shape that dropping a lock or two doesn't matter much.
4656 */
drh0e9365c2011-03-02 02:08:13 +00004657 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004658 h = -1;
4659 }
drh7708e972008-11-29 00:56:52 +00004660 unixLeaveMutex();
4661 }
danielk1977e339d652008-06-28 11:23:00 +00004662
drhd2cb50b2009-01-09 21:41:17 +00004663#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004664 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004665 /* AFP locking uses the file path so it needs to be included in
4666 ** the afpLockingContext.
4667 */
4668 afpLockingContext *pCtx;
4669 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4670 if( pCtx==0 ){
4671 rc = SQLITE_NOMEM;
4672 }else{
4673 /* NB: zFilename exists and remains valid until the file is closed
4674 ** according to requirement F11141. So we do not need to make a
4675 ** copy of the filename. */
4676 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004677 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004678 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004679 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004680 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004681 if( rc!=SQLITE_OK ){
4682 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004683 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004684 h = -1;
4685 }
drh7708e972008-11-29 00:56:52 +00004686 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004687 }
drh7708e972008-11-29 00:56:52 +00004688 }
4689#endif
danielk1977e339d652008-06-28 11:23:00 +00004690
drh7708e972008-11-29 00:56:52 +00004691 else if( pLockingStyle == &dotlockIoMethods ){
4692 /* Dotfile locking uses the file path so it needs to be included in
4693 ** the dotlockLockingContext
4694 */
4695 char *zLockFile;
4696 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004697 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004698 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004699 zLockFile = (char *)sqlite3_malloc(nFilename);
4700 if( zLockFile==0 ){
4701 rc = SQLITE_NOMEM;
4702 }else{
4703 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004704 }
drh7708e972008-11-29 00:56:52 +00004705 pNew->lockingContext = zLockFile;
4706 }
danielk1977e339d652008-06-28 11:23:00 +00004707
drh6c7d5c52008-11-21 20:32:33 +00004708#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004709 else if( pLockingStyle == &semIoMethods ){
4710 /* Named semaphore locking uses the file path so it needs to be
4711 ** included in the semLockingContext
4712 */
4713 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004714 rc = findInodeInfo(pNew, &pNew->pInode);
4715 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4716 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004717 int n;
drh2238dcc2009-08-27 17:56:20 +00004718 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004719 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004720 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004721 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004722 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4723 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004724 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004725 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004726 }
chw97185482008-11-17 08:05:31 +00004727 }
drh7708e972008-11-29 00:56:52 +00004728 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004729 }
drh7708e972008-11-29 00:56:52 +00004730#endif
aswift5b1a2562008-08-22 00:22:35 +00004731
4732 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004733#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004734 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004735 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004736 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004737 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004738 isDelete = 0;
4739 }
4740 pNew->isDelete = isDelete;
4741#endif
danielk1977e339d652008-06-28 11:23:00 +00004742 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004743 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004744 }else{
drh7708e972008-11-29 00:56:52 +00004745 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004746 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004747 }
danielk1977e339d652008-06-28 11:23:00 +00004748 return rc;
drh054889e2005-11-30 03:20:31 +00004749}
drh9c06c952005-11-26 00:25:00 +00004750
danielk1977ad94b582007-08-20 06:44:22 +00004751/*
drh8b3cf822010-06-01 21:02:51 +00004752** Return the name of a directory in which to put temporary files.
4753** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004754*/
drh7234c6d2010-06-19 15:10:09 +00004755static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004756 static const char *azDirs[] = {
4757 0,
aswiftaebf4132008-11-21 00:10:35 +00004758 0,
danielk197717b90b52008-06-06 11:11:25 +00004759 "/var/tmp",
4760 "/usr/tmp",
4761 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004762 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004763 };
drh8b3cf822010-06-01 21:02:51 +00004764 unsigned int i;
4765 struct stat buf;
4766 const char *zDir = 0;
4767
4768 azDirs[0] = sqlite3_temp_directory;
4769 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004770 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004771 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004772 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004773 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004774 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004775 break;
4776 }
4777 return zDir;
4778}
4779
4780/*
4781** Create a temporary file name in zBuf. zBuf must be allocated
4782** by the calling process and must be big enough to hold at least
4783** pVfs->mxPathname bytes.
4784*/
4785static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004786 static const unsigned char zChars[] =
4787 "abcdefghijklmnopqrstuvwxyz"
4788 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4789 "0123456789";
drh41022642008-11-21 00:24:42 +00004790 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004791 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004792
4793 /* It's odd to simulate an io-error here, but really this is just
4794 ** using the io-error infrastructure to test that SQLite handles this
4795 ** function failing.
4796 */
4797 SimulateIOError( return SQLITE_IOERR );
4798
drh7234c6d2010-06-19 15:10:09 +00004799 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004800 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004801
4802 /* Check that the output buffer is large enough for the temporary file
4803 ** name. If it is not, return SQLITE_ERROR.
4804 */
danielk197700e13612008-11-17 19:18:54 +00004805 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004806 return SQLITE_ERROR;
4807 }
4808
4809 do{
4810 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004811 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004812 sqlite3_randomness(15, &zBuf[j]);
4813 for(i=0; i<15; i++, j++){
4814 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4815 }
4816 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004817 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004818 return SQLITE_OK;
4819}
4820
drhd2cb50b2009-01-09 21:41:17 +00004821#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004822/*
4823** Routine to transform a unixFile into a proxy-locking unixFile.
4824** Implementation in the proxy-lock division, but used by unixOpen()
4825** if SQLITE_PREFER_PROXY_LOCKING is defined.
4826*/
4827static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004828#endif
drhc66d5b62008-12-03 22:48:32 +00004829
dan08da86a2009-08-21 17:18:03 +00004830/*
4831** Search for an unused file descriptor that was opened on the database
4832** file (not a journal or master-journal file) identified by pathname
4833** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4834** argument to this function.
4835**
4836** Such a file descriptor may exist if a database connection was closed
4837** but the associated file descriptor could not be closed because some
4838** other file descriptor open on the same file is holding a file-lock.
4839** Refer to comments in the unixClose() function and the lengthy comment
4840** describing "Posix Advisory Locking" at the start of this file for
4841** further details. Also, ticket #4018.
4842**
4843** If a suitable file descriptor is found, then it is returned. If no
4844** such file descriptor is located, -1 is returned.
4845*/
dane946c392009-08-22 11:39:46 +00004846static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4847 UnixUnusedFd *pUnused = 0;
4848
4849 /* Do not search for an unused file descriptor on vxworks. Not because
4850 ** vxworks would not benefit from the change (it might, we're not sure),
4851 ** but because no way to test it is currently available. It is better
4852 ** not to risk breaking vxworks support for the sake of such an obscure
4853 ** feature. */
4854#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004855 struct stat sStat; /* Results of stat() call */
4856
4857 /* A stat() call may fail for various reasons. If this happens, it is
4858 ** almost certain that an open() call on the same path will also fail.
4859 ** For this reason, if an error occurs in the stat() call here, it is
4860 ** ignored and -1 is returned. The caller will try to open a new file
4861 ** descriptor on the same path, fail, and return an error to SQLite.
4862 **
4863 ** Even if a subsequent open() call does succeed, the consequences of
4864 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004865 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004866 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004867
4868 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004869 pInode = inodeList;
4870 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4871 || pInode->fileId.ino!=sStat.st_ino) ){
4872 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004873 }
drh8af6c222010-05-14 12:43:01 +00004874 if( pInode ){
dane946c392009-08-22 11:39:46 +00004875 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004876 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004877 pUnused = *pp;
4878 if( pUnused ){
4879 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004880 }
4881 }
4882 unixLeaveMutex();
4883 }
dane946c392009-08-22 11:39:46 +00004884#endif /* if !OS_VXWORKS */
4885 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004886}
danielk197717b90b52008-06-06 11:11:25 +00004887
4888/*
danddb0ac42010-07-14 14:48:58 +00004889** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004890** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004891** and a value suitable for passing as the third argument to open(2) is
4892** written to *pMode. If an IO error occurs, an SQLite error code is
4893** returned and the value of *pMode is not modified.
4894**
4895** If the file being opened is a temporary file, it is always created with
4896** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004897** is a database or master journal file, it is created with the permissions
4898** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004899**
drh8ab58662010-07-15 18:38:39 +00004900** Finally, if the file being opened is a WAL or regular journal file, then
4901** this function queries the file-system for the permissions on the
4902** corresponding database file and sets *pMode to this value. Whenever
4903** possible, WAL and journal files are created using the same permissions
4904** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004905**
4906** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4907** original filename is unavailable. But 8_3_NAMES is only used for
4908** FAT filesystems and permissions do not matter there, so just use
4909** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004910*/
4911static int findCreateFileMode(
4912 const char *zPath, /* Path of file (possibly) being created */
4913 int flags, /* Flags passed as 4th argument to xOpen() */
4914 mode_t *pMode /* OUT: Permissions to open file with */
4915){
4916 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004917 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004918 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004919 char zDb[MAX_PATHNAME+1]; /* Database file path */
4920 int nDb; /* Number of valid bytes in zDb */
4921 struct stat sStat; /* Output of stat() on database file */
4922
dana0c989d2010-11-05 18:07:37 +00004923 /* zPath is a path to a WAL or journal file. The following block derives
4924 ** the path to the associated database file from zPath. This block handles
4925 ** the following naming conventions:
4926 **
4927 ** "<path to db>-journal"
4928 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004929 ** "<path to db>-journalNN"
4930 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004931 **
drhd337c5b2011-10-20 18:23:35 +00004932 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004933 ** used by the test_multiplex.c module.
4934 */
4935 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004936#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004937 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004938 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004939#else
4940 while( zPath[nDb]!='-' ){
4941 assert( nDb>0 );
4942 assert( zPath[nDb]!='\n' );
4943 nDb--;
4944 }
4945#endif
danddb0ac42010-07-14 14:48:58 +00004946 memcpy(zDb, zPath, nDb);
4947 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004948
drh58384f12011-07-28 00:14:45 +00004949 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004950 *pMode = sStat.st_mode & 0777;
4951 }else{
4952 rc = SQLITE_IOERR_FSTAT;
4953 }
4954 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4955 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004956 }
4957 return rc;
4958}
4959
4960/*
danielk1977ad94b582007-08-20 06:44:22 +00004961** Open the file zPath.
4962**
danielk1977b4b47412007-08-17 15:53:36 +00004963** Previously, the SQLite OS layer used three functions in place of this
4964** one:
4965**
4966** sqlite3OsOpenReadWrite();
4967** sqlite3OsOpenReadOnly();
4968** sqlite3OsOpenExclusive();
4969**
4970** These calls correspond to the following combinations of flags:
4971**
4972** ReadWrite() -> (READWRITE | CREATE)
4973** ReadOnly() -> (READONLY)
4974** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4975**
4976** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4977** true, the file was configured to be automatically deleted when the
4978** file handle closed. To achieve the same effect using this new
4979** interface, add the DELETEONCLOSE flag to those specified above for
4980** OpenExclusive().
4981*/
4982static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004983 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4984 const char *zPath, /* Pathname of file to be opened */
4985 sqlite3_file *pFile, /* The file descriptor to be filled in */
4986 int flags, /* Input flags to control the opening */
4987 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004988){
dan08da86a2009-08-21 17:18:03 +00004989 unixFile *p = (unixFile *)pFile;
4990 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004991 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004992 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004993 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004994 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004995
4996 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4997 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4998 int isCreate = (flags & SQLITE_OPEN_CREATE);
4999 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5000 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005001#if SQLITE_ENABLE_LOCKING_STYLE
5002 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5003#endif
drh3d4435b2011-08-26 20:55:50 +00005004#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5005 struct statfs fsInfo;
5006#endif
danielk1977b4b47412007-08-17 15:53:36 +00005007
danielk1977fee2d252007-08-18 10:59:19 +00005008 /* If creating a master or main-file journal, this function will open
5009 ** a file-descriptor on the directory too. The first time unixSync()
5010 ** is called the directory file descriptor will be fsync()ed and close()d.
5011 */
drh0059eae2011-08-08 23:48:40 +00005012 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005013 eType==SQLITE_OPEN_MASTER_JOURNAL
5014 || eType==SQLITE_OPEN_MAIN_JOURNAL
5015 || eType==SQLITE_OPEN_WAL
5016 ));
danielk1977fee2d252007-08-18 10:59:19 +00005017
danielk197717b90b52008-06-06 11:11:25 +00005018 /* If argument zPath is a NULL pointer, this function is required to open
5019 ** a temporary file. Use this buffer to store the file name in.
5020 */
5021 char zTmpname[MAX_PATHNAME+1];
5022 const char *zName = zPath;
5023
danielk1977fee2d252007-08-18 10:59:19 +00005024 /* Check the following statements are true:
5025 **
5026 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5027 ** (b) if CREATE is set, then READWRITE must also be set, and
5028 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005029 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005030 */
danielk1977b4b47412007-08-17 15:53:36 +00005031 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005032 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005033 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005034 assert(isDelete==0 || isCreate);
5035
danddb0ac42010-07-14 14:48:58 +00005036 /* The main DB, main journal, WAL file and master journal are never
5037 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005038 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5039 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5040 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005041 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005042
danielk1977fee2d252007-08-18 10:59:19 +00005043 /* Assert that the upper layer has set one of the "file-type" flags. */
5044 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5045 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5046 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005047 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005048 );
5049
dan08da86a2009-08-21 17:18:03 +00005050 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005051
dan08da86a2009-08-21 17:18:03 +00005052 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005053 UnixUnusedFd *pUnused;
5054 pUnused = findReusableFd(zName, flags);
5055 if( pUnused ){
5056 fd = pUnused->fd;
5057 }else{
dan6aa657f2009-08-24 18:57:58 +00005058 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005059 if( !pUnused ){
5060 return SQLITE_NOMEM;
5061 }
5062 }
5063 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005064 }else if( !zName ){
5065 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005066 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005067 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005068 if( rc!=SQLITE_OK ){
5069 return rc;
5070 }
5071 zName = zTmpname;
5072 }
5073
dan08da86a2009-08-21 17:18:03 +00005074 /* Determine the value of the flags parameter passed to POSIX function
5075 ** open(). These must be calculated even if open() is not called, as
5076 ** they may be stored as part of the file handle and used by the
5077 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005078 if( isReadonly ) openFlags |= O_RDONLY;
5079 if( isReadWrite ) openFlags |= O_RDWR;
5080 if( isCreate ) openFlags |= O_CREAT;
5081 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5082 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005083
danielk1977b4b47412007-08-17 15:53:36 +00005084 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005085 mode_t openMode; /* Permissions to create file with */
5086 rc = findCreateFileMode(zName, flags, &openMode);
5087 if( rc!=SQLITE_OK ){
5088 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005089 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005090 return rc;
5091 }
drhad4f1e52011-03-04 15:43:57 +00005092 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005093 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005094 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5095 /* Failed to open the file for read/write access. Try read-only. */
5096 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005097 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005098 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005099 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005100 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005101 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005102 }
5103 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005104 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005105 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005106 }
danielk1977b4b47412007-08-17 15:53:36 +00005107 }
dan08da86a2009-08-21 17:18:03 +00005108 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005109 if( pOutFlags ){
5110 *pOutFlags = flags;
5111 }
5112
dane946c392009-08-22 11:39:46 +00005113 if( p->pUnused ){
5114 p->pUnused->fd = fd;
5115 p->pUnused->flags = flags;
5116 }
5117
danielk1977b4b47412007-08-17 15:53:36 +00005118 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005119#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005120 zPath = zName;
5121#else
drh036ac7f2011-08-08 23:18:05 +00005122 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005123#endif
danielk1977b4b47412007-08-17 15:53:36 +00005124 }
drh41022642008-11-21 00:24:42 +00005125#if SQLITE_ENABLE_LOCKING_STYLE
5126 else{
dan08da86a2009-08-21 17:18:03 +00005127 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005128 }
5129#endif
5130
danielk1977e339d652008-06-28 11:23:00 +00005131#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005132 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005133#endif
5134
drhda0e7682008-07-30 15:27:54 +00005135 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005136
drh7ed97b92010-01-20 13:07:21 +00005137
5138#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005139 if( fstatfs(fd, &fsInfo) == -1 ){
5140 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005141 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005142 return SQLITE_IOERR_ACCESS;
5143 }
5144 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5145 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5146 }
5147#endif
5148
5149#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005150#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005151 isAutoProxy = 1;
5152#endif
5153 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005154 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5155 int useProxy = 0;
5156
dan08da86a2009-08-21 17:18:03 +00005157 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5158 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005159 if( envforce!=NULL ){
5160 useProxy = atoi(envforce)>0;
5161 }else{
aswiftaebf4132008-11-21 00:10:35 +00005162 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005163 /* In theory, the close(fd) call is sub-optimal. If the file opened
5164 ** with fd is a database file, and there are other connections open
5165 ** on that file that are currently holding advisory locks on it,
5166 ** then the call to close() will cancel those locks. In practice,
5167 ** we're assuming that statfs() doesn't fail very often. At least
5168 ** not while other file descriptors opened by the same process on
5169 ** the same file are working. */
5170 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005171 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005172 rc = SQLITE_IOERR_ACCESS;
5173 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005174 }
5175 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5176 }
5177 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005178 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005179 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005180 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005181 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005182 if( rc!=SQLITE_OK ){
5183 /* Use unixClose to clean up the resources added in fillInUnixFile
5184 ** and clear all the structure's references. Specifically,
5185 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5186 */
5187 unixClose(pFile);
5188 return rc;
5189 }
aswiftaebf4132008-11-21 00:10:35 +00005190 }
dane946c392009-08-22 11:39:46 +00005191 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005192 }
5193 }
5194#endif
5195
drh0059eae2011-08-08 23:48:40 +00005196 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005197 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005198open_finished:
5199 if( rc!=SQLITE_OK ){
5200 sqlite3_free(p->pUnused);
5201 }
5202 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005203}
5204
dane946c392009-08-22 11:39:46 +00005205
danielk1977b4b47412007-08-17 15:53:36 +00005206/*
danielk1977fee2d252007-08-18 10:59:19 +00005207** Delete the file at zPath. If the dirSync argument is true, fsync()
5208** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005209*/
drh6b9d6dd2008-12-03 19:34:47 +00005210static int unixDelete(
5211 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5212 const char *zPath, /* Name of file to be deleted */
5213 int dirSync /* If true, fsync() directory after deleting file */
5214){
danielk1977fee2d252007-08-18 10:59:19 +00005215 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005216 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005217 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005218 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005219 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005220 }
danielk1977d39fa702008-10-16 13:27:40 +00005221#ifndef SQLITE_DISABLE_DIRSYNC
danielk1977fee2d252007-08-18 10:59:19 +00005222 if( dirSync ){
5223 int fd;
drh90315a22011-08-10 01:52:12 +00005224 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005225 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005226#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005227 if( fsync(fd)==-1 )
5228#else
5229 if( fsync(fd) )
5230#endif
5231 {
dane18d4952011-02-21 11:46:24 +00005232 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005233 }
drh0e9365c2011-03-02 02:08:13 +00005234 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005235 }else if( rc==SQLITE_CANTOPEN ){
5236 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005237 }
5238 }
danielk1977d138dd82008-10-15 16:02:48 +00005239#endif
danielk1977fee2d252007-08-18 10:59:19 +00005240 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005241}
5242
danielk197790949c22007-08-17 16:50:38 +00005243/*
5244** Test the existance of or access permissions of file zPath. The
5245** test performed depends on the value of flags:
5246**
5247** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5248** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5249** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5250**
5251** Otherwise return 0.
5252*/
danielk1977861f7452008-06-05 11:39:11 +00005253static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005254 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5255 const char *zPath, /* Path of the file to examine */
5256 int flags, /* What do we want to learn about the zPath file? */
5257 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005258){
rse25c0d1a2007-09-20 08:38:14 +00005259 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005260 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005261 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005262 switch( flags ){
5263 case SQLITE_ACCESS_EXISTS:
5264 amode = F_OK;
5265 break;
5266 case SQLITE_ACCESS_READWRITE:
5267 amode = W_OK|R_OK;
5268 break;
drh50d3f902007-08-27 21:10:36 +00005269 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005270 amode = R_OK;
5271 break;
5272
5273 default:
5274 assert(!"Invalid flags argument");
5275 }
drh99ab3b12011-03-02 15:09:07 +00005276 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005277 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5278 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005279 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005280 *pResOut = 0;
5281 }
5282 }
danielk1977861f7452008-06-05 11:39:11 +00005283 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005284}
5285
danielk1977b4b47412007-08-17 15:53:36 +00005286
5287/*
5288** Turn a relative pathname into a full pathname. The relative path
5289** is stored as a nul-terminated string in the buffer pointed to by
5290** zPath.
5291**
5292** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5293** (in this case, MAX_PATHNAME bytes). The full-path is written to
5294** this buffer before returning.
5295*/
danielk1977adfb9b02007-09-17 07:02:56 +00005296static int unixFullPathname(
5297 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5298 const char *zPath, /* Possibly relative input path */
5299 int nOut, /* Size of output buffer in bytes */
5300 char *zOut /* Output buffer */
5301){
danielk1977843e65f2007-09-01 16:16:15 +00005302
5303 /* It's odd to simulate an io-error here, but really this is just
5304 ** using the io-error infrastructure to test that SQLite handles this
5305 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005306 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005307 */
5308 SimulateIOError( return SQLITE_ERROR );
5309
drh153c62c2007-08-24 03:51:33 +00005310 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005311 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005312
drh3c7f2dc2007-12-06 13:26:20 +00005313 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005314 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005315 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005316 }else{
5317 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005318 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005319 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005320 }
drhea678832008-12-10 19:26:22 +00005321 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005322 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005323 }
5324 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005325}
5326
drh0ccebe72005-06-07 22:22:50 +00005327
drh761df872006-12-21 01:29:22 +00005328#ifndef SQLITE_OMIT_LOAD_EXTENSION
5329/*
5330** Interfaces for opening a shared library, finding entry points
5331** within the shared library, and closing the shared library.
5332*/
5333#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005334static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5335 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005336 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5337}
danielk197795c8a542007-09-01 06:51:27 +00005338
5339/*
5340** SQLite calls this function immediately after a call to unixDlSym() or
5341** unixDlOpen() fails (returns a null pointer). If a more detailed error
5342** message is available, it is written to zBufOut. If no error message
5343** is available, zBufOut is left unmodified and SQLite uses a default
5344** error message.
5345*/
danielk1977397d65f2008-11-19 11:35:39 +00005346static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005347 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005348 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005349 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005350 zErr = dlerror();
5351 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005352 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005353 }
drh6c7d5c52008-11-21 20:32:33 +00005354 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005355}
drh1875f7a2008-12-08 18:19:17 +00005356static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5357 /*
5358 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5359 ** cast into a pointer to a function. And yet the library dlsym() routine
5360 ** returns a void* which is really a pointer to a function. So how do we
5361 ** use dlsym() with -pedantic-errors?
5362 **
5363 ** Variable x below is defined to be a pointer to a function taking
5364 ** parameters void* and const char* and returning a pointer to a function.
5365 ** We initialize x by assigning it a pointer to the dlsym() function.
5366 ** (That assignment requires a cast.) Then we call the function that
5367 ** x points to.
5368 **
5369 ** This work-around is unlikely to work correctly on any system where
5370 ** you really cannot cast a function pointer into void*. But then, on the
5371 ** other hand, dlsym() will not work on such a system either, so we have
5372 ** not really lost anything.
5373 */
5374 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005375 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005376 x = (void(*(*)(void*,const char*))(void))dlsym;
5377 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005378}
danielk1977397d65f2008-11-19 11:35:39 +00005379static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5380 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005381 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005382}
danielk1977b4b47412007-08-17 15:53:36 +00005383#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5384 #define unixDlOpen 0
5385 #define unixDlError 0
5386 #define unixDlSym 0
5387 #define unixDlClose 0
5388#endif
5389
5390/*
danielk197790949c22007-08-17 16:50:38 +00005391** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005392*/
danielk1977397d65f2008-11-19 11:35:39 +00005393static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5394 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005395 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005396
drhbbd42a62004-05-22 17:41:58 +00005397 /* We have to initialize zBuf to prevent valgrind from reporting
5398 ** errors. The reports issued by valgrind are incorrect - we would
5399 ** prefer that the randomness be increased by making use of the
5400 ** uninitialized space in zBuf - but valgrind errors tend to worry
5401 ** some users. Rather than argue, it seems easier just to initialize
5402 ** the whole array and silence valgrind, even if that means less randomness
5403 ** in the random seed.
5404 **
5405 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005406 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005407 ** tests repeatable.
5408 */
danielk1977b4b47412007-08-17 15:53:36 +00005409 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005410#if !defined(SQLITE_TEST)
5411 {
drh842b8642005-01-21 17:53:17 +00005412 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005413 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005414 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005415 time_t t;
5416 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005417 memcpy(zBuf, &t, sizeof(t));
5418 pid = getpid();
5419 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005420 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005421 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005422 }else{
drhe562be52011-03-02 18:01:10 +00005423 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005424 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005425 }
drhbbd42a62004-05-22 17:41:58 +00005426 }
5427#endif
drh72cbd072008-10-14 17:58:38 +00005428 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005429}
5430
danielk1977b4b47412007-08-17 15:53:36 +00005431
drhbbd42a62004-05-22 17:41:58 +00005432/*
5433** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005434** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005435** The return value is the number of microseconds of sleep actually
5436** requested from the underlying operating system, a number which
5437** might be greater than or equal to the argument, but not less
5438** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005439*/
danielk1977397d65f2008-11-19 11:35:39 +00005440static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005441#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005442 struct timespec sp;
5443
5444 sp.tv_sec = microseconds / 1000000;
5445 sp.tv_nsec = (microseconds % 1000000) * 1000;
5446 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005447 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005448 return microseconds;
5449#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005450 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005451 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005452 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005453#else
danielk1977b4b47412007-08-17 15:53:36 +00005454 int seconds = (microseconds+999999)/1000000;
5455 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005456 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005457 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005458#endif
drh88f474a2006-01-02 20:00:12 +00005459}
5460
5461/*
drh6b9d6dd2008-12-03 19:34:47 +00005462** The following variable, if set to a non-zero value, is interpreted as
5463** the number of seconds since 1970 and is used to set the result of
5464** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005465*/
5466#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005467int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005468#endif
5469
5470/*
drhb7e8ea22010-05-03 14:32:30 +00005471** Find the current time (in Universal Coordinated Time). Write into *piNow
5472** the current time and date as a Julian Day number times 86_400_000. In
5473** other words, write into *piNow the number of milliseconds since the Julian
5474** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5475** proleptic Gregorian calendar.
5476**
drh31702252011-10-12 23:13:43 +00005477** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5478** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005479*/
5480static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5481 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005482 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005483#if defined(NO_GETTOD)
5484 time_t t;
5485 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005486 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005487#elif OS_VXWORKS
5488 struct timespec sNow;
5489 clock_gettime(CLOCK_REALTIME, &sNow);
5490 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5491#else
5492 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005493 if( gettimeofday(&sNow, 0)==0 ){
5494 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5495 }else{
5496 rc = SQLITE_ERROR;
5497 }
drhb7e8ea22010-05-03 14:32:30 +00005498#endif
5499
5500#ifdef SQLITE_TEST
5501 if( sqlite3_current_time ){
5502 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5503 }
5504#endif
5505 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005506 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005507}
5508
5509/*
drhbbd42a62004-05-22 17:41:58 +00005510** Find the current time (in Universal Coordinated Time). Write the
5511** current time and date as a Julian Day number into *prNow and
5512** return 0. Return 1 if the time and date cannot be found.
5513*/
danielk1977397d65f2008-11-19 11:35:39 +00005514static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005515 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005516 int rc;
drhff828942010-06-26 21:34:06 +00005517 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005518 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005519 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005520 return rc;
drhbbd42a62004-05-22 17:41:58 +00005521}
danielk1977b4b47412007-08-17 15:53:36 +00005522
drh6b9d6dd2008-12-03 19:34:47 +00005523/*
5524** We added the xGetLastError() method with the intention of providing
5525** better low-level error messages when operating-system problems come up
5526** during SQLite operation. But so far, none of that has been implemented
5527** in the core. So this routine is never called. For now, it is merely
5528** a place-holder.
5529*/
danielk1977397d65f2008-11-19 11:35:39 +00005530static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5531 UNUSED_PARAMETER(NotUsed);
5532 UNUSED_PARAMETER(NotUsed2);
5533 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005534 return 0;
5535}
5536
drhf2424c52010-04-26 00:04:55 +00005537
5538/*
drh734c9862008-11-28 15:37:20 +00005539************************ End of sqlite3_vfs methods ***************************
5540******************************************************************************/
5541
drh715ff302008-12-03 22:32:44 +00005542/******************************************************************************
5543************************** Begin Proxy Locking ********************************
5544**
5545** Proxy locking is a "uber-locking-method" in this sense: It uses the
5546** other locking methods on secondary lock files. Proxy locking is a
5547** meta-layer over top of the primitive locking implemented above. For
5548** this reason, the division that implements of proxy locking is deferred
5549** until late in the file (here) after all of the other I/O methods have
5550** been defined - so that the primitive locking methods are available
5551** as services to help with the implementation of proxy locking.
5552**
5553****
5554**
5555** The default locking schemes in SQLite use byte-range locks on the
5556** database file to coordinate safe, concurrent access by multiple readers
5557** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5558** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5559** as POSIX read & write locks over fixed set of locations (via fsctl),
5560** on AFP and SMB only exclusive byte-range locks are available via fsctl
5561** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5562** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5563** address in the shared range is taken for a SHARED lock, the entire
5564** shared range is taken for an EXCLUSIVE lock):
5565**
5566** PENDING_BYTE 0x40000000
5567** RESERVED_BYTE 0x40000001
5568** SHARED_RANGE 0x40000002 -> 0x40000200
5569**
5570** This works well on the local file system, but shows a nearly 100x
5571** slowdown in read performance on AFP because the AFP client disables
5572** the read cache when byte-range locks are present. Enabling the read
5573** cache exposes a cache coherency problem that is present on all OS X
5574** supported network file systems. NFS and AFP both observe the
5575** close-to-open semantics for ensuring cache coherency
5576** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5577** address the requirements for concurrent database access by multiple
5578** readers and writers
5579** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5580**
5581** To address the performance and cache coherency issues, proxy file locking
5582** changes the way database access is controlled by limiting access to a
5583** single host at a time and moving file locks off of the database file
5584** and onto a proxy file on the local file system.
5585**
5586**
5587** Using proxy locks
5588** -----------------
5589**
5590** C APIs
5591**
5592** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5593** <proxy_path> | ":auto:");
5594** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5595**
5596**
5597** SQL pragmas
5598**
5599** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5600** PRAGMA [database.]lock_proxy_file
5601**
5602** Specifying ":auto:" means that if there is a conch file with a matching
5603** host ID in it, the proxy path in the conch file will be used, otherwise
5604** a proxy path based on the user's temp dir
5605** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5606** actual proxy file name is generated from the name and path of the
5607** database file. For example:
5608**
5609** For database path "/Users/me/foo.db"
5610** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5611**
5612** Once a lock proxy is configured for a database connection, it can not
5613** be removed, however it may be switched to a different proxy path via
5614** the above APIs (assuming the conch file is not being held by another
5615** connection or process).
5616**
5617**
5618** How proxy locking works
5619** -----------------------
5620**
5621** Proxy file locking relies primarily on two new supporting files:
5622**
5623** * conch file to limit access to the database file to a single host
5624** at a time
5625**
5626** * proxy file to act as a proxy for the advisory locks normally
5627** taken on the database
5628**
5629** The conch file - to use a proxy file, sqlite must first "hold the conch"
5630** by taking an sqlite-style shared lock on the conch file, reading the
5631** contents and comparing the host's unique host ID (see below) and lock
5632** proxy path against the values stored in the conch. The conch file is
5633** stored in the same directory as the database file and the file name
5634** is patterned after the database file name as ".<databasename>-conch".
5635** If the conch file does not exist, or it's contents do not match the
5636** host ID and/or proxy path, then the lock is escalated to an exclusive
5637** lock and the conch file contents is updated with the host ID and proxy
5638** path and the lock is downgraded to a shared lock again. If the conch
5639** is held by another process (with a shared lock), the exclusive lock
5640** will fail and SQLITE_BUSY is returned.
5641**
5642** The proxy file - a single-byte file used for all advisory file locks
5643** normally taken on the database file. This allows for safe sharing
5644** of the database file for multiple readers and writers on the same
5645** host (the conch ensures that they all use the same local lock file).
5646**
drh715ff302008-12-03 22:32:44 +00005647** Requesting the lock proxy does not immediately take the conch, it is
5648** only taken when the first request to lock database file is made.
5649** This matches the semantics of the traditional locking behavior, where
5650** opening a connection to a database file does not take a lock on it.
5651** The shared lock and an open file descriptor are maintained until
5652** the connection to the database is closed.
5653**
5654** The proxy file and the lock file are never deleted so they only need
5655** to be created the first time they are used.
5656**
5657** Configuration options
5658** ---------------------
5659**
5660** SQLITE_PREFER_PROXY_LOCKING
5661**
5662** Database files accessed on non-local file systems are
5663** automatically configured for proxy locking, lock files are
5664** named automatically using the same logic as
5665** PRAGMA lock_proxy_file=":auto:"
5666**
5667** SQLITE_PROXY_DEBUG
5668**
5669** Enables the logging of error messages during host id file
5670** retrieval and creation
5671**
drh715ff302008-12-03 22:32:44 +00005672** LOCKPROXYDIR
5673**
5674** Overrides the default directory used for lock proxy files that
5675** are named automatically via the ":auto:" setting
5676**
5677** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5678**
5679** Permissions to use when creating a directory for storing the
5680** lock proxy files, only used when LOCKPROXYDIR is not set.
5681**
5682**
5683** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5684** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5685** force proxy locking to be used for every database file opened, and 0
5686** will force automatic proxy locking to be disabled for all database
5687** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5688** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5689*/
5690
5691/*
5692** Proxy locking is only available on MacOSX
5693*/
drhd2cb50b2009-01-09 21:41:17 +00005694#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005695
drh715ff302008-12-03 22:32:44 +00005696/*
5697** The proxyLockingContext has the path and file structures for the remote
5698** and local proxy files in it
5699*/
5700typedef struct proxyLockingContext proxyLockingContext;
5701struct proxyLockingContext {
5702 unixFile *conchFile; /* Open conch file */
5703 char *conchFilePath; /* Name of the conch file */
5704 unixFile *lockProxy; /* Open proxy lock file */
5705 char *lockProxyPath; /* Name of the proxy lock file */
5706 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005707 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005708 void *oldLockingContext; /* Original lockingcontext to restore on close */
5709 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5710};
5711
drh7ed97b92010-01-20 13:07:21 +00005712/*
5713** The proxy lock file path for the database at dbPath is written into lPath,
5714** which must point to valid, writable memory large enough for a maxLen length
5715** file path.
drh715ff302008-12-03 22:32:44 +00005716*/
drh715ff302008-12-03 22:32:44 +00005717static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5718 int len;
5719 int dbLen;
5720 int i;
5721
5722#ifdef LOCKPROXYDIR
5723 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5724#else
5725# ifdef _CS_DARWIN_USER_TEMP_DIR
5726 {
drh7ed97b92010-01-20 13:07:21 +00005727 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005728 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5729 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005730 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005731 }
drh7ed97b92010-01-20 13:07:21 +00005732 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005733 }
5734# else
5735 len = strlcpy(lPath, "/tmp/", maxLen);
5736# endif
5737#endif
5738
5739 if( lPath[len-1]!='/' ){
5740 len = strlcat(lPath, "/", maxLen);
5741 }
5742
5743 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005744 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005745 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005746 char c = dbPath[i];
5747 lPath[i+len] = (c=='/')?'_':c;
5748 }
5749 lPath[i+len]='\0';
5750 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005751 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005752 return SQLITE_OK;
5753}
5754
drh7ed97b92010-01-20 13:07:21 +00005755/*
5756 ** Creates the lock file and any missing directories in lockPath
5757 */
5758static int proxyCreateLockPath(const char *lockPath){
5759 int i, len;
5760 char buf[MAXPATHLEN];
5761 int start = 0;
5762
5763 assert(lockPath!=NULL);
5764 /* try to create all the intermediate directories */
5765 len = (int)strlen(lockPath);
5766 buf[0] = lockPath[0];
5767 for( i=1; i<len; i++ ){
5768 if( lockPath[i] == '/' && (i - start > 0) ){
5769 /* only mkdir if leaf dir != "." or "/" or ".." */
5770 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5771 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5772 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005773 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005774 int err=errno;
5775 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005776 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005777 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005778 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005779 return err;
5780 }
5781 }
5782 }
5783 start=i+1;
5784 }
5785 buf[i] = lockPath[i];
5786 }
drh308c2a52010-05-14 11:30:18 +00005787 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005788 return 0;
5789}
5790
drh715ff302008-12-03 22:32:44 +00005791/*
5792** Create a new VFS file descriptor (stored in memory obtained from
5793** sqlite3_malloc) and open the file named "path" in the file descriptor.
5794**
5795** The caller is responsible not only for closing the file descriptor
5796** but also for freeing the memory associated with the file descriptor.
5797*/
drh7ed97b92010-01-20 13:07:21 +00005798static int proxyCreateUnixFile(
5799 const char *path, /* path for the new unixFile */
5800 unixFile **ppFile, /* unixFile created and returned by ref */
5801 int islockfile /* if non zero missing dirs will be created */
5802) {
5803 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005804 unixFile *pNew;
5805 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005806 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005807 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005808 int terrno = 0;
5809 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005810
drh7ed97b92010-01-20 13:07:21 +00005811 /* 1. first try to open/create the file
5812 ** 2. if that fails, and this is a lock file (not-conch), try creating
5813 ** the parent directories and then try again.
5814 ** 3. if that fails, try to open the file read-only
5815 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5816 */
5817 pUnused = findReusableFd(path, openFlags);
5818 if( pUnused ){
5819 fd = pUnused->fd;
5820 }else{
5821 pUnused = sqlite3_malloc(sizeof(*pUnused));
5822 if( !pUnused ){
5823 return SQLITE_NOMEM;
5824 }
5825 }
5826 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005827 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005828 terrno = errno;
5829 if( fd<0 && errno==ENOENT && islockfile ){
5830 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005831 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005832 }
5833 }
5834 }
5835 if( fd<0 ){
5836 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005837 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005838 terrno = errno;
5839 }
5840 if( fd<0 ){
5841 if( islockfile ){
5842 return SQLITE_BUSY;
5843 }
5844 switch (terrno) {
5845 case EACCES:
5846 return SQLITE_PERM;
5847 case EIO:
5848 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5849 default:
drh9978c972010-02-23 17:36:32 +00005850 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005851 }
5852 }
5853
5854 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5855 if( pNew==NULL ){
5856 rc = SQLITE_NOMEM;
5857 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005858 }
5859 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005860 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005861 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005862 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005863 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005864 pUnused->fd = fd;
5865 pUnused->flags = openFlags;
5866 pNew->pUnused = pUnused;
5867
drh0059eae2011-08-08 23:48:40 +00005868 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005869 if( rc==SQLITE_OK ){
5870 *ppFile = pNew;
5871 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005872 }
drh7ed97b92010-01-20 13:07:21 +00005873end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005874 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005875 sqlite3_free(pNew);
5876 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005877 return rc;
5878}
5879
drh7ed97b92010-01-20 13:07:21 +00005880#ifdef SQLITE_TEST
5881/* simulate multiple hosts by creating unique hostid file paths */
5882int sqlite3_hostid_num = 0;
5883#endif
5884
5885#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5886
drh0ab216a2010-07-02 17:10:40 +00005887/* Not always defined in the headers as it ought to be */
5888extern int gethostuuid(uuid_t id, const struct timespec *wait);
5889
drh7ed97b92010-01-20 13:07:21 +00005890/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5891** bytes of writable memory.
5892*/
5893static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005894 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5895 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005896#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5897 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005898 {
5899 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5900 if( gethostuuid(pHostID, &timeout) ){
5901 int err = errno;
5902 if( pError ){
5903 *pError = err;
5904 }
5905 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005906 }
drh7ed97b92010-01-20 13:07:21 +00005907 }
drh3d4435b2011-08-26 20:55:50 +00005908#else
5909 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005910#endif
drh7ed97b92010-01-20 13:07:21 +00005911#ifdef SQLITE_TEST
5912 /* simulate multiple hosts by creating unique hostid file paths */
5913 if( sqlite3_hostid_num != 0){
5914 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5915 }
5916#endif
5917
5918 return SQLITE_OK;
5919}
5920
5921/* The conch file contains the header, host id and lock file path
5922 */
5923#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5924#define PROXY_HEADERLEN 1 /* conch file header length */
5925#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5926#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5927
5928/*
5929** Takes an open conch file, copies the contents to a new path and then moves
5930** it back. The newly created file's file descriptor is assigned to the
5931** conch file structure and finally the original conch file descriptor is
5932** closed. Returns zero if successful.
5933*/
5934static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5935 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5936 unixFile *conchFile = pCtx->conchFile;
5937 char tPath[MAXPATHLEN];
5938 char buf[PROXY_MAXCONCHLEN];
5939 char *cPath = pCtx->conchFilePath;
5940 size_t readLen = 0;
5941 size_t pathLen = 0;
5942 char errmsg[64] = "";
5943 int fd = -1;
5944 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005945 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005946
5947 /* create a new path by replace the trailing '-conch' with '-break' */
5948 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5949 if( pathLen>MAXPATHLEN || pathLen<6 ||
5950 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005951 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005952 goto end_breaklock;
5953 }
5954 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005955 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005956 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005957 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005958 goto end_breaklock;
5959 }
5960 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005961 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5962 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005963 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005964 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005965 goto end_breaklock;
5966 }
drhe562be52011-03-02 18:01:10 +00005967 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005968 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005969 goto end_breaklock;
5970 }
5971 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005972 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005973 goto end_breaklock;
5974 }
5975 rc = 0;
5976 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005977 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005978 conchFile->h = fd;
5979 conchFile->openFlags = O_RDWR | O_CREAT;
5980
5981end_breaklock:
5982 if( rc ){
5983 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005984 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005985 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005986 }
5987 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5988 }
5989 return rc;
5990}
5991
5992/* Take the requested lock on the conch file and break a stale lock if the
5993** host id matches.
5994*/
5995static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5996 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5997 unixFile *conchFile = pCtx->conchFile;
5998 int rc = SQLITE_OK;
5999 int nTries = 0;
6000 struct timespec conchModTime;
6001
drh3d4435b2011-08-26 20:55:50 +00006002 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006003 do {
6004 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6005 nTries ++;
6006 if( rc==SQLITE_BUSY ){
6007 /* If the lock failed (busy):
6008 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6009 * 2nd try: fail if the mod time changed or host id is different, wait
6010 * 10 sec and try again
6011 * 3rd try: break the lock unless the mod time has changed.
6012 */
6013 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006014 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006015 pFile->lastErrno = errno;
6016 return SQLITE_IOERR_LOCK;
6017 }
6018
6019 if( nTries==1 ){
6020 conchModTime = buf.st_mtimespec;
6021 usleep(500000); /* wait 0.5 sec and try the lock again*/
6022 continue;
6023 }
6024
6025 assert( nTries>1 );
6026 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6027 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6028 return SQLITE_BUSY;
6029 }
6030
6031 if( nTries==2 ){
6032 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006033 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006034 if( len<0 ){
6035 pFile->lastErrno = errno;
6036 return SQLITE_IOERR_LOCK;
6037 }
6038 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6039 /* don't break the lock if the host id doesn't match */
6040 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6041 return SQLITE_BUSY;
6042 }
6043 }else{
6044 /* don't break the lock on short read or a version mismatch */
6045 return SQLITE_BUSY;
6046 }
6047 usleep(10000000); /* wait 10 sec and try the lock again */
6048 continue;
6049 }
6050
6051 assert( nTries==3 );
6052 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6053 rc = SQLITE_OK;
6054 if( lockType==EXCLUSIVE_LOCK ){
6055 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6056 }
6057 if( !rc ){
6058 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6059 }
6060 }
6061 }
6062 } while( rc==SQLITE_BUSY && nTries<3 );
6063
6064 return rc;
6065}
6066
6067/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006068** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6069** lockPath means that the lockPath in the conch file will be used if the
6070** host IDs match, or a new lock path will be generated automatically
6071** and written to the conch file.
6072*/
6073static int proxyTakeConch(unixFile *pFile){
6074 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6075
drh7ed97b92010-01-20 13:07:21 +00006076 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006077 return SQLITE_OK;
6078 }else{
6079 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006080 uuid_t myHostID;
6081 int pError = 0;
6082 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006083 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006084 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006085 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006086 int createConch = 0;
6087 int hostIdMatch = 0;
6088 int readLen = 0;
6089 int tryOldLockPath = 0;
6090 int forceNewLockPath = 0;
6091
drh308c2a52010-05-14 11:30:18 +00006092 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6093 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006094
drh7ed97b92010-01-20 13:07:21 +00006095 rc = proxyGetHostID(myHostID, &pError);
6096 if( (rc&0xff)==SQLITE_IOERR ){
6097 pFile->lastErrno = pError;
6098 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006099 }
drh7ed97b92010-01-20 13:07:21 +00006100 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006101 if( rc!=SQLITE_OK ){
6102 goto end_takeconch;
6103 }
drh7ed97b92010-01-20 13:07:21 +00006104 /* read the existing conch file */
6105 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6106 if( readLen<0 ){
6107 /* I/O error: lastErrno set by seekAndRead */
6108 pFile->lastErrno = conchFile->lastErrno;
6109 rc = SQLITE_IOERR_READ;
6110 goto end_takeconch;
6111 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6112 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6113 /* a short read or version format mismatch means we need to create a new
6114 ** conch file.
6115 */
6116 createConch = 1;
6117 }
6118 /* if the host id matches and the lock path already exists in the conch
6119 ** we'll try to use the path there, if we can't open that path, we'll
6120 ** retry with a new auto-generated path
6121 */
6122 do { /* in case we need to try again for an :auto: named lock file */
6123
6124 if( !createConch && !forceNewLockPath ){
6125 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6126 PROXY_HOSTIDLEN);
6127 /* if the conch has data compare the contents */
6128 if( !pCtx->lockProxyPath ){
6129 /* for auto-named local lock file, just check the host ID and we'll
6130 ** use the local lock file path that's already in there
6131 */
6132 if( hostIdMatch ){
6133 size_t pathLen = (readLen - PROXY_PATHINDEX);
6134
6135 if( pathLen>=MAXPATHLEN ){
6136 pathLen=MAXPATHLEN-1;
6137 }
6138 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6139 lockPath[pathLen] = 0;
6140 tempLockPath = lockPath;
6141 tryOldLockPath = 1;
6142 /* create a copy of the lock path if the conch is taken */
6143 goto end_takeconch;
6144 }
6145 }else if( hostIdMatch
6146 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6147 readLen-PROXY_PATHINDEX)
6148 ){
6149 /* conch host and lock path match */
6150 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006151 }
drh7ed97b92010-01-20 13:07:21 +00006152 }
6153
6154 /* if the conch isn't writable and doesn't match, we can't take it */
6155 if( (conchFile->openFlags&O_RDWR) == 0 ){
6156 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006157 goto end_takeconch;
6158 }
drh7ed97b92010-01-20 13:07:21 +00006159
6160 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006161 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006162 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6163 tempLockPath = lockPath;
6164 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006165 }
drh7ed97b92010-01-20 13:07:21 +00006166
6167 /* update conch with host and path (this will fail if other process
6168 ** has a shared lock already), if the host id matches, use the big
6169 ** stick.
drh715ff302008-12-03 22:32:44 +00006170 */
drh7ed97b92010-01-20 13:07:21 +00006171 futimes(conchFile->h, NULL);
6172 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006173 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006174 /* We are trying for an exclusive lock but another thread in this
6175 ** same process is still holding a shared lock. */
6176 rc = SQLITE_BUSY;
6177 } else {
6178 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006179 }
drh715ff302008-12-03 22:32:44 +00006180 }else{
drh7ed97b92010-01-20 13:07:21 +00006181 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006182 }
drh7ed97b92010-01-20 13:07:21 +00006183 if( rc==SQLITE_OK ){
6184 char writeBuffer[PROXY_MAXCONCHLEN];
6185 int writeSize = 0;
6186
6187 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6188 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6189 if( pCtx->lockProxyPath!=NULL ){
6190 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6191 }else{
6192 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6193 }
6194 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006195 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006196 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6197 fsync(conchFile->h);
6198 /* If we created a new conch file (not just updated the contents of a
6199 ** valid conch file), try to match the permissions of the database
6200 */
6201 if( rc==SQLITE_OK && createConch ){
6202 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006203 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006204 if( err==0 ){
6205 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6206 S_IROTH|S_IWOTH);
6207 /* try to match the database file R/W permissions, ignore failure */
6208#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006209 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006210#else
drhff812312011-02-23 13:33:46 +00006211 do{
drhe562be52011-03-02 18:01:10 +00006212 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006213 }while( rc==(-1) && errno==EINTR );
6214 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006215 int code = errno;
6216 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6217 cmode, code, strerror(code));
6218 } else {
6219 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6220 }
6221 }else{
6222 int code = errno;
6223 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6224 err, code, strerror(code));
6225#endif
6226 }
drh715ff302008-12-03 22:32:44 +00006227 }
6228 }
drh7ed97b92010-01-20 13:07:21 +00006229 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6230
6231 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006232 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006233 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006234 int fd;
drh7ed97b92010-01-20 13:07:21 +00006235 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006236 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006237 }
6238 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006239 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006240 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006241 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006242 if( fd>=0 ){
6243 pFile->h = fd;
6244 }else{
drh9978c972010-02-23 17:36:32 +00006245 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006246 during locking */
6247 }
6248 }
6249 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6250 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6251 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6252 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6253 /* we couldn't create the proxy lock file with the old lock file path
6254 ** so try again via auto-naming
6255 */
6256 forceNewLockPath = 1;
6257 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006258 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006259 }
6260 }
6261 if( rc==SQLITE_OK ){
6262 /* Need to make a copy of path if we extracted the value
6263 ** from the conch file or the path was allocated on the stack
6264 */
6265 if( tempLockPath ){
6266 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6267 if( !pCtx->lockProxyPath ){
6268 rc = SQLITE_NOMEM;
6269 }
6270 }
6271 }
6272 if( rc==SQLITE_OK ){
6273 pCtx->conchHeld = 1;
6274
6275 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6276 afpLockingContext *afpCtx;
6277 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6278 afpCtx->dbPath = pCtx->lockProxyPath;
6279 }
6280 } else {
6281 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6282 }
drh308c2a52010-05-14 11:30:18 +00006283 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6284 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006285 return rc;
drh308c2a52010-05-14 11:30:18 +00006286 } while (1); /* in case we need to retry the :auto: lock file -
6287 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006288 }
6289}
6290
6291/*
6292** If pFile holds a lock on a conch file, then release that lock.
6293*/
6294static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006295 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006296 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6297 unixFile *conchFile; /* Name of the conch file */
6298
6299 pCtx = (proxyLockingContext *)pFile->lockingContext;
6300 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006301 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006302 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006303 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006304 if( pCtx->conchHeld>0 ){
6305 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6306 }
drh715ff302008-12-03 22:32:44 +00006307 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006308 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6309 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006310 return rc;
6311}
6312
6313/*
6314** Given the name of a database file, compute the name of its conch file.
6315** Store the conch filename in memory obtained from sqlite3_malloc().
6316** Make *pConchPath point to the new name. Return SQLITE_OK on success
6317** or SQLITE_NOMEM if unable to obtain memory.
6318**
6319** The caller is responsible for ensuring that the allocated memory
6320** space is eventually freed.
6321**
6322** *pConchPath is set to NULL if a memory allocation error occurs.
6323*/
6324static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6325 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006326 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006327 char *conchPath; /* buffer in which to construct conch name */
6328
6329 /* Allocate space for the conch filename and initialize the name to
6330 ** the name of the original database file. */
6331 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6332 if( conchPath==0 ){
6333 return SQLITE_NOMEM;
6334 }
6335 memcpy(conchPath, dbPath, len+1);
6336
6337 /* now insert a "." before the last / character */
6338 for( i=(len-1); i>=0; i-- ){
6339 if( conchPath[i]=='/' ){
6340 i++;
6341 break;
6342 }
6343 }
6344 conchPath[i]='.';
6345 while ( i<len ){
6346 conchPath[i+1]=dbPath[i];
6347 i++;
6348 }
6349
6350 /* append the "-conch" suffix to the file */
6351 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006352 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006353
6354 return SQLITE_OK;
6355}
6356
6357
6358/* Takes a fully configured proxy locking-style unix file and switches
6359** the local lock file path
6360*/
6361static int switchLockProxyPath(unixFile *pFile, const char *path) {
6362 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6363 char *oldPath = pCtx->lockProxyPath;
6364 int rc = SQLITE_OK;
6365
drh308c2a52010-05-14 11:30:18 +00006366 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006367 return SQLITE_BUSY;
6368 }
6369
6370 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6371 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6372 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6373 return SQLITE_OK;
6374 }else{
6375 unixFile *lockProxy = pCtx->lockProxy;
6376 pCtx->lockProxy=NULL;
6377 pCtx->conchHeld = 0;
6378 if( lockProxy!=NULL ){
6379 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6380 if( rc ) return rc;
6381 sqlite3_free(lockProxy);
6382 }
6383 sqlite3_free(oldPath);
6384 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6385 }
6386
6387 return rc;
6388}
6389
6390/*
6391** pFile is a file that has been opened by a prior xOpen call. dbPath
6392** is a string buffer at least MAXPATHLEN+1 characters in size.
6393**
6394** This routine find the filename associated with pFile and writes it
6395** int dbPath.
6396*/
6397static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006398#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006399 if( pFile->pMethod == &afpIoMethods ){
6400 /* afp style keeps a reference to the db path in the filePath field
6401 ** of the struct */
drhea678832008-12-10 19:26:22 +00006402 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006403 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6404 } else
drh715ff302008-12-03 22:32:44 +00006405#endif
6406 if( pFile->pMethod == &dotlockIoMethods ){
6407 /* dot lock style uses the locking context to store the dot lock
6408 ** file path */
6409 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6410 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6411 }else{
6412 /* all other styles use the locking context to store the db file path */
6413 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006414 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006415 }
6416 return SQLITE_OK;
6417}
6418
6419/*
6420** Takes an already filled in unix file and alters it so all file locking
6421** will be performed on the local proxy lock file. The following fields
6422** are preserved in the locking context so that they can be restored and
6423** the unix structure properly cleaned up at close time:
6424** ->lockingContext
6425** ->pMethod
6426*/
6427static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6428 proxyLockingContext *pCtx;
6429 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6430 char *lockPath=NULL;
6431 int rc = SQLITE_OK;
6432
drh308c2a52010-05-14 11:30:18 +00006433 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006434 return SQLITE_BUSY;
6435 }
6436 proxyGetDbPathForUnixFile(pFile, dbPath);
6437 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6438 lockPath=NULL;
6439 }else{
6440 lockPath=(char *)path;
6441 }
6442
drh308c2a52010-05-14 11:30:18 +00006443 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6444 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006445
6446 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6447 if( pCtx==0 ){
6448 return SQLITE_NOMEM;
6449 }
6450 memset(pCtx, 0, sizeof(*pCtx));
6451
6452 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6453 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006454 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6455 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6456 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6457 ** (c) the file system is read-only, then enable no-locking access.
6458 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6459 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6460 */
6461 struct statfs fsInfo;
6462 struct stat conchInfo;
6463 int goLockless = 0;
6464
drh99ab3b12011-03-02 15:09:07 +00006465 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006466 int err = errno;
6467 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6468 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6469 }
6470 }
6471 if( goLockless ){
6472 pCtx->conchHeld = -1; /* read only FS/ lockless */
6473 rc = SQLITE_OK;
6474 }
6475 }
drh715ff302008-12-03 22:32:44 +00006476 }
6477 if( rc==SQLITE_OK && lockPath ){
6478 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6479 }
6480
6481 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006482 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6483 if( pCtx->dbPath==NULL ){
6484 rc = SQLITE_NOMEM;
6485 }
6486 }
6487 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006488 /* all memory is allocated, proxys are created and assigned,
6489 ** switch the locking context and pMethod then return.
6490 */
drh715ff302008-12-03 22:32:44 +00006491 pCtx->oldLockingContext = pFile->lockingContext;
6492 pFile->lockingContext = pCtx;
6493 pCtx->pOldMethod = pFile->pMethod;
6494 pFile->pMethod = &proxyIoMethods;
6495 }else{
6496 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006497 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006498 sqlite3_free(pCtx->conchFile);
6499 }
drhd56b1212010-08-11 06:14:15 +00006500 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006501 sqlite3_free(pCtx->conchFilePath);
6502 sqlite3_free(pCtx);
6503 }
drh308c2a52010-05-14 11:30:18 +00006504 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6505 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006506 return rc;
6507}
6508
6509
6510/*
6511** This routine handles sqlite3_file_control() calls that are specific
6512** to proxy locking.
6513*/
6514static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6515 switch( op ){
6516 case SQLITE_GET_LOCKPROXYFILE: {
6517 unixFile *pFile = (unixFile*)id;
6518 if( pFile->pMethod == &proxyIoMethods ){
6519 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6520 proxyTakeConch(pFile);
6521 if( pCtx->lockProxyPath ){
6522 *(const char **)pArg = pCtx->lockProxyPath;
6523 }else{
6524 *(const char **)pArg = ":auto: (not held)";
6525 }
6526 } else {
6527 *(const char **)pArg = NULL;
6528 }
6529 return SQLITE_OK;
6530 }
6531 case SQLITE_SET_LOCKPROXYFILE: {
6532 unixFile *pFile = (unixFile*)id;
6533 int rc = SQLITE_OK;
6534 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6535 if( pArg==NULL || (const char *)pArg==0 ){
6536 if( isProxyStyle ){
6537 /* turn off proxy locking - not supported */
6538 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6539 }else{
6540 /* turn off proxy locking - already off - NOOP */
6541 rc = SQLITE_OK;
6542 }
6543 }else{
6544 const char *proxyPath = (const char *)pArg;
6545 if( isProxyStyle ){
6546 proxyLockingContext *pCtx =
6547 (proxyLockingContext*)pFile->lockingContext;
6548 if( !strcmp(pArg, ":auto:")
6549 || (pCtx->lockProxyPath &&
6550 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6551 ){
6552 rc = SQLITE_OK;
6553 }else{
6554 rc = switchLockProxyPath(pFile, proxyPath);
6555 }
6556 }else{
6557 /* turn on proxy file locking */
6558 rc = proxyTransformUnixFile(pFile, proxyPath);
6559 }
6560 }
6561 return rc;
6562 }
6563 default: {
6564 assert( 0 ); /* The call assures that only valid opcodes are sent */
6565 }
6566 }
6567 /*NOTREACHED*/
6568 return SQLITE_ERROR;
6569}
6570
6571/*
6572** Within this division (the proxying locking implementation) the procedures
6573** above this point are all utilities. The lock-related methods of the
6574** proxy-locking sqlite3_io_method object follow.
6575*/
6576
6577
6578/*
6579** This routine checks if there is a RESERVED lock held on the specified
6580** file by this or any other process. If such a lock is held, set *pResOut
6581** to a non-zero value otherwise *pResOut is set to zero. The return value
6582** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6583*/
6584static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6585 unixFile *pFile = (unixFile*)id;
6586 int rc = proxyTakeConch(pFile);
6587 if( rc==SQLITE_OK ){
6588 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006589 if( pCtx->conchHeld>0 ){
6590 unixFile *proxy = pCtx->lockProxy;
6591 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6592 }else{ /* conchHeld < 0 is lockless */
6593 pResOut=0;
6594 }
drh715ff302008-12-03 22:32:44 +00006595 }
6596 return rc;
6597}
6598
6599/*
drh308c2a52010-05-14 11:30:18 +00006600** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006601** of the following:
6602**
6603** (1) SHARED_LOCK
6604** (2) RESERVED_LOCK
6605** (3) PENDING_LOCK
6606** (4) EXCLUSIVE_LOCK
6607**
6608** Sometimes when requesting one lock state, additional lock states
6609** are inserted in between. The locking might fail on one of the later
6610** transitions leaving the lock state different from what it started but
6611** still short of its goal. The following chart shows the allowed
6612** transitions and the inserted intermediate states:
6613**
6614** UNLOCKED -> SHARED
6615** SHARED -> RESERVED
6616** SHARED -> (PENDING) -> EXCLUSIVE
6617** RESERVED -> (PENDING) -> EXCLUSIVE
6618** PENDING -> EXCLUSIVE
6619**
6620** This routine will only increase a lock. Use the sqlite3OsUnlock()
6621** routine to lower a locking level.
6622*/
drh308c2a52010-05-14 11:30:18 +00006623static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006624 unixFile *pFile = (unixFile*)id;
6625 int rc = proxyTakeConch(pFile);
6626 if( rc==SQLITE_OK ){
6627 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006628 if( pCtx->conchHeld>0 ){
6629 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006630 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6631 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006632 }else{
6633 /* conchHeld < 0 is lockless */
6634 }
drh715ff302008-12-03 22:32:44 +00006635 }
6636 return rc;
6637}
6638
6639
6640/*
drh308c2a52010-05-14 11:30:18 +00006641** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006642** must be either NO_LOCK or SHARED_LOCK.
6643**
6644** If the locking level of the file descriptor is already at or below
6645** the requested locking level, this routine is a no-op.
6646*/
drh308c2a52010-05-14 11:30:18 +00006647static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006648 unixFile *pFile = (unixFile*)id;
6649 int rc = proxyTakeConch(pFile);
6650 if( rc==SQLITE_OK ){
6651 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006652 if( pCtx->conchHeld>0 ){
6653 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006654 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6655 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006656 }else{
6657 /* conchHeld < 0 is lockless */
6658 }
drh715ff302008-12-03 22:32:44 +00006659 }
6660 return rc;
6661}
6662
6663/*
6664** Close a file that uses proxy locks.
6665*/
6666static int proxyClose(sqlite3_file *id) {
6667 if( id ){
6668 unixFile *pFile = (unixFile*)id;
6669 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6670 unixFile *lockProxy = pCtx->lockProxy;
6671 unixFile *conchFile = pCtx->conchFile;
6672 int rc = SQLITE_OK;
6673
6674 if( lockProxy ){
6675 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6676 if( rc ) return rc;
6677 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6678 if( rc ) return rc;
6679 sqlite3_free(lockProxy);
6680 pCtx->lockProxy = 0;
6681 }
6682 if( conchFile ){
6683 if( pCtx->conchHeld ){
6684 rc = proxyReleaseConch(pFile);
6685 if( rc ) return rc;
6686 }
6687 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6688 if( rc ) return rc;
6689 sqlite3_free(conchFile);
6690 }
drhd56b1212010-08-11 06:14:15 +00006691 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006692 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006693 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006694 /* restore the original locking context and pMethod then close it */
6695 pFile->lockingContext = pCtx->oldLockingContext;
6696 pFile->pMethod = pCtx->pOldMethod;
6697 sqlite3_free(pCtx);
6698 return pFile->pMethod->xClose(id);
6699 }
6700 return SQLITE_OK;
6701}
6702
6703
6704
drhd2cb50b2009-01-09 21:41:17 +00006705#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006706/*
6707** The proxy locking style is intended for use with AFP filesystems.
6708** And since AFP is only supported on MacOSX, the proxy locking is also
6709** restricted to MacOSX.
6710**
6711**
6712******************* End of the proxy lock implementation **********************
6713******************************************************************************/
6714
drh734c9862008-11-28 15:37:20 +00006715/*
danielk1977e339d652008-06-28 11:23:00 +00006716** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006717**
6718** This routine registers all VFS implementations for unix-like operating
6719** systems. This routine, and the sqlite3_os_end() routine that follows,
6720** should be the only routines in this file that are visible from other
6721** files.
drh6b9d6dd2008-12-03 19:34:47 +00006722**
6723** This routine is called once during SQLite initialization and by a
6724** single thread. The memory allocation and mutex subsystems have not
6725** necessarily been initialized when this routine is called, and so they
6726** should not be used.
drh153c62c2007-08-24 03:51:33 +00006727*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006728int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006729 /*
6730 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006731 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6732 ** to the "finder" function. (pAppData is a pointer to a pointer because
6733 ** silly C90 rules prohibit a void* from being cast to a function pointer
6734 ** and so we have to go through the intermediate pointer to avoid problems
6735 ** when compiling with -pedantic-errors on GCC.)
6736 **
6737 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006738 ** finder-function. The finder-function returns a pointer to the
6739 ** sqlite_io_methods object that implements the desired locking
6740 ** behaviors. See the division above that contains the IOMETHODS
6741 ** macro for addition information on finder-functions.
6742 **
6743 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6744 ** object. But the "autolockIoFinder" available on MacOSX does a little
6745 ** more than that; it looks at the filesystem type that hosts the
6746 ** database file and tries to choose an locking method appropriate for
6747 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006748 */
drh7708e972008-11-29 00:56:52 +00006749 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006750 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006751 sizeof(unixFile), /* szOsFile */ \
6752 MAX_PATHNAME, /* mxPathname */ \
6753 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006754 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006755 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006756 unixOpen, /* xOpen */ \
6757 unixDelete, /* xDelete */ \
6758 unixAccess, /* xAccess */ \
6759 unixFullPathname, /* xFullPathname */ \
6760 unixDlOpen, /* xDlOpen */ \
6761 unixDlError, /* xDlError */ \
6762 unixDlSym, /* xDlSym */ \
6763 unixDlClose, /* xDlClose */ \
6764 unixRandomness, /* xRandomness */ \
6765 unixSleep, /* xSleep */ \
6766 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006767 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006768 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006769 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006770 unixGetSystemCall, /* xGetSystemCall */ \
6771 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006772 }
6773
drh6b9d6dd2008-12-03 19:34:47 +00006774 /*
6775 ** All default VFSes for unix are contained in the following array.
6776 **
6777 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6778 ** by the SQLite core when the VFS is registered. So the following
6779 ** array cannot be const.
6780 */
danielk1977e339d652008-06-28 11:23:00 +00006781 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006782#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006783 UNIXVFS("unix", autolockIoFinder ),
6784#else
6785 UNIXVFS("unix", posixIoFinder ),
6786#endif
6787 UNIXVFS("unix-none", nolockIoFinder ),
6788 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006789 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006790#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006791 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006792#endif
6793#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006794 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006795#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006796 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006797#endif
chw78a13182009-04-07 05:35:03 +00006798#endif
drhd2cb50b2009-01-09 21:41:17 +00006799#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006800 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006801 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006802 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006803#endif
drh153c62c2007-08-24 03:51:33 +00006804 };
drh6b9d6dd2008-12-03 19:34:47 +00006805 unsigned int i; /* Loop counter */
6806
drh2aa5a002011-04-13 13:42:25 +00006807 /* Double-check that the aSyscall[] array has been constructed
6808 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8942d412012-01-02 18:20:14 +00006809 assert( ArraySize(aSyscall)==20 );
drh2aa5a002011-04-13 13:42:25 +00006810
drh6b9d6dd2008-12-03 19:34:47 +00006811 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006812 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006813 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006814 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006815 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006816}
danielk1977e339d652008-06-28 11:23:00 +00006817
6818/*
drh6b9d6dd2008-12-03 19:34:47 +00006819** Shutdown the operating system interface.
6820**
6821** Some operating systems might need to do some cleanup in this routine,
6822** to release dynamically allocated objects. But not on unix.
6823** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006824*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006825int sqlite3_os_end(void){
6826 return SQLITE_OK;
6827}
drhdce8bdb2007-08-16 13:01:44 +00006828
danielk197729bafea2008-06-26 10:41:19 +00006829#endif /* SQLITE_OS_UNIX */