blob: 9a3cdfb9bb461095c38387117049326f635cd72d [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__) */
drh9e33c2c2007-08-31 18:34:59 +00003573 }
drh0b52b7d2011-01-26 19:46:22 +00003574 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003575}
3576
3577/*
danielk1977a3d4c882007-03-23 10:08:38 +00003578** Return the sector size in bytes of the underlying block device for
3579** the specified file. This is almost always 512 bytes, but may be
3580** larger for some devices.
3581**
3582** SQLite code assumes this function cannot fail. It also assumes that
3583** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003584** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003585** same for both.
3586*/
drh1da88f02011-12-17 16:09:16 +00003587static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003588 (void)pFile;
3589 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003590}
3591
danielk197790949c22007-08-17 16:50:38 +00003592/*
drhf12b3f62011-12-21 14:42:29 +00003593** Return the device characteristics for the file.
3594**
drhcb15f352011-12-23 01:04:17 +00003595** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3596** However, that choice is contraversial since technically the underlying
3597** file system does not always provide powersafe overwrites. (In other
3598** words, after a power-loss event, parts of the file that were never
3599** written might end up being altered.) However, non-PSOW behavior is very,
3600** very rare. And asserting PSOW makes a large reduction in the amount
3601** of required I/O for journaling, since a lot of padding is eliminated.
3602** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3603** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003604*/
drhf12b3f62011-12-21 14:42:29 +00003605static int unixDeviceCharacteristics(sqlite3_file *id){
3606 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003607 if( p->ctrlFlags & UNIXFILE_PSOW ){
3608 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3609 }else{
3610 return 0;
3611 }
danielk197762079062007-08-15 17:08:46 +00003612}
3613
drhd9e5c4f2010-05-12 18:01:39 +00003614#ifndef SQLITE_OMIT_WAL
3615
3616
3617/*
drhd91c68f2010-05-14 14:52:25 +00003618** Object used to represent an shared memory buffer.
3619**
3620** When multiple threads all reference the same wal-index, each thread
3621** has its own unixShm object, but they all point to a single instance
3622** of this unixShmNode object. In other words, each wal-index is opened
3623** only once per process.
3624**
3625** Each unixShmNode object is connected to a single unixInodeInfo object.
3626** We could coalesce this object into unixInodeInfo, but that would mean
3627** every open file that does not use shared memory (in other words, most
3628** open files) would have to carry around this extra information. So
3629** the unixInodeInfo object contains a pointer to this unixShmNode object
3630** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003631**
3632** unixMutexHeld() must be true when creating or destroying
3633** this object or while reading or writing the following fields:
3634**
3635** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003636**
3637** The following fields are read-only after the object is created:
3638**
3639** fid
3640** zFilename
3641**
drhd91c68f2010-05-14 14:52:25 +00003642** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003643** unixMutexHeld() is true when reading or writing any other field
3644** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003645*/
drhd91c68f2010-05-14 14:52:25 +00003646struct unixShmNode {
3647 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003648 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003649 char *zFilename; /* Name of the mmapped file */
3650 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003651 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003652 u16 nRegion; /* Size of array apRegion */
3653 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003654 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003655 int nRef; /* Number of unixShm objects pointing to this */
3656 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003657#ifdef SQLITE_DEBUG
3658 u8 exclMask; /* Mask of exclusive locks held */
3659 u8 sharedMask; /* Mask of shared locks held */
3660 u8 nextShmId; /* Next available unixShm.id value */
3661#endif
3662};
3663
3664/*
drhd9e5c4f2010-05-12 18:01:39 +00003665** Structure used internally by this VFS to record the state of an
3666** open shared memory connection.
3667**
drhd91c68f2010-05-14 14:52:25 +00003668** The following fields are initialized when this object is created and
3669** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003670**
drhd91c68f2010-05-14 14:52:25 +00003671** unixShm.pFile
3672** unixShm.id
3673**
3674** All other fields are read/write. The unixShm.pFile->mutex must be held
3675** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003676*/
3677struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003678 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3679 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003680 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003681 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003682 u16 sharedMask; /* Mask of shared locks held */
3683 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003684};
3685
3686/*
drhd9e5c4f2010-05-12 18:01:39 +00003687** Constants used for locking
3688*/
drhbd9676c2010-06-23 17:58:38 +00003689#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003690#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003691
drhd9e5c4f2010-05-12 18:01:39 +00003692/*
drh73b64e42010-05-30 19:55:15 +00003693** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003694**
3695** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3696** otherwise.
3697*/
3698static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003699 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3700 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003701 int ofst, /* First byte of the locking range */
3702 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003703){
3704 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003705 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003706
drhd91c68f2010-05-14 14:52:25 +00003707 /* Access to the unixShmNode object is serialized by the caller */
3708 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003709
drh73b64e42010-05-30 19:55:15 +00003710 /* Shared locks never span more than one byte */
3711 assert( n==1 || lockType!=F_RDLCK );
3712
3713 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003714 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003715
drh3cb93392011-03-12 18:10:44 +00003716 if( pShmNode->h>=0 ){
3717 /* Initialize the locking parameters */
3718 memset(&f, 0, sizeof(f));
3719 f.l_type = lockType;
3720 f.l_whence = SEEK_SET;
3721 f.l_start = ofst;
3722 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003723
drh3cb93392011-03-12 18:10:44 +00003724 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3725 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3726 }
drhd9e5c4f2010-05-12 18:01:39 +00003727
3728 /* Update the global lock state and do debug tracing */
3729#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003730 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003731 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003732 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003733 if( rc==SQLITE_OK ){
3734 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003735 OSTRACE(("unlock %d ok", ofst));
3736 pShmNode->exclMask &= ~mask;
3737 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003738 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003739 OSTRACE(("read-lock %d ok", ofst));
3740 pShmNode->exclMask &= ~mask;
3741 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003742 }else{
3743 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003744 OSTRACE(("write-lock %d ok", ofst));
3745 pShmNode->exclMask |= mask;
3746 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003747 }
3748 }else{
3749 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003750 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003751 }else if( lockType==F_RDLCK ){
3752 OSTRACE(("read-lock failed"));
3753 }else{
3754 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003755 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003756 }
3757 }
drh20e1f082010-05-31 16:10:12 +00003758 OSTRACE((" - afterwards %03x,%03x\n",
3759 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003760 }
drhd9e5c4f2010-05-12 18:01:39 +00003761#endif
3762
3763 return rc;
3764}
3765
drhd9e5c4f2010-05-12 18:01:39 +00003766
3767/*
drhd91c68f2010-05-14 14:52:25 +00003768** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003769**
3770** This is not a VFS shared-memory method; it is a utility function called
3771** by VFS shared-memory methods.
3772*/
drhd91c68f2010-05-14 14:52:25 +00003773static void unixShmPurge(unixFile *pFd){
3774 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003775 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003776 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003777 int i;
drhd91c68f2010-05-14 14:52:25 +00003778 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003779 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003780 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003781 if( p->h>=0 ){
3782 munmap(p->apRegion[i], p->szRegion);
3783 }else{
3784 sqlite3_free(p->apRegion[i]);
3785 }
dan13a3cb82010-06-11 19:04:21 +00003786 }
dan18801912010-06-14 14:07:50 +00003787 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003788 if( p->h>=0 ){
3789 robust_close(pFd, p->h, __LINE__);
3790 p->h = -1;
3791 }
drhd91c68f2010-05-14 14:52:25 +00003792 p->pInode->pShmNode = 0;
3793 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003794 }
3795}
3796
3797/*
danda9fe0c2010-07-13 18:44:03 +00003798** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003799** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003800**
drh7234c6d2010-06-19 15:10:09 +00003801** The file used to implement shared-memory is in the same directory
3802** as the open database file and has the same name as the open database
3803** file with the "-shm" suffix added. For example, if the database file
3804** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003805** for shared memory will be called "/home/user1/config.db-shm".
3806**
3807** Another approach to is to use files in /dev/shm or /dev/tmp or an
3808** some other tmpfs mount. But if a file in a different directory
3809** from the database file is used, then differing access permissions
3810** or a chroot() might cause two different processes on the same
3811** database to end up using different files for shared memory -
3812** meaning that their memory would not really be shared - resulting
3813** in database corruption. Nevertheless, this tmpfs file usage
3814** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3815** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3816** option results in an incompatible build of SQLite; builds of SQLite
3817** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3818** same database file at the same time, database corruption will likely
3819** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3820** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003821**
3822** When opening a new shared-memory file, if no other instances of that
3823** file are currently open, in this process or in other processes, then
3824** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003825**
3826** If the original database file (pDbFd) is using the "unix-excl" VFS
3827** that means that an exclusive lock is held on the database file and
3828** that no other processes are able to read or write the database. In
3829** that case, we do not really need shared memory. No shared memory
3830** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003831*/
danda9fe0c2010-07-13 18:44:03 +00003832static int unixOpenSharedMemory(unixFile *pDbFd){
3833 struct unixShm *p = 0; /* The connection to be opened */
3834 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3835 int rc; /* Result code */
3836 unixInodeInfo *pInode; /* The inode of fd */
3837 char *zShmFilename; /* Name of the file used for SHM */
3838 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003839
danda9fe0c2010-07-13 18:44:03 +00003840 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003841 p = sqlite3_malloc( sizeof(*p) );
3842 if( p==0 ) return SQLITE_NOMEM;
3843 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003844 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003845
danda9fe0c2010-07-13 18:44:03 +00003846 /* Check to see if a unixShmNode object already exists. Reuse an existing
3847 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003848 */
3849 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003850 pInode = pDbFd->pInode;
3851 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003852 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003853 struct stat sStat; /* fstat() info for database file */
3854
3855 /* Call fstat() to figure out the permissions on the database file. If
3856 ** a new *-shm file is created, an attempt will be made to create it
3857 ** with the same permissions. The actual permissions the file is created
3858 ** with are subject to the current umask setting.
3859 */
drh3cb93392011-03-12 18:10:44 +00003860 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003861 rc = SQLITE_IOERR_FSTAT;
3862 goto shm_open_err;
3863 }
3864
drha4ced192010-07-15 18:32:40 +00003865#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003866 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003867#else
drh52bcde02012-01-03 14:50:45 +00003868 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003869#endif
drh7234c6d2010-06-19 15:10:09 +00003870 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003871 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003872 rc = SQLITE_NOMEM;
3873 goto shm_open_err;
3874 }
drhd91c68f2010-05-14 14:52:25 +00003875 memset(pShmNode, 0, sizeof(*pShmNode));
drh7234c6d2010-06-19 15:10:09 +00003876 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003877#ifdef SQLITE_SHM_DIRECTORY
3878 sqlite3_snprintf(nShmFilename, zShmFilename,
3879 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3880 (u32)sStat.st_ino, (u32)sStat.st_dev);
3881#else
drh7234c6d2010-06-19 15:10:09 +00003882 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003883 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003884#endif
drhd91c68f2010-05-14 14:52:25 +00003885 pShmNode->h = -1;
3886 pDbFd->pInode->pShmNode = pShmNode;
3887 pShmNode->pInode = pDbFd->pInode;
3888 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3889 if( pShmNode->mutex==0 ){
3890 rc = SQLITE_NOMEM;
3891 goto shm_open_err;
3892 }
drhd9e5c4f2010-05-12 18:01:39 +00003893
drh3cb93392011-03-12 18:10:44 +00003894 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003895 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003896 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003897 openFlags = O_RDONLY;
3898 pShmNode->isReadonly = 1;
3899 }
3900 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003901 if( pShmNode->h<0 ){
drh66dfec8b2011-06-01 20:01:49 +00003902 if( pShmNode->h<0 ){
3903 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3904 goto shm_open_err;
3905 }
drhd9e5c4f2010-05-12 18:01:39 +00003906 }
drh3cb93392011-03-12 18:10:44 +00003907
3908 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003909 ** If not, truncate the file to zero length.
3910 */
3911 rc = SQLITE_OK;
3912 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3913 if( robust_ftruncate(pShmNode->h, 0) ){
3914 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003915 }
3916 }
drh66dfec8b2011-06-01 20:01:49 +00003917 if( rc==SQLITE_OK ){
3918 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3919 }
3920 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003921 }
drhd9e5c4f2010-05-12 18:01:39 +00003922 }
3923
drhd91c68f2010-05-14 14:52:25 +00003924 /* Make the new connection a child of the unixShmNode */
3925 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003926#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003927 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003928#endif
drhd91c68f2010-05-14 14:52:25 +00003929 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003930 pDbFd->pShm = p;
3931 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003932
3933 /* The reference count on pShmNode has already been incremented under
3934 ** the cover of the unixEnterMutex() mutex and the pointer from the
3935 ** new (struct unixShm) object to the pShmNode has been set. All that is
3936 ** left to do is to link the new object into the linked list starting
3937 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3938 ** mutex.
3939 */
3940 sqlite3_mutex_enter(pShmNode->mutex);
3941 p->pNext = pShmNode->pFirst;
3942 pShmNode->pFirst = p;
3943 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003944 return SQLITE_OK;
3945
3946 /* Jump here on any error */
3947shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003948 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003949 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003950 unixLeaveMutex();
3951 return rc;
3952}
3953
3954/*
danda9fe0c2010-07-13 18:44:03 +00003955** This function is called to obtain a pointer to region iRegion of the
3956** shared-memory associated with the database file fd. Shared-memory regions
3957** are numbered starting from zero. Each shared-memory region is szRegion
3958** bytes in size.
3959**
3960** If an error occurs, an error code is returned and *pp is set to NULL.
3961**
3962** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3963** region has not been allocated (by any client, including one running in a
3964** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3965** bExtend is non-zero and the requested shared-memory region has not yet
3966** been allocated, it is allocated by this function.
3967**
3968** If the shared-memory region has already been allocated or is allocated by
3969** this call as described above, then it is mapped into this processes
3970** address space (if it is not already), *pp is set to point to the mapped
3971** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003972*/
danda9fe0c2010-07-13 18:44:03 +00003973static int unixShmMap(
3974 sqlite3_file *fd, /* Handle open on database file */
3975 int iRegion, /* Region to retrieve */
3976 int szRegion, /* Size of regions */
3977 int bExtend, /* True to extend file if necessary */
3978 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003979){
danda9fe0c2010-07-13 18:44:03 +00003980 unixFile *pDbFd = (unixFile*)fd;
3981 unixShm *p;
3982 unixShmNode *pShmNode;
3983 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003984
danda9fe0c2010-07-13 18:44:03 +00003985 /* If the shared-memory file has not yet been opened, open it now. */
3986 if( pDbFd->pShm==0 ){
3987 rc = unixOpenSharedMemory(pDbFd);
3988 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00003989 }
drhd9e5c4f2010-05-12 18:01:39 +00003990
danda9fe0c2010-07-13 18:44:03 +00003991 p = pDbFd->pShm;
3992 pShmNode = p->pShmNode;
3993 sqlite3_mutex_enter(pShmNode->mutex);
3994 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00003995 assert( pShmNode->pInode==pDbFd->pInode );
3996 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
3997 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00003998
3999 if( pShmNode->nRegion<=iRegion ){
4000 char **apNew; /* New apRegion[] array */
4001 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4002 struct stat sStat; /* Used by fstat() */
4003
4004 pShmNode->szRegion = szRegion;
4005
drh3cb93392011-03-12 18:10:44 +00004006 if( pShmNode->h>=0 ){
4007 /* The requested region is not mapped into this processes address space.
4008 ** Check to see if it has been allocated (i.e. if the wal-index file is
4009 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004010 */
drh3cb93392011-03-12 18:10:44 +00004011 if( osFstat(pShmNode->h, &sStat) ){
4012 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004013 goto shmpage_out;
4014 }
drh3cb93392011-03-12 18:10:44 +00004015
4016 if( sStat.st_size<nByte ){
4017 /* The requested memory region does not exist. If bExtend is set to
4018 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4019 **
4020 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4021 ** the requested memory region.
4022 */
4023 if( !bExtend ) goto shmpage_out;
4024 if( robust_ftruncate(pShmNode->h, nByte) ){
4025 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4026 pShmNode->zFilename);
4027 goto shmpage_out;
4028 }
4029 }
danda9fe0c2010-07-13 18:44:03 +00004030 }
4031
4032 /* Map the requested memory region into this processes address space. */
4033 apNew = (char **)sqlite3_realloc(
4034 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4035 );
4036 if( !apNew ){
4037 rc = SQLITE_IOERR_NOMEM;
4038 goto shmpage_out;
4039 }
4040 pShmNode->apRegion = apNew;
4041 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004042 void *pMem;
4043 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004044 pMem = mmap(0, szRegion,
4045 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004046 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4047 );
4048 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004049 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004050 goto shmpage_out;
4051 }
4052 }else{
4053 pMem = sqlite3_malloc(szRegion);
4054 if( pMem==0 ){
4055 rc = SQLITE_NOMEM;
4056 goto shmpage_out;
4057 }
4058 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004059 }
4060 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4061 pShmNode->nRegion++;
4062 }
4063 }
4064
4065shmpage_out:
4066 if( pShmNode->nRegion>iRegion ){
4067 *pp = pShmNode->apRegion[iRegion];
4068 }else{
4069 *pp = 0;
4070 }
drh66dfec8b2011-06-01 20:01:49 +00004071 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004072 sqlite3_mutex_leave(pShmNode->mutex);
4073 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004074}
4075
4076/*
drhd9e5c4f2010-05-12 18:01:39 +00004077** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004078**
4079** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4080** different here than in posix. In xShmLock(), one can go from unlocked
4081** to shared and back or from unlocked to exclusive and back. But one may
4082** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004083*/
4084static int unixShmLock(
4085 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004086 int ofst, /* First lock to acquire or release */
4087 int n, /* Number of locks to acquire or release */
4088 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004089){
drh73b64e42010-05-30 19:55:15 +00004090 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4091 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4092 unixShm *pX; /* For looping over all siblings */
4093 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4094 int rc = SQLITE_OK; /* Result code */
4095 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004096
drhd91c68f2010-05-14 14:52:25 +00004097 assert( pShmNode==pDbFd->pInode->pShmNode );
4098 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004099 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004100 assert( n>=1 );
4101 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4102 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4103 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4104 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4105 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004106 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4107 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004108
drhc99597c2010-05-31 01:41:15 +00004109 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004110 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004111 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004112 if( flags & SQLITE_SHM_UNLOCK ){
4113 u16 allMask = 0; /* Mask of locks held by siblings */
4114
4115 /* See if any siblings hold this same lock */
4116 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4117 if( pX==p ) continue;
4118 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4119 allMask |= pX->sharedMask;
4120 }
4121
4122 /* Unlock the system-level locks */
4123 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004124 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004125 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004126 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004127 }
drh73b64e42010-05-30 19:55:15 +00004128
4129 /* Undo the local locks */
4130 if( rc==SQLITE_OK ){
4131 p->exclMask &= ~mask;
4132 p->sharedMask &= ~mask;
4133 }
4134 }else if( flags & SQLITE_SHM_SHARED ){
4135 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4136
4137 /* Find out which shared locks are already held by sibling connections.
4138 ** If any sibling already holds an exclusive lock, go ahead and return
4139 ** SQLITE_BUSY.
4140 */
4141 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004142 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004143 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004144 break;
4145 }
4146 allShared |= pX->sharedMask;
4147 }
4148
4149 /* Get shared locks at the system level, if necessary */
4150 if( rc==SQLITE_OK ){
4151 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004152 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004153 }else{
drh73b64e42010-05-30 19:55:15 +00004154 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004155 }
drhd9e5c4f2010-05-12 18:01:39 +00004156 }
drh73b64e42010-05-30 19:55:15 +00004157
4158 /* Get the local shared locks */
4159 if( rc==SQLITE_OK ){
4160 p->sharedMask |= mask;
4161 }
4162 }else{
4163 /* Make sure no sibling connections hold locks that will block this
4164 ** lock. If any do, return SQLITE_BUSY right away.
4165 */
4166 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004167 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4168 rc = SQLITE_BUSY;
4169 break;
4170 }
4171 }
4172
4173 /* Get the exclusive locks at the system level. Then if successful
4174 ** also mark the local connection as being locked.
4175 */
4176 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004177 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004178 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004179 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004180 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004181 }
drhd9e5c4f2010-05-12 18:01:39 +00004182 }
4183 }
drhd91c68f2010-05-14 14:52:25 +00004184 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004185 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4186 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004187 return rc;
4188}
4189
drh286a2882010-05-20 23:51:06 +00004190/*
4191** Implement a memory barrier or memory fence on shared memory.
4192**
4193** All loads and stores begun before the barrier must complete before
4194** any load or store begun after the barrier.
4195*/
4196static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004197 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004198){
drhff828942010-06-26 21:34:06 +00004199 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004200 unixEnterMutex();
4201 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004202}
4203
dan18801912010-06-14 14:07:50 +00004204/*
danda9fe0c2010-07-13 18:44:03 +00004205** Close a connection to shared-memory. Delete the underlying
4206** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004207**
4208** If there is no shared memory associated with the connection then this
4209** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004210*/
danda9fe0c2010-07-13 18:44:03 +00004211static int unixShmUnmap(
4212 sqlite3_file *fd, /* The underlying database file */
4213 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004214){
danda9fe0c2010-07-13 18:44:03 +00004215 unixShm *p; /* The connection to be closed */
4216 unixShmNode *pShmNode; /* The underlying shared-memory file */
4217 unixShm **pp; /* For looping over sibling connections */
4218 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004219
danda9fe0c2010-07-13 18:44:03 +00004220 pDbFd = (unixFile*)fd;
4221 p = pDbFd->pShm;
4222 if( p==0 ) return SQLITE_OK;
4223 pShmNode = p->pShmNode;
4224
4225 assert( pShmNode==pDbFd->pInode->pShmNode );
4226 assert( pShmNode->pInode==pDbFd->pInode );
4227
4228 /* Remove connection p from the set of connections associated
4229 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004230 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004231 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4232 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004233
danda9fe0c2010-07-13 18:44:03 +00004234 /* Free the connection p */
4235 sqlite3_free(p);
4236 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004237 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004238
4239 /* If pShmNode->nRef has reached 0, then close the underlying
4240 ** shared-memory file, too */
4241 unixEnterMutex();
4242 assert( pShmNode->nRef>0 );
4243 pShmNode->nRef--;
4244 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004245 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004246 unixShmPurge(pDbFd);
4247 }
4248 unixLeaveMutex();
4249
4250 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004251}
drh286a2882010-05-20 23:51:06 +00004252
danda9fe0c2010-07-13 18:44:03 +00004253
drhd9e5c4f2010-05-12 18:01:39 +00004254#else
drh6b017cc2010-06-14 18:01:46 +00004255# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004256# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004257# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004258# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004259#endif /* #ifndef SQLITE_OMIT_WAL */
4260
drh734c9862008-11-28 15:37:20 +00004261/*
4262** Here ends the implementation of all sqlite3_file methods.
4263**
4264********************** End sqlite3_file Methods *******************************
4265******************************************************************************/
4266
4267/*
drh6b9d6dd2008-12-03 19:34:47 +00004268** This division contains definitions of sqlite3_io_methods objects that
4269** implement various file locking strategies. It also contains definitions
4270** of "finder" functions. A finder-function is used to locate the appropriate
4271** sqlite3_io_methods object for a particular database file. The pAppData
4272** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4273** the correct finder-function for that VFS.
4274**
4275** Most finder functions return a pointer to a fixed sqlite3_io_methods
4276** object. The only interesting finder-function is autolockIoFinder, which
4277** looks at the filesystem type and tries to guess the best locking
4278** strategy from that.
4279**
drh1875f7a2008-12-08 18:19:17 +00004280** For finder-funtion F, two objects are created:
4281**
4282** (1) The real finder-function named "FImpt()".
4283**
dane946c392009-08-22 11:39:46 +00004284** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004285**
4286**
4287** A pointer to the F pointer is used as the pAppData value for VFS
4288** objects. We have to do this instead of letting pAppData point
4289** directly at the finder-function since C90 rules prevent a void*
4290** from be cast into a function pointer.
4291**
drh6b9d6dd2008-12-03 19:34:47 +00004292**
drh7708e972008-11-29 00:56:52 +00004293** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004294**
drh7708e972008-11-29 00:56:52 +00004295** * A constant sqlite3_io_methods object call METHOD that has locking
4296** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4297**
4298** * An I/O method finder function called FINDER that returns a pointer
4299** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004300*/
drhd9e5c4f2010-05-12 18:01:39 +00004301#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004302static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004303 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004304 CLOSE, /* xClose */ \
4305 unixRead, /* xRead */ \
4306 unixWrite, /* xWrite */ \
4307 unixTruncate, /* xTruncate */ \
4308 unixSync, /* xSync */ \
4309 unixFileSize, /* xFileSize */ \
4310 LOCK, /* xLock */ \
4311 UNLOCK, /* xUnlock */ \
4312 CKLOCK, /* xCheckReservedLock */ \
4313 unixFileControl, /* xFileControl */ \
4314 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004315 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004316 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004317 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004318 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004319 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004320}; \
drh0c2694b2009-09-03 16:23:44 +00004321static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4322 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004323 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004324} \
drh0c2694b2009-09-03 16:23:44 +00004325static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004326 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004327
4328/*
4329** Here are all of the sqlite3_io_methods objects for each of the
4330** locking strategies. Functions that return pointers to these methods
4331** are also created.
4332*/
4333IOMETHODS(
4334 posixIoFinder, /* Finder function name */
4335 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004336 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004337 unixClose, /* xClose method */
4338 unixLock, /* xLock method */
4339 unixUnlock, /* xUnlock method */
4340 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004341)
drh7708e972008-11-29 00:56:52 +00004342IOMETHODS(
4343 nolockIoFinder, /* Finder function name */
4344 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004345 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004346 nolockClose, /* xClose method */
4347 nolockLock, /* xLock method */
4348 nolockUnlock, /* xUnlock method */
4349 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004350)
drh7708e972008-11-29 00:56:52 +00004351IOMETHODS(
4352 dotlockIoFinder, /* Finder function name */
4353 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004354 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004355 dotlockClose, /* xClose method */
4356 dotlockLock, /* xLock method */
4357 dotlockUnlock, /* xUnlock method */
4358 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004359)
drh7708e972008-11-29 00:56:52 +00004360
chw78a13182009-04-07 05:35:03 +00004361#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004362IOMETHODS(
4363 flockIoFinder, /* Finder function name */
4364 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004365 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004366 flockClose, /* xClose method */
4367 flockLock, /* xLock method */
4368 flockUnlock, /* xUnlock method */
4369 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004370)
drh7708e972008-11-29 00:56:52 +00004371#endif
4372
drh6c7d5c52008-11-21 20:32:33 +00004373#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004374IOMETHODS(
4375 semIoFinder, /* Finder function name */
4376 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004377 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004378 semClose, /* xClose method */
4379 semLock, /* xLock method */
4380 semUnlock, /* xUnlock method */
4381 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004382)
aswiftaebf4132008-11-21 00:10:35 +00004383#endif
drh7708e972008-11-29 00:56:52 +00004384
drhd2cb50b2009-01-09 21:41:17 +00004385#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004386IOMETHODS(
4387 afpIoFinder, /* Finder function name */
4388 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004389 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004390 afpClose, /* xClose method */
4391 afpLock, /* xLock method */
4392 afpUnlock, /* xUnlock method */
4393 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004394)
drh715ff302008-12-03 22:32:44 +00004395#endif
4396
4397/*
4398** The proxy locking method is a "super-method" in the sense that it
4399** opens secondary file descriptors for the conch and lock files and
4400** it uses proxy, dot-file, AFP, and flock() locking methods on those
4401** secondary files. For this reason, the division that implements
4402** proxy locking is located much further down in the file. But we need
4403** to go ahead and define the sqlite3_io_methods and finder function
4404** for proxy locking here. So we forward declare the I/O methods.
4405*/
drhd2cb50b2009-01-09 21:41:17 +00004406#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004407static int proxyClose(sqlite3_file*);
4408static int proxyLock(sqlite3_file*, int);
4409static int proxyUnlock(sqlite3_file*, int);
4410static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004411IOMETHODS(
4412 proxyIoFinder, /* Finder function name */
4413 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004414 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004415 proxyClose, /* xClose method */
4416 proxyLock, /* xLock method */
4417 proxyUnlock, /* xUnlock method */
4418 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004419)
aswiftaebf4132008-11-21 00:10:35 +00004420#endif
drh7708e972008-11-29 00:56:52 +00004421
drh7ed97b92010-01-20 13:07:21 +00004422/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4423#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4424IOMETHODS(
4425 nfsIoFinder, /* Finder function name */
4426 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004427 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004428 unixClose, /* xClose method */
4429 unixLock, /* xLock method */
4430 nfsUnlock, /* xUnlock method */
4431 unixCheckReservedLock /* xCheckReservedLock method */
4432)
4433#endif
drh7708e972008-11-29 00:56:52 +00004434
drhd2cb50b2009-01-09 21:41:17 +00004435#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004436/*
drh6b9d6dd2008-12-03 19:34:47 +00004437** This "finder" function attempts to determine the best locking strategy
4438** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004439** object that implements that strategy.
4440**
4441** This is for MacOSX only.
4442*/
drh1875f7a2008-12-08 18:19:17 +00004443static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004444 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004445 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004446){
4447 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004448 const char *zFilesystem; /* Filesystem type name */
4449 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004450 } aMap[] = {
4451 { "hfs", &posixIoMethods },
4452 { "ufs", &posixIoMethods },
4453 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004454 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004455 { "webdav", &nolockIoMethods },
4456 { 0, 0 }
4457 };
4458 int i;
4459 struct statfs fsInfo;
4460 struct flock lockInfo;
4461
4462 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004463 /* If filePath==NULL that means we are dealing with a transient file
4464 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004465 return &nolockIoMethods;
4466 }
4467 if( statfs(filePath, &fsInfo) != -1 ){
4468 if( fsInfo.f_flags & MNT_RDONLY ){
4469 return &nolockIoMethods;
4470 }
4471 for(i=0; aMap[i].zFilesystem; i++){
4472 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4473 return aMap[i].pMethods;
4474 }
4475 }
4476 }
4477
4478 /* Default case. Handles, amongst others, "nfs".
4479 ** Test byte-range lock using fcntl(). If the call succeeds,
4480 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004481 */
drh7708e972008-11-29 00:56:52 +00004482 lockInfo.l_len = 1;
4483 lockInfo.l_start = 0;
4484 lockInfo.l_whence = SEEK_SET;
4485 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004486 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004487 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4488 return &nfsIoMethods;
4489 } else {
4490 return &posixIoMethods;
4491 }
drh7708e972008-11-29 00:56:52 +00004492 }else{
4493 return &dotlockIoMethods;
4494 }
4495}
drh0c2694b2009-09-03 16:23:44 +00004496static const sqlite3_io_methods
4497 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004498
drhd2cb50b2009-01-09 21:41:17 +00004499#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004500
chw78a13182009-04-07 05:35:03 +00004501#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4502/*
4503** This "finder" function attempts to determine the best locking strategy
4504** for the database file "filePath". It then returns the sqlite3_io_methods
4505** object that implements that strategy.
4506**
4507** This is for VXWorks only.
4508*/
4509static const sqlite3_io_methods *autolockIoFinderImpl(
4510 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004511 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004512){
4513 struct flock lockInfo;
4514
4515 if( !filePath ){
4516 /* If filePath==NULL that means we are dealing with a transient file
4517 ** that does not need to be locked. */
4518 return &nolockIoMethods;
4519 }
4520
4521 /* Test if fcntl() is supported and use POSIX style locks.
4522 ** Otherwise fall back to the named semaphore method.
4523 */
4524 lockInfo.l_len = 1;
4525 lockInfo.l_start = 0;
4526 lockInfo.l_whence = SEEK_SET;
4527 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004528 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004529 return &posixIoMethods;
4530 }else{
4531 return &semIoMethods;
4532 }
4533}
drh0c2694b2009-09-03 16:23:44 +00004534static const sqlite3_io_methods
4535 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004536
4537#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4538
drh7708e972008-11-29 00:56:52 +00004539/*
4540** An abstract type for a pointer to a IO method finder function:
4541*/
drh0c2694b2009-09-03 16:23:44 +00004542typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004543
aswiftaebf4132008-11-21 00:10:35 +00004544
drh734c9862008-11-28 15:37:20 +00004545/****************************************************************************
4546**************************** sqlite3_vfs methods ****************************
4547**
4548** This division contains the implementation of methods on the
4549** sqlite3_vfs object.
4550*/
4551
danielk1977a3d4c882007-03-23 10:08:38 +00004552/*
danielk1977e339d652008-06-28 11:23:00 +00004553** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004554*/
4555static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004556 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004557 int h, /* Open file descriptor of file being opened */
drh0059eae2011-08-08 23:48:40 +00004558 int syncDir, /* True to sync directory on first sync */
drh218c5082008-03-07 00:27:10 +00004559 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004560 const char *zFilename, /* Name of the file being opened */
chw97185482008-11-17 08:05:31 +00004561 int noLock, /* Omit locking if true */
drh77197112011-03-15 19:08:48 +00004562 int isDelete, /* Delete on close if true */
4563 int isReadOnly /* True if the file is opened read-only */
drhbfe66312006-10-03 17:40:40 +00004564){
drh7708e972008-11-29 00:56:52 +00004565 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004566 unixFile *pNew = (unixFile *)pId;
4567 int rc = SQLITE_OK;
4568
drh8af6c222010-05-14 12:43:01 +00004569 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004570
dane946c392009-08-22 11:39:46 +00004571 /* Parameter isDelete is only used on vxworks. Express this explicitly
4572 ** here to prevent compiler warnings about unused parameters.
danielk1977a03396a2008-11-19 14:35:46 +00004573 */
drh7708e972008-11-29 00:56:52 +00004574 UNUSED_PARAMETER(isDelete);
danielk1977a03396a2008-11-19 14:35:46 +00004575
dan00157392010-10-05 11:33:15 +00004576 /* Usually the path zFilename should not be a relative pathname. The
4577 ** exception is when opening the proxy "conch" file in builds that
4578 ** include the special Apple locking styles.
4579 */
dan00157392010-10-05 11:33:15 +00004580#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004581 assert( zFilename==0 || zFilename[0]=='/'
4582 || pVfs->pAppData==(void*)&autolockIoFinder );
4583#else
4584 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004585#endif
dan00157392010-10-05 11:33:15 +00004586
drhb07028f2011-10-14 21:49:18 +00004587 /* No locking occurs in temporary files */
4588 assert( zFilename!=0 || noLock );
4589
drh308c2a52010-05-14 11:30:18 +00004590 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004591 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004592 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004593 pNew->zPath = zFilename;
drhbec7c972011-12-23 00:25:02 +00004594 pNew->ctrlFlags = 0;
drhcb15f352011-12-23 01:04:17 +00004595 if( sqlite3_uri_boolean(zFilename, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
4596 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004597 }
drha7e61d82011-03-12 17:02:57 +00004598 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004599 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004600 }
drh77197112011-03-15 19:08:48 +00004601 if( isReadOnly ){
4602 pNew->ctrlFlags |= UNIXFILE_RDONLY;
4603 }
drh0059eae2011-08-08 23:48:40 +00004604 if( syncDir ){
4605 pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
4606 }
drh339eb0b2008-03-07 15:34:11 +00004607
drh6c7d5c52008-11-21 20:32:33 +00004608#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004609 pNew->pId = vxworksFindFileId(zFilename);
4610 if( pNew->pId==0 ){
4611 noLock = 1;
4612 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004613 }
4614#endif
4615
drhda0e7682008-07-30 15:27:54 +00004616 if( noLock ){
drh7708e972008-11-29 00:56:52 +00004617 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004618 }else{
drh0c2694b2009-09-03 16:23:44 +00004619 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004620#if SQLITE_ENABLE_LOCKING_STYLE
4621 /* Cache zFilename in the locking context (AFP and dotlock override) for
4622 ** proxyLock activation is possible (remote proxy is based on db name)
4623 ** zFilename remains valid until file is closed, to support */
4624 pNew->lockingContext = (void*)zFilename;
4625#endif
drhda0e7682008-07-30 15:27:54 +00004626 }
danielk1977e339d652008-06-28 11:23:00 +00004627
drh7ed97b92010-01-20 13:07:21 +00004628 if( pLockingStyle == &posixIoMethods
4629#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4630 || pLockingStyle == &nfsIoMethods
4631#endif
4632 ){
drh7708e972008-11-29 00:56:52 +00004633 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004634 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004635 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004636 /* If an error occured in findInodeInfo(), close the file descriptor
4637 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004638 ** in two scenarios:
4639 **
4640 ** (a) A call to fstat() failed.
4641 ** (b) A malloc failed.
4642 **
4643 ** Scenario (b) may only occur if the process is holding no other
4644 ** file descriptors open on the same file. If there were other file
4645 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004646 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004647 ** handle h - as it is guaranteed that no posix locks will be released
4648 ** by doing so.
4649 **
4650 ** If scenario (a) caused the error then things are not so safe. The
4651 ** implicit assumption here is that if fstat() fails, things are in
4652 ** such bad shape that dropping a lock or two doesn't matter much.
4653 */
drh0e9365c2011-03-02 02:08:13 +00004654 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004655 h = -1;
4656 }
drh7708e972008-11-29 00:56:52 +00004657 unixLeaveMutex();
4658 }
danielk1977e339d652008-06-28 11:23:00 +00004659
drhd2cb50b2009-01-09 21:41:17 +00004660#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004661 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004662 /* AFP locking uses the file path so it needs to be included in
4663 ** the afpLockingContext.
4664 */
4665 afpLockingContext *pCtx;
4666 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4667 if( pCtx==0 ){
4668 rc = SQLITE_NOMEM;
4669 }else{
4670 /* NB: zFilename exists and remains valid until the file is closed
4671 ** according to requirement F11141. So we do not need to make a
4672 ** copy of the filename. */
4673 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004674 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004675 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004676 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004677 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004678 if( rc!=SQLITE_OK ){
4679 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004680 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004681 h = -1;
4682 }
drh7708e972008-11-29 00:56:52 +00004683 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004684 }
drh7708e972008-11-29 00:56:52 +00004685 }
4686#endif
danielk1977e339d652008-06-28 11:23:00 +00004687
drh7708e972008-11-29 00:56:52 +00004688 else if( pLockingStyle == &dotlockIoMethods ){
4689 /* Dotfile locking uses the file path so it needs to be included in
4690 ** the dotlockLockingContext
4691 */
4692 char *zLockFile;
4693 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004694 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004695 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004696 zLockFile = (char *)sqlite3_malloc(nFilename);
4697 if( zLockFile==0 ){
4698 rc = SQLITE_NOMEM;
4699 }else{
4700 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004701 }
drh7708e972008-11-29 00:56:52 +00004702 pNew->lockingContext = zLockFile;
4703 }
danielk1977e339d652008-06-28 11:23:00 +00004704
drh6c7d5c52008-11-21 20:32:33 +00004705#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004706 else if( pLockingStyle == &semIoMethods ){
4707 /* Named semaphore locking uses the file path so it needs to be
4708 ** included in the semLockingContext
4709 */
4710 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004711 rc = findInodeInfo(pNew, &pNew->pInode);
4712 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4713 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004714 int n;
drh2238dcc2009-08-27 17:56:20 +00004715 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004716 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004717 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004718 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004719 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4720 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004721 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004722 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004723 }
chw97185482008-11-17 08:05:31 +00004724 }
drh7708e972008-11-29 00:56:52 +00004725 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004726 }
drh7708e972008-11-29 00:56:52 +00004727#endif
aswift5b1a2562008-08-22 00:22:35 +00004728
4729 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004730#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004731 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004732 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004733 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004734 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004735 isDelete = 0;
4736 }
4737 pNew->isDelete = isDelete;
4738#endif
danielk1977e339d652008-06-28 11:23:00 +00004739 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004740 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004741 }else{
drh7708e972008-11-29 00:56:52 +00004742 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004743 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004744 }
danielk1977e339d652008-06-28 11:23:00 +00004745 return rc;
drh054889e2005-11-30 03:20:31 +00004746}
drh9c06c952005-11-26 00:25:00 +00004747
danielk1977ad94b582007-08-20 06:44:22 +00004748/*
drh8b3cf822010-06-01 21:02:51 +00004749** Return the name of a directory in which to put temporary files.
4750** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004751*/
drh7234c6d2010-06-19 15:10:09 +00004752static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004753 static const char *azDirs[] = {
4754 0,
aswiftaebf4132008-11-21 00:10:35 +00004755 0,
danielk197717b90b52008-06-06 11:11:25 +00004756 "/var/tmp",
4757 "/usr/tmp",
4758 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004759 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004760 };
drh8b3cf822010-06-01 21:02:51 +00004761 unsigned int i;
4762 struct stat buf;
4763 const char *zDir = 0;
4764
4765 azDirs[0] = sqlite3_temp_directory;
4766 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004767 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004768 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004769 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004770 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004771 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004772 break;
4773 }
4774 return zDir;
4775}
4776
4777/*
4778** Create a temporary file name in zBuf. zBuf must be allocated
4779** by the calling process and must be big enough to hold at least
4780** pVfs->mxPathname bytes.
4781*/
4782static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004783 static const unsigned char zChars[] =
4784 "abcdefghijklmnopqrstuvwxyz"
4785 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4786 "0123456789";
drh41022642008-11-21 00:24:42 +00004787 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004788 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004789
4790 /* It's odd to simulate an io-error here, but really this is just
4791 ** using the io-error infrastructure to test that SQLite handles this
4792 ** function failing.
4793 */
4794 SimulateIOError( return SQLITE_IOERR );
4795
drh7234c6d2010-06-19 15:10:09 +00004796 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004797 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004798
4799 /* Check that the output buffer is large enough for the temporary file
4800 ** name. If it is not, return SQLITE_ERROR.
4801 */
danielk197700e13612008-11-17 19:18:54 +00004802 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004803 return SQLITE_ERROR;
4804 }
4805
4806 do{
4807 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004808 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004809 sqlite3_randomness(15, &zBuf[j]);
4810 for(i=0; i<15; i++, j++){
4811 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4812 }
4813 zBuf[j] = 0;
drh99ab3b12011-03-02 15:09:07 +00004814 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004815 return SQLITE_OK;
4816}
4817
drhd2cb50b2009-01-09 21:41:17 +00004818#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004819/*
4820** Routine to transform a unixFile into a proxy-locking unixFile.
4821** Implementation in the proxy-lock division, but used by unixOpen()
4822** if SQLITE_PREFER_PROXY_LOCKING is defined.
4823*/
4824static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004825#endif
drhc66d5b62008-12-03 22:48:32 +00004826
dan08da86a2009-08-21 17:18:03 +00004827/*
4828** Search for an unused file descriptor that was opened on the database
4829** file (not a journal or master-journal file) identified by pathname
4830** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4831** argument to this function.
4832**
4833** Such a file descriptor may exist if a database connection was closed
4834** but the associated file descriptor could not be closed because some
4835** other file descriptor open on the same file is holding a file-lock.
4836** Refer to comments in the unixClose() function and the lengthy comment
4837** describing "Posix Advisory Locking" at the start of this file for
4838** further details. Also, ticket #4018.
4839**
4840** If a suitable file descriptor is found, then it is returned. If no
4841** such file descriptor is located, -1 is returned.
4842*/
dane946c392009-08-22 11:39:46 +00004843static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4844 UnixUnusedFd *pUnused = 0;
4845
4846 /* Do not search for an unused file descriptor on vxworks. Not because
4847 ** vxworks would not benefit from the change (it might, we're not sure),
4848 ** but because no way to test it is currently available. It is better
4849 ** not to risk breaking vxworks support for the sake of such an obscure
4850 ** feature. */
4851#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004852 struct stat sStat; /* Results of stat() call */
4853
4854 /* A stat() call may fail for various reasons. If this happens, it is
4855 ** almost certain that an open() call on the same path will also fail.
4856 ** For this reason, if an error occurs in the stat() call here, it is
4857 ** ignored and -1 is returned. The caller will try to open a new file
4858 ** descriptor on the same path, fail, and return an error to SQLite.
4859 **
4860 ** Even if a subsequent open() call does succeed, the consequences of
4861 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004862 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004863 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004864
4865 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004866 pInode = inodeList;
4867 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4868 || pInode->fileId.ino!=sStat.st_ino) ){
4869 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004870 }
drh8af6c222010-05-14 12:43:01 +00004871 if( pInode ){
dane946c392009-08-22 11:39:46 +00004872 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004873 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004874 pUnused = *pp;
4875 if( pUnused ){
4876 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004877 }
4878 }
4879 unixLeaveMutex();
4880 }
dane946c392009-08-22 11:39:46 +00004881#endif /* if !OS_VXWORKS */
4882 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004883}
danielk197717b90b52008-06-06 11:11:25 +00004884
4885/*
danddb0ac42010-07-14 14:48:58 +00004886** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004887** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004888** and a value suitable for passing as the third argument to open(2) is
4889** written to *pMode. If an IO error occurs, an SQLite error code is
4890** returned and the value of *pMode is not modified.
4891**
4892** If the file being opened is a temporary file, it is always created with
4893** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004894** is a database or master journal file, it is created with the permissions
4895** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004896**
drh8ab58662010-07-15 18:38:39 +00004897** Finally, if the file being opened is a WAL or regular journal file, then
4898** this function queries the file-system for the permissions on the
4899** corresponding database file and sets *pMode to this value. Whenever
4900** possible, WAL and journal files are created using the same permissions
4901** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004902**
4903** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4904** original filename is unavailable. But 8_3_NAMES is only used for
4905** FAT filesystems and permissions do not matter there, so just use
4906** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004907*/
4908static int findCreateFileMode(
4909 const char *zPath, /* Path of file (possibly) being created */
4910 int flags, /* Flags passed as 4th argument to xOpen() */
4911 mode_t *pMode /* OUT: Permissions to open file with */
4912){
4913 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004914 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drh8ab58662010-07-15 18:38:39 +00004915 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004916 char zDb[MAX_PATHNAME+1]; /* Database file path */
4917 int nDb; /* Number of valid bytes in zDb */
4918 struct stat sStat; /* Output of stat() on database file */
4919
dana0c989d2010-11-05 18:07:37 +00004920 /* zPath is a path to a WAL or journal file. The following block derives
4921 ** the path to the associated database file from zPath. This block handles
4922 ** the following naming conventions:
4923 **
4924 ** "<path to db>-journal"
4925 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004926 ** "<path to db>-journalNN"
4927 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004928 **
drhd337c5b2011-10-20 18:23:35 +00004929 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004930 ** used by the test_multiplex.c module.
4931 */
4932 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004933#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004934 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004935 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004936#else
4937 while( zPath[nDb]!='-' ){
4938 assert( nDb>0 );
4939 assert( zPath[nDb]!='\n' );
4940 nDb--;
4941 }
4942#endif
danddb0ac42010-07-14 14:48:58 +00004943 memcpy(zDb, zPath, nDb);
4944 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004945
drh58384f12011-07-28 00:14:45 +00004946 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004947 *pMode = sStat.st_mode & 0777;
4948 }else{
4949 rc = SQLITE_IOERR_FSTAT;
4950 }
4951 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4952 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004953 }
4954 return rc;
4955}
4956
4957/*
danielk1977ad94b582007-08-20 06:44:22 +00004958** Open the file zPath.
4959**
danielk1977b4b47412007-08-17 15:53:36 +00004960** Previously, the SQLite OS layer used three functions in place of this
4961** one:
4962**
4963** sqlite3OsOpenReadWrite();
4964** sqlite3OsOpenReadOnly();
4965** sqlite3OsOpenExclusive();
4966**
4967** These calls correspond to the following combinations of flags:
4968**
4969** ReadWrite() -> (READWRITE | CREATE)
4970** ReadOnly() -> (READONLY)
4971** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4972**
4973** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4974** true, the file was configured to be automatically deleted when the
4975** file handle closed. To achieve the same effect using this new
4976** interface, add the DELETEONCLOSE flag to those specified above for
4977** OpenExclusive().
4978*/
4979static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004980 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4981 const char *zPath, /* Pathname of file to be opened */
4982 sqlite3_file *pFile, /* The file descriptor to be filled in */
4983 int flags, /* Input flags to control the opening */
4984 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004985){
dan08da86a2009-08-21 17:18:03 +00004986 unixFile *p = (unixFile *)pFile;
4987 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004988 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004989 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004990 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004991 int rc = SQLITE_OK; /* Function Return Code */
danielk1977b4b47412007-08-17 15:53:36 +00004992
4993 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
4994 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
4995 int isCreate = (flags & SQLITE_OPEN_CREATE);
4996 int isReadonly = (flags & SQLITE_OPEN_READONLY);
4997 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00004998#if SQLITE_ENABLE_LOCKING_STYLE
4999 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5000#endif
drh3d4435b2011-08-26 20:55:50 +00005001#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5002 struct statfs fsInfo;
5003#endif
danielk1977b4b47412007-08-17 15:53:36 +00005004
danielk1977fee2d252007-08-18 10:59:19 +00005005 /* If creating a master or main-file journal, this function will open
5006 ** a file-descriptor on the directory too. The first time unixSync()
5007 ** is called the directory file descriptor will be fsync()ed and close()d.
5008 */
drh0059eae2011-08-08 23:48:40 +00005009 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005010 eType==SQLITE_OPEN_MASTER_JOURNAL
5011 || eType==SQLITE_OPEN_MAIN_JOURNAL
5012 || eType==SQLITE_OPEN_WAL
5013 ));
danielk1977fee2d252007-08-18 10:59:19 +00005014
danielk197717b90b52008-06-06 11:11:25 +00005015 /* If argument zPath is a NULL pointer, this function is required to open
5016 ** a temporary file. Use this buffer to store the file name in.
5017 */
5018 char zTmpname[MAX_PATHNAME+1];
5019 const char *zName = zPath;
5020
danielk1977fee2d252007-08-18 10:59:19 +00005021 /* Check the following statements are true:
5022 **
5023 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5024 ** (b) if CREATE is set, then READWRITE must also be set, and
5025 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005026 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005027 */
danielk1977b4b47412007-08-17 15:53:36 +00005028 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005029 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005030 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005031 assert(isDelete==0 || isCreate);
5032
danddb0ac42010-07-14 14:48:58 +00005033 /* The main DB, main journal, WAL file and master journal are never
5034 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005035 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5036 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5037 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005038 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005039
danielk1977fee2d252007-08-18 10:59:19 +00005040 /* Assert that the upper layer has set one of the "file-type" flags. */
5041 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5042 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5043 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005044 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005045 );
5046
dan08da86a2009-08-21 17:18:03 +00005047 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005048
dan08da86a2009-08-21 17:18:03 +00005049 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005050 UnixUnusedFd *pUnused;
5051 pUnused = findReusableFd(zName, flags);
5052 if( pUnused ){
5053 fd = pUnused->fd;
5054 }else{
dan6aa657f2009-08-24 18:57:58 +00005055 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005056 if( !pUnused ){
5057 return SQLITE_NOMEM;
5058 }
5059 }
5060 p->pUnused = pUnused;
dan08da86a2009-08-21 17:18:03 +00005061 }else if( !zName ){
5062 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005063 assert(isDelete && !syncDir);
drh8b3cf822010-06-01 21:02:51 +00005064 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005065 if( rc!=SQLITE_OK ){
5066 return rc;
5067 }
5068 zName = zTmpname;
5069 }
5070
dan08da86a2009-08-21 17:18:03 +00005071 /* Determine the value of the flags parameter passed to POSIX function
5072 ** open(). These must be calculated even if open() is not called, as
5073 ** they may be stored as part of the file handle and used by the
5074 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005075 if( isReadonly ) openFlags |= O_RDONLY;
5076 if( isReadWrite ) openFlags |= O_RDWR;
5077 if( isCreate ) openFlags |= O_CREAT;
5078 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5079 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005080
danielk1977b4b47412007-08-17 15:53:36 +00005081 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005082 mode_t openMode; /* Permissions to create file with */
5083 rc = findCreateFileMode(zName, flags, &openMode);
5084 if( rc!=SQLITE_OK ){
5085 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005086 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005087 return rc;
5088 }
drhad4f1e52011-03-04 15:43:57 +00005089 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005090 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005091 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5092 /* Failed to open the file for read/write access. Try read-only. */
5093 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005094 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005095 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005096 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005097 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005098 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005099 }
5100 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005101 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005102 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005103 }
danielk1977b4b47412007-08-17 15:53:36 +00005104 }
dan08da86a2009-08-21 17:18:03 +00005105 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005106 if( pOutFlags ){
5107 *pOutFlags = flags;
5108 }
5109
dane946c392009-08-22 11:39:46 +00005110 if( p->pUnused ){
5111 p->pUnused->fd = fd;
5112 p->pUnused->flags = flags;
5113 }
5114
danielk1977b4b47412007-08-17 15:53:36 +00005115 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005116#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005117 zPath = zName;
5118#else
drh036ac7f2011-08-08 23:18:05 +00005119 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005120#endif
danielk1977b4b47412007-08-17 15:53:36 +00005121 }
drh41022642008-11-21 00:24:42 +00005122#if SQLITE_ENABLE_LOCKING_STYLE
5123 else{
dan08da86a2009-08-21 17:18:03 +00005124 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005125 }
5126#endif
5127
danielk1977e339d652008-06-28 11:23:00 +00005128#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005129 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005130#endif
5131
drhda0e7682008-07-30 15:27:54 +00005132 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005133
drh7ed97b92010-01-20 13:07:21 +00005134
5135#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005136 if( fstatfs(fd, &fsInfo) == -1 ){
5137 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005138 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005139 return SQLITE_IOERR_ACCESS;
5140 }
5141 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5142 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5143 }
5144#endif
5145
5146#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005147#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005148 isAutoProxy = 1;
5149#endif
5150 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005151 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5152 int useProxy = 0;
5153
dan08da86a2009-08-21 17:18:03 +00005154 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5155 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005156 if( envforce!=NULL ){
5157 useProxy = atoi(envforce)>0;
5158 }else{
aswiftaebf4132008-11-21 00:10:35 +00005159 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005160 /* In theory, the close(fd) call is sub-optimal. If the file opened
5161 ** with fd is a database file, and there are other connections open
5162 ** on that file that are currently holding advisory locks on it,
5163 ** then the call to close() will cancel those locks. In practice,
5164 ** we're assuming that statfs() doesn't fail very often. At least
5165 ** not while other file descriptors opened by the same process on
5166 ** the same file are working. */
5167 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005168 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005169 rc = SQLITE_IOERR_ACCESS;
5170 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005171 }
5172 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5173 }
5174 if( useProxy ){
drh0059eae2011-08-08 23:48:40 +00005175 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005176 isDelete, isReadonly);
aswiftaebf4132008-11-21 00:10:35 +00005177 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005178 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005179 if( rc!=SQLITE_OK ){
5180 /* Use unixClose to clean up the resources added in fillInUnixFile
5181 ** and clear all the structure's references. Specifically,
5182 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5183 */
5184 unixClose(pFile);
5185 return rc;
5186 }
aswiftaebf4132008-11-21 00:10:35 +00005187 }
dane946c392009-08-22 11:39:46 +00005188 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005189 }
5190 }
5191#endif
5192
drh0059eae2011-08-08 23:48:40 +00005193 rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
drh77197112011-03-15 19:08:48 +00005194 isDelete, isReadonly);
dane946c392009-08-22 11:39:46 +00005195open_finished:
5196 if( rc!=SQLITE_OK ){
5197 sqlite3_free(p->pUnused);
5198 }
5199 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005200}
5201
dane946c392009-08-22 11:39:46 +00005202
danielk1977b4b47412007-08-17 15:53:36 +00005203/*
danielk1977fee2d252007-08-18 10:59:19 +00005204** Delete the file at zPath. If the dirSync argument is true, fsync()
5205** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005206*/
drh6b9d6dd2008-12-03 19:34:47 +00005207static int unixDelete(
5208 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5209 const char *zPath, /* Name of file to be deleted */
5210 int dirSync /* If true, fsync() directory after deleting file */
5211){
danielk1977fee2d252007-08-18 10:59:19 +00005212 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005213 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005214 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005215 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005216 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005217 }
danielk1977d39fa702008-10-16 13:27:40 +00005218#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005219 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005220 int fd;
drh90315a22011-08-10 01:52:12 +00005221 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005222 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005223#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005224 if( fsync(fd)==-1 )
5225#else
5226 if( fsync(fd) )
5227#endif
5228 {
dane18d4952011-02-21 11:46:24 +00005229 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005230 }
drh0e9365c2011-03-02 02:08:13 +00005231 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005232 }else if( rc==SQLITE_CANTOPEN ){
5233 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005234 }
5235 }
danielk1977d138dd82008-10-15 16:02:48 +00005236#endif
danielk1977fee2d252007-08-18 10:59:19 +00005237 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005238}
5239
danielk197790949c22007-08-17 16:50:38 +00005240/*
5241** Test the existance of or access permissions of file zPath. The
5242** test performed depends on the value of flags:
5243**
5244** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5245** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5246** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5247**
5248** Otherwise return 0.
5249*/
danielk1977861f7452008-06-05 11:39:11 +00005250static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005251 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5252 const char *zPath, /* Path of the file to examine */
5253 int flags, /* What do we want to learn about the zPath file? */
5254 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005255){
rse25c0d1a2007-09-20 08:38:14 +00005256 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005257 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005258 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005259 switch( flags ){
5260 case SQLITE_ACCESS_EXISTS:
5261 amode = F_OK;
5262 break;
5263 case SQLITE_ACCESS_READWRITE:
5264 amode = W_OK|R_OK;
5265 break;
drh50d3f902007-08-27 21:10:36 +00005266 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005267 amode = R_OK;
5268 break;
5269
5270 default:
5271 assert(!"Invalid flags argument");
5272 }
drh99ab3b12011-03-02 15:09:07 +00005273 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005274 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5275 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005276 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005277 *pResOut = 0;
5278 }
5279 }
danielk1977861f7452008-06-05 11:39:11 +00005280 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005281}
5282
danielk1977b4b47412007-08-17 15:53:36 +00005283
5284/*
5285** Turn a relative pathname into a full pathname. The relative path
5286** is stored as a nul-terminated string in the buffer pointed to by
5287** zPath.
5288**
5289** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5290** (in this case, MAX_PATHNAME bytes). The full-path is written to
5291** this buffer before returning.
5292*/
danielk1977adfb9b02007-09-17 07:02:56 +00005293static int unixFullPathname(
5294 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5295 const char *zPath, /* Possibly relative input path */
5296 int nOut, /* Size of output buffer in bytes */
5297 char *zOut /* Output buffer */
5298){
danielk1977843e65f2007-09-01 16:16:15 +00005299
5300 /* It's odd to simulate an io-error here, but really this is just
5301 ** using the io-error infrastructure to test that SQLite handles this
5302 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005303 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005304 */
5305 SimulateIOError( return SQLITE_ERROR );
5306
drh153c62c2007-08-24 03:51:33 +00005307 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005308 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005309
drh3c7f2dc2007-12-06 13:26:20 +00005310 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005311 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005312 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005313 }else{
5314 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005315 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005316 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005317 }
drhea678832008-12-10 19:26:22 +00005318 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005319 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005320 }
5321 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005322}
5323
drh0ccebe72005-06-07 22:22:50 +00005324
drh761df872006-12-21 01:29:22 +00005325#ifndef SQLITE_OMIT_LOAD_EXTENSION
5326/*
5327** Interfaces for opening a shared library, finding entry points
5328** within the shared library, and closing the shared library.
5329*/
5330#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005331static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5332 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005333 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5334}
danielk197795c8a542007-09-01 06:51:27 +00005335
5336/*
5337** SQLite calls this function immediately after a call to unixDlSym() or
5338** unixDlOpen() fails (returns a null pointer). If a more detailed error
5339** message is available, it is written to zBufOut. If no error message
5340** is available, zBufOut is left unmodified and SQLite uses a default
5341** error message.
5342*/
danielk1977397d65f2008-11-19 11:35:39 +00005343static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005344 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005345 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005346 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005347 zErr = dlerror();
5348 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005349 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005350 }
drh6c7d5c52008-11-21 20:32:33 +00005351 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005352}
drh1875f7a2008-12-08 18:19:17 +00005353static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5354 /*
5355 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5356 ** cast into a pointer to a function. And yet the library dlsym() routine
5357 ** returns a void* which is really a pointer to a function. So how do we
5358 ** use dlsym() with -pedantic-errors?
5359 **
5360 ** Variable x below is defined to be a pointer to a function taking
5361 ** parameters void* and const char* and returning a pointer to a function.
5362 ** We initialize x by assigning it a pointer to the dlsym() function.
5363 ** (That assignment requires a cast.) Then we call the function that
5364 ** x points to.
5365 **
5366 ** This work-around is unlikely to work correctly on any system where
5367 ** you really cannot cast a function pointer into void*. But then, on the
5368 ** other hand, dlsym() will not work on such a system either, so we have
5369 ** not really lost anything.
5370 */
5371 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005372 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005373 x = (void(*(*)(void*,const char*))(void))dlsym;
5374 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005375}
danielk1977397d65f2008-11-19 11:35:39 +00005376static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5377 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005378 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005379}
danielk1977b4b47412007-08-17 15:53:36 +00005380#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5381 #define unixDlOpen 0
5382 #define unixDlError 0
5383 #define unixDlSym 0
5384 #define unixDlClose 0
5385#endif
5386
5387/*
danielk197790949c22007-08-17 16:50:38 +00005388** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005389*/
danielk1977397d65f2008-11-19 11:35:39 +00005390static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5391 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005392 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005393
drhbbd42a62004-05-22 17:41:58 +00005394 /* We have to initialize zBuf to prevent valgrind from reporting
5395 ** errors. The reports issued by valgrind are incorrect - we would
5396 ** prefer that the randomness be increased by making use of the
5397 ** uninitialized space in zBuf - but valgrind errors tend to worry
5398 ** some users. Rather than argue, it seems easier just to initialize
5399 ** the whole array and silence valgrind, even if that means less randomness
5400 ** in the random seed.
5401 **
5402 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005403 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005404 ** tests repeatable.
5405 */
danielk1977b4b47412007-08-17 15:53:36 +00005406 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005407#if !defined(SQLITE_TEST)
5408 {
drh842b8642005-01-21 17:53:17 +00005409 int pid, fd;
drhad4f1e52011-03-04 15:43:57 +00005410 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005411 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005412 time_t t;
5413 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005414 memcpy(zBuf, &t, sizeof(t));
5415 pid = getpid();
5416 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005417 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005418 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005419 }else{
drhe562be52011-03-02 18:01:10 +00005420 do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005421 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005422 }
drhbbd42a62004-05-22 17:41:58 +00005423 }
5424#endif
drh72cbd072008-10-14 17:58:38 +00005425 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005426}
5427
danielk1977b4b47412007-08-17 15:53:36 +00005428
drhbbd42a62004-05-22 17:41:58 +00005429/*
5430** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005431** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005432** The return value is the number of microseconds of sleep actually
5433** requested from the underlying operating system, a number which
5434** might be greater than or equal to the argument, but not less
5435** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005436*/
danielk1977397d65f2008-11-19 11:35:39 +00005437static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005438#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005439 struct timespec sp;
5440
5441 sp.tv_sec = microseconds / 1000000;
5442 sp.tv_nsec = (microseconds % 1000000) * 1000;
5443 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005444 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005445 return microseconds;
5446#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005447 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005448 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005449 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005450#else
danielk1977b4b47412007-08-17 15:53:36 +00005451 int seconds = (microseconds+999999)/1000000;
5452 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005453 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005454 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005455#endif
drh88f474a2006-01-02 20:00:12 +00005456}
5457
5458/*
drh6b9d6dd2008-12-03 19:34:47 +00005459** The following variable, if set to a non-zero value, is interpreted as
5460** the number of seconds since 1970 and is used to set the result of
5461** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005462*/
5463#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005464int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005465#endif
5466
5467/*
drhb7e8ea22010-05-03 14:32:30 +00005468** Find the current time (in Universal Coordinated Time). Write into *piNow
5469** the current time and date as a Julian Day number times 86_400_000. In
5470** other words, write into *piNow the number of milliseconds since the Julian
5471** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5472** proleptic Gregorian calendar.
5473**
drh31702252011-10-12 23:13:43 +00005474** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5475** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005476*/
5477static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5478 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005479 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005480#if defined(NO_GETTOD)
5481 time_t t;
5482 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005483 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005484#elif OS_VXWORKS
5485 struct timespec sNow;
5486 clock_gettime(CLOCK_REALTIME, &sNow);
5487 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5488#else
5489 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005490 if( gettimeofday(&sNow, 0)==0 ){
5491 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5492 }else{
5493 rc = SQLITE_ERROR;
5494 }
drhb7e8ea22010-05-03 14:32:30 +00005495#endif
5496
5497#ifdef SQLITE_TEST
5498 if( sqlite3_current_time ){
5499 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5500 }
5501#endif
5502 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005503 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005504}
5505
5506/*
drhbbd42a62004-05-22 17:41:58 +00005507** Find the current time (in Universal Coordinated Time). Write the
5508** current time and date as a Julian Day number into *prNow and
5509** return 0. Return 1 if the time and date cannot be found.
5510*/
danielk1977397d65f2008-11-19 11:35:39 +00005511static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005512 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005513 int rc;
drhff828942010-06-26 21:34:06 +00005514 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005515 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005516 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005517 return rc;
drhbbd42a62004-05-22 17:41:58 +00005518}
danielk1977b4b47412007-08-17 15:53:36 +00005519
drh6b9d6dd2008-12-03 19:34:47 +00005520/*
5521** We added the xGetLastError() method with the intention of providing
5522** better low-level error messages when operating-system problems come up
5523** during SQLite operation. But so far, none of that has been implemented
5524** in the core. So this routine is never called. For now, it is merely
5525** a place-holder.
5526*/
danielk1977397d65f2008-11-19 11:35:39 +00005527static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5528 UNUSED_PARAMETER(NotUsed);
5529 UNUSED_PARAMETER(NotUsed2);
5530 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005531 return 0;
5532}
5533
drhf2424c52010-04-26 00:04:55 +00005534
5535/*
drh734c9862008-11-28 15:37:20 +00005536************************ End of sqlite3_vfs methods ***************************
5537******************************************************************************/
5538
drh715ff302008-12-03 22:32:44 +00005539/******************************************************************************
5540************************** Begin Proxy Locking ********************************
5541**
5542** Proxy locking is a "uber-locking-method" in this sense: It uses the
5543** other locking methods on secondary lock files. Proxy locking is a
5544** meta-layer over top of the primitive locking implemented above. For
5545** this reason, the division that implements of proxy locking is deferred
5546** until late in the file (here) after all of the other I/O methods have
5547** been defined - so that the primitive locking methods are available
5548** as services to help with the implementation of proxy locking.
5549**
5550****
5551**
5552** The default locking schemes in SQLite use byte-range locks on the
5553** database file to coordinate safe, concurrent access by multiple readers
5554** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5555** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5556** as POSIX read & write locks over fixed set of locations (via fsctl),
5557** on AFP and SMB only exclusive byte-range locks are available via fsctl
5558** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5559** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5560** address in the shared range is taken for a SHARED lock, the entire
5561** shared range is taken for an EXCLUSIVE lock):
5562**
5563** PENDING_BYTE 0x40000000
5564** RESERVED_BYTE 0x40000001
5565** SHARED_RANGE 0x40000002 -> 0x40000200
5566**
5567** This works well on the local file system, but shows a nearly 100x
5568** slowdown in read performance on AFP because the AFP client disables
5569** the read cache when byte-range locks are present. Enabling the read
5570** cache exposes a cache coherency problem that is present on all OS X
5571** supported network file systems. NFS and AFP both observe the
5572** close-to-open semantics for ensuring cache coherency
5573** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5574** address the requirements for concurrent database access by multiple
5575** readers and writers
5576** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5577**
5578** To address the performance and cache coherency issues, proxy file locking
5579** changes the way database access is controlled by limiting access to a
5580** single host at a time and moving file locks off of the database file
5581** and onto a proxy file on the local file system.
5582**
5583**
5584** Using proxy locks
5585** -----------------
5586**
5587** C APIs
5588**
5589** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5590** <proxy_path> | ":auto:");
5591** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5592**
5593**
5594** SQL pragmas
5595**
5596** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5597** PRAGMA [database.]lock_proxy_file
5598**
5599** Specifying ":auto:" means that if there is a conch file with a matching
5600** host ID in it, the proxy path in the conch file will be used, otherwise
5601** a proxy path based on the user's temp dir
5602** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5603** actual proxy file name is generated from the name and path of the
5604** database file. For example:
5605**
5606** For database path "/Users/me/foo.db"
5607** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5608**
5609** Once a lock proxy is configured for a database connection, it can not
5610** be removed, however it may be switched to a different proxy path via
5611** the above APIs (assuming the conch file is not being held by another
5612** connection or process).
5613**
5614**
5615** How proxy locking works
5616** -----------------------
5617**
5618** Proxy file locking relies primarily on two new supporting files:
5619**
5620** * conch file to limit access to the database file to a single host
5621** at a time
5622**
5623** * proxy file to act as a proxy for the advisory locks normally
5624** taken on the database
5625**
5626** The conch file - to use a proxy file, sqlite must first "hold the conch"
5627** by taking an sqlite-style shared lock on the conch file, reading the
5628** contents and comparing the host's unique host ID (see below) and lock
5629** proxy path against the values stored in the conch. The conch file is
5630** stored in the same directory as the database file and the file name
5631** is patterned after the database file name as ".<databasename>-conch".
5632** If the conch file does not exist, or it's contents do not match the
5633** host ID and/or proxy path, then the lock is escalated to an exclusive
5634** lock and the conch file contents is updated with the host ID and proxy
5635** path and the lock is downgraded to a shared lock again. If the conch
5636** is held by another process (with a shared lock), the exclusive lock
5637** will fail and SQLITE_BUSY is returned.
5638**
5639** The proxy file - a single-byte file used for all advisory file locks
5640** normally taken on the database file. This allows for safe sharing
5641** of the database file for multiple readers and writers on the same
5642** host (the conch ensures that they all use the same local lock file).
5643**
drh715ff302008-12-03 22:32:44 +00005644** Requesting the lock proxy does not immediately take the conch, it is
5645** only taken when the first request to lock database file is made.
5646** This matches the semantics of the traditional locking behavior, where
5647** opening a connection to a database file does not take a lock on it.
5648** The shared lock and an open file descriptor are maintained until
5649** the connection to the database is closed.
5650**
5651** The proxy file and the lock file are never deleted so they only need
5652** to be created the first time they are used.
5653**
5654** Configuration options
5655** ---------------------
5656**
5657** SQLITE_PREFER_PROXY_LOCKING
5658**
5659** Database files accessed on non-local file systems are
5660** automatically configured for proxy locking, lock files are
5661** named automatically using the same logic as
5662** PRAGMA lock_proxy_file=":auto:"
5663**
5664** SQLITE_PROXY_DEBUG
5665**
5666** Enables the logging of error messages during host id file
5667** retrieval and creation
5668**
drh715ff302008-12-03 22:32:44 +00005669** LOCKPROXYDIR
5670**
5671** Overrides the default directory used for lock proxy files that
5672** are named automatically via the ":auto:" setting
5673**
5674** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5675**
5676** Permissions to use when creating a directory for storing the
5677** lock proxy files, only used when LOCKPROXYDIR is not set.
5678**
5679**
5680** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5681** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5682** force proxy locking to be used for every database file opened, and 0
5683** will force automatic proxy locking to be disabled for all database
5684** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5685** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5686*/
5687
5688/*
5689** Proxy locking is only available on MacOSX
5690*/
drhd2cb50b2009-01-09 21:41:17 +00005691#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005692
drh715ff302008-12-03 22:32:44 +00005693/*
5694** The proxyLockingContext has the path and file structures for the remote
5695** and local proxy files in it
5696*/
5697typedef struct proxyLockingContext proxyLockingContext;
5698struct proxyLockingContext {
5699 unixFile *conchFile; /* Open conch file */
5700 char *conchFilePath; /* Name of the conch file */
5701 unixFile *lockProxy; /* Open proxy lock file */
5702 char *lockProxyPath; /* Name of the proxy lock file */
5703 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005704 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005705 void *oldLockingContext; /* Original lockingcontext to restore on close */
5706 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5707};
5708
drh7ed97b92010-01-20 13:07:21 +00005709/*
5710** The proxy lock file path for the database at dbPath is written into lPath,
5711** which must point to valid, writable memory large enough for a maxLen length
5712** file path.
drh715ff302008-12-03 22:32:44 +00005713*/
drh715ff302008-12-03 22:32:44 +00005714static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5715 int len;
5716 int dbLen;
5717 int i;
5718
5719#ifdef LOCKPROXYDIR
5720 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5721#else
5722# ifdef _CS_DARWIN_USER_TEMP_DIR
5723 {
drh7ed97b92010-01-20 13:07:21 +00005724 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005725 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5726 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005727 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005728 }
drh7ed97b92010-01-20 13:07:21 +00005729 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005730 }
5731# else
5732 len = strlcpy(lPath, "/tmp/", maxLen);
5733# endif
5734#endif
5735
5736 if( lPath[len-1]!='/' ){
5737 len = strlcat(lPath, "/", maxLen);
5738 }
5739
5740 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005741 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005742 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005743 char c = dbPath[i];
5744 lPath[i+len] = (c=='/')?'_':c;
5745 }
5746 lPath[i+len]='\0';
5747 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005748 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005749 return SQLITE_OK;
5750}
5751
drh7ed97b92010-01-20 13:07:21 +00005752/*
5753 ** Creates the lock file and any missing directories in lockPath
5754 */
5755static int proxyCreateLockPath(const char *lockPath){
5756 int i, len;
5757 char buf[MAXPATHLEN];
5758 int start = 0;
5759
5760 assert(lockPath!=NULL);
5761 /* try to create all the intermediate directories */
5762 len = (int)strlen(lockPath);
5763 buf[0] = lockPath[0];
5764 for( i=1; i<len; i++ ){
5765 if( lockPath[i] == '/' && (i - start > 0) ){
5766 /* only mkdir if leaf dir != "." or "/" or ".." */
5767 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5768 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5769 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005770 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005771 int err=errno;
5772 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005773 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005774 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005775 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005776 return err;
5777 }
5778 }
5779 }
5780 start=i+1;
5781 }
5782 buf[i] = lockPath[i];
5783 }
drh308c2a52010-05-14 11:30:18 +00005784 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005785 return 0;
5786}
5787
drh715ff302008-12-03 22:32:44 +00005788/*
5789** Create a new VFS file descriptor (stored in memory obtained from
5790** sqlite3_malloc) and open the file named "path" in the file descriptor.
5791**
5792** The caller is responsible not only for closing the file descriptor
5793** but also for freeing the memory associated with the file descriptor.
5794*/
drh7ed97b92010-01-20 13:07:21 +00005795static int proxyCreateUnixFile(
5796 const char *path, /* path for the new unixFile */
5797 unixFile **ppFile, /* unixFile created and returned by ref */
5798 int islockfile /* if non zero missing dirs will be created */
5799) {
5800 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005801 unixFile *pNew;
5802 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005803 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005804 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005805 int terrno = 0;
5806 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005807
drh7ed97b92010-01-20 13:07:21 +00005808 /* 1. first try to open/create the file
5809 ** 2. if that fails, and this is a lock file (not-conch), try creating
5810 ** the parent directories and then try again.
5811 ** 3. if that fails, try to open the file read-only
5812 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5813 */
5814 pUnused = findReusableFd(path, openFlags);
5815 if( pUnused ){
5816 fd = pUnused->fd;
5817 }else{
5818 pUnused = sqlite3_malloc(sizeof(*pUnused));
5819 if( !pUnused ){
5820 return SQLITE_NOMEM;
5821 }
5822 }
5823 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005824 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005825 terrno = errno;
5826 if( fd<0 && errno==ENOENT && islockfile ){
5827 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005828 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005829 }
5830 }
5831 }
5832 if( fd<0 ){
5833 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005834 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005835 terrno = errno;
5836 }
5837 if( fd<0 ){
5838 if( islockfile ){
5839 return SQLITE_BUSY;
5840 }
5841 switch (terrno) {
5842 case EACCES:
5843 return SQLITE_PERM;
5844 case EIO:
5845 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5846 default:
drh9978c972010-02-23 17:36:32 +00005847 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005848 }
5849 }
5850
5851 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5852 if( pNew==NULL ){
5853 rc = SQLITE_NOMEM;
5854 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005855 }
5856 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005857 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005858 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005859 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005860 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005861 pUnused->fd = fd;
5862 pUnused->flags = openFlags;
5863 pNew->pUnused = pUnused;
5864
drh0059eae2011-08-08 23:48:40 +00005865 rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
drh7ed97b92010-01-20 13:07:21 +00005866 if( rc==SQLITE_OK ){
5867 *ppFile = pNew;
5868 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005869 }
drh7ed97b92010-01-20 13:07:21 +00005870end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005871 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005872 sqlite3_free(pNew);
5873 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005874 return rc;
5875}
5876
drh7ed97b92010-01-20 13:07:21 +00005877#ifdef SQLITE_TEST
5878/* simulate multiple hosts by creating unique hostid file paths */
5879int sqlite3_hostid_num = 0;
5880#endif
5881
5882#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5883
drh0ab216a2010-07-02 17:10:40 +00005884/* Not always defined in the headers as it ought to be */
5885extern int gethostuuid(uuid_t id, const struct timespec *wait);
5886
drh7ed97b92010-01-20 13:07:21 +00005887/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5888** bytes of writable memory.
5889*/
5890static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005891 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5892 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005893#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5894 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005895 {
5896 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5897 if( gethostuuid(pHostID, &timeout) ){
5898 int err = errno;
5899 if( pError ){
5900 *pError = err;
5901 }
5902 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005903 }
drh7ed97b92010-01-20 13:07:21 +00005904 }
drh3d4435b2011-08-26 20:55:50 +00005905#else
5906 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005907#endif
drh7ed97b92010-01-20 13:07:21 +00005908#ifdef SQLITE_TEST
5909 /* simulate multiple hosts by creating unique hostid file paths */
5910 if( sqlite3_hostid_num != 0){
5911 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5912 }
5913#endif
5914
5915 return SQLITE_OK;
5916}
5917
5918/* The conch file contains the header, host id and lock file path
5919 */
5920#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5921#define PROXY_HEADERLEN 1 /* conch file header length */
5922#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5923#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5924
5925/*
5926** Takes an open conch file, copies the contents to a new path and then moves
5927** it back. The newly created file's file descriptor is assigned to the
5928** conch file structure and finally the original conch file descriptor is
5929** closed. Returns zero if successful.
5930*/
5931static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5932 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5933 unixFile *conchFile = pCtx->conchFile;
5934 char tPath[MAXPATHLEN];
5935 char buf[PROXY_MAXCONCHLEN];
5936 char *cPath = pCtx->conchFilePath;
5937 size_t readLen = 0;
5938 size_t pathLen = 0;
5939 char errmsg[64] = "";
5940 int fd = -1;
5941 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005942 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005943
5944 /* create a new path by replace the trailing '-conch' with '-break' */
5945 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5946 if( pathLen>MAXPATHLEN || pathLen<6 ||
5947 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005948 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005949 goto end_breaklock;
5950 }
5951 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005952 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005953 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005954 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005955 goto end_breaklock;
5956 }
5957 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005958 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5959 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005960 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005961 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005962 goto end_breaklock;
5963 }
drhe562be52011-03-02 18:01:10 +00005964 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00005965 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005966 goto end_breaklock;
5967 }
5968 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00005969 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005970 goto end_breaklock;
5971 }
5972 rc = 0;
5973 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00005974 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005975 conchFile->h = fd;
5976 conchFile->openFlags = O_RDWR | O_CREAT;
5977
5978end_breaklock:
5979 if( rc ){
5980 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00005981 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00005982 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005983 }
5984 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5985 }
5986 return rc;
5987}
5988
5989/* Take the requested lock on the conch file and break a stale lock if the
5990** host id matches.
5991*/
5992static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5993 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5994 unixFile *conchFile = pCtx->conchFile;
5995 int rc = SQLITE_OK;
5996 int nTries = 0;
5997 struct timespec conchModTime;
5998
drh3d4435b2011-08-26 20:55:50 +00005999 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006000 do {
6001 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6002 nTries ++;
6003 if( rc==SQLITE_BUSY ){
6004 /* If the lock failed (busy):
6005 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6006 * 2nd try: fail if the mod time changed or host id is different, wait
6007 * 10 sec and try again
6008 * 3rd try: break the lock unless the mod time has changed.
6009 */
6010 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006011 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006012 pFile->lastErrno = errno;
6013 return SQLITE_IOERR_LOCK;
6014 }
6015
6016 if( nTries==1 ){
6017 conchModTime = buf.st_mtimespec;
6018 usleep(500000); /* wait 0.5 sec and try the lock again*/
6019 continue;
6020 }
6021
6022 assert( nTries>1 );
6023 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6024 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6025 return SQLITE_BUSY;
6026 }
6027
6028 if( nTries==2 ){
6029 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006030 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006031 if( len<0 ){
6032 pFile->lastErrno = errno;
6033 return SQLITE_IOERR_LOCK;
6034 }
6035 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6036 /* don't break the lock if the host id doesn't match */
6037 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6038 return SQLITE_BUSY;
6039 }
6040 }else{
6041 /* don't break the lock on short read or a version mismatch */
6042 return SQLITE_BUSY;
6043 }
6044 usleep(10000000); /* wait 10 sec and try the lock again */
6045 continue;
6046 }
6047
6048 assert( nTries==3 );
6049 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6050 rc = SQLITE_OK;
6051 if( lockType==EXCLUSIVE_LOCK ){
6052 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6053 }
6054 if( !rc ){
6055 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6056 }
6057 }
6058 }
6059 } while( rc==SQLITE_BUSY && nTries<3 );
6060
6061 return rc;
6062}
6063
6064/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006065** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6066** lockPath means that the lockPath in the conch file will be used if the
6067** host IDs match, or a new lock path will be generated automatically
6068** and written to the conch file.
6069*/
6070static int proxyTakeConch(unixFile *pFile){
6071 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6072
drh7ed97b92010-01-20 13:07:21 +00006073 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006074 return SQLITE_OK;
6075 }else{
6076 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006077 uuid_t myHostID;
6078 int pError = 0;
6079 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006080 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006081 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006082 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006083 int createConch = 0;
6084 int hostIdMatch = 0;
6085 int readLen = 0;
6086 int tryOldLockPath = 0;
6087 int forceNewLockPath = 0;
6088
drh308c2a52010-05-14 11:30:18 +00006089 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6090 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006091
drh7ed97b92010-01-20 13:07:21 +00006092 rc = proxyGetHostID(myHostID, &pError);
6093 if( (rc&0xff)==SQLITE_IOERR ){
6094 pFile->lastErrno = pError;
6095 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006096 }
drh7ed97b92010-01-20 13:07:21 +00006097 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006098 if( rc!=SQLITE_OK ){
6099 goto end_takeconch;
6100 }
drh7ed97b92010-01-20 13:07:21 +00006101 /* read the existing conch file */
6102 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6103 if( readLen<0 ){
6104 /* I/O error: lastErrno set by seekAndRead */
6105 pFile->lastErrno = conchFile->lastErrno;
6106 rc = SQLITE_IOERR_READ;
6107 goto end_takeconch;
6108 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6109 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6110 /* a short read or version format mismatch means we need to create a new
6111 ** conch file.
6112 */
6113 createConch = 1;
6114 }
6115 /* if the host id matches and the lock path already exists in the conch
6116 ** we'll try to use the path there, if we can't open that path, we'll
6117 ** retry with a new auto-generated path
6118 */
6119 do { /* in case we need to try again for an :auto: named lock file */
6120
6121 if( !createConch && !forceNewLockPath ){
6122 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6123 PROXY_HOSTIDLEN);
6124 /* if the conch has data compare the contents */
6125 if( !pCtx->lockProxyPath ){
6126 /* for auto-named local lock file, just check the host ID and we'll
6127 ** use the local lock file path that's already in there
6128 */
6129 if( hostIdMatch ){
6130 size_t pathLen = (readLen - PROXY_PATHINDEX);
6131
6132 if( pathLen>=MAXPATHLEN ){
6133 pathLen=MAXPATHLEN-1;
6134 }
6135 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6136 lockPath[pathLen] = 0;
6137 tempLockPath = lockPath;
6138 tryOldLockPath = 1;
6139 /* create a copy of the lock path if the conch is taken */
6140 goto end_takeconch;
6141 }
6142 }else if( hostIdMatch
6143 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6144 readLen-PROXY_PATHINDEX)
6145 ){
6146 /* conch host and lock path match */
6147 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006148 }
drh7ed97b92010-01-20 13:07:21 +00006149 }
6150
6151 /* if the conch isn't writable and doesn't match, we can't take it */
6152 if( (conchFile->openFlags&O_RDWR) == 0 ){
6153 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006154 goto end_takeconch;
6155 }
drh7ed97b92010-01-20 13:07:21 +00006156
6157 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006158 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006159 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6160 tempLockPath = lockPath;
6161 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006162 }
drh7ed97b92010-01-20 13:07:21 +00006163
6164 /* update conch with host and path (this will fail if other process
6165 ** has a shared lock already), if the host id matches, use the big
6166 ** stick.
drh715ff302008-12-03 22:32:44 +00006167 */
drh7ed97b92010-01-20 13:07:21 +00006168 futimes(conchFile->h, NULL);
6169 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006170 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006171 /* We are trying for an exclusive lock but another thread in this
6172 ** same process is still holding a shared lock. */
6173 rc = SQLITE_BUSY;
6174 } else {
6175 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006176 }
drh715ff302008-12-03 22:32:44 +00006177 }else{
drh7ed97b92010-01-20 13:07:21 +00006178 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006179 }
drh7ed97b92010-01-20 13:07:21 +00006180 if( rc==SQLITE_OK ){
6181 char writeBuffer[PROXY_MAXCONCHLEN];
6182 int writeSize = 0;
6183
6184 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6185 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6186 if( pCtx->lockProxyPath!=NULL ){
6187 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6188 }else{
6189 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6190 }
6191 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006192 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006193 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6194 fsync(conchFile->h);
6195 /* If we created a new conch file (not just updated the contents of a
6196 ** valid conch file), try to match the permissions of the database
6197 */
6198 if( rc==SQLITE_OK && createConch ){
6199 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006200 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006201 if( err==0 ){
6202 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6203 S_IROTH|S_IWOTH);
6204 /* try to match the database file R/W permissions, ignore failure */
6205#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006206 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006207#else
drhff812312011-02-23 13:33:46 +00006208 do{
drhe562be52011-03-02 18:01:10 +00006209 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006210 }while( rc==(-1) && errno==EINTR );
6211 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006212 int code = errno;
6213 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6214 cmode, code, strerror(code));
6215 } else {
6216 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6217 }
6218 }else{
6219 int code = errno;
6220 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6221 err, code, strerror(code));
6222#endif
6223 }
drh715ff302008-12-03 22:32:44 +00006224 }
6225 }
drh7ed97b92010-01-20 13:07:21 +00006226 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6227
6228 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006229 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006230 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006231 int fd;
drh7ed97b92010-01-20 13:07:21 +00006232 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006233 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006234 }
6235 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006236 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006237 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006238 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006239 if( fd>=0 ){
6240 pFile->h = fd;
6241 }else{
drh9978c972010-02-23 17:36:32 +00006242 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006243 during locking */
6244 }
6245 }
6246 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6247 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6248 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6249 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6250 /* we couldn't create the proxy lock file with the old lock file path
6251 ** so try again via auto-naming
6252 */
6253 forceNewLockPath = 1;
6254 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006255 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006256 }
6257 }
6258 if( rc==SQLITE_OK ){
6259 /* Need to make a copy of path if we extracted the value
6260 ** from the conch file or the path was allocated on the stack
6261 */
6262 if( tempLockPath ){
6263 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6264 if( !pCtx->lockProxyPath ){
6265 rc = SQLITE_NOMEM;
6266 }
6267 }
6268 }
6269 if( rc==SQLITE_OK ){
6270 pCtx->conchHeld = 1;
6271
6272 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6273 afpLockingContext *afpCtx;
6274 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6275 afpCtx->dbPath = pCtx->lockProxyPath;
6276 }
6277 } else {
6278 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6279 }
drh308c2a52010-05-14 11:30:18 +00006280 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6281 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006282 return rc;
drh308c2a52010-05-14 11:30:18 +00006283 } while (1); /* in case we need to retry the :auto: lock file -
6284 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006285 }
6286}
6287
6288/*
6289** If pFile holds a lock on a conch file, then release that lock.
6290*/
6291static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006292 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006293 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6294 unixFile *conchFile; /* Name of the conch file */
6295
6296 pCtx = (proxyLockingContext *)pFile->lockingContext;
6297 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006298 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006299 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006300 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006301 if( pCtx->conchHeld>0 ){
6302 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6303 }
drh715ff302008-12-03 22:32:44 +00006304 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006305 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6306 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006307 return rc;
6308}
6309
6310/*
6311** Given the name of a database file, compute the name of its conch file.
6312** Store the conch filename in memory obtained from sqlite3_malloc().
6313** Make *pConchPath point to the new name. Return SQLITE_OK on success
6314** or SQLITE_NOMEM if unable to obtain memory.
6315**
6316** The caller is responsible for ensuring that the allocated memory
6317** space is eventually freed.
6318**
6319** *pConchPath is set to NULL if a memory allocation error occurs.
6320*/
6321static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6322 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006323 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006324 char *conchPath; /* buffer in which to construct conch name */
6325
6326 /* Allocate space for the conch filename and initialize the name to
6327 ** the name of the original database file. */
6328 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6329 if( conchPath==0 ){
6330 return SQLITE_NOMEM;
6331 }
6332 memcpy(conchPath, dbPath, len+1);
6333
6334 /* now insert a "." before the last / character */
6335 for( i=(len-1); i>=0; i-- ){
6336 if( conchPath[i]=='/' ){
6337 i++;
6338 break;
6339 }
6340 }
6341 conchPath[i]='.';
6342 while ( i<len ){
6343 conchPath[i+1]=dbPath[i];
6344 i++;
6345 }
6346
6347 /* append the "-conch" suffix to the file */
6348 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006349 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006350
6351 return SQLITE_OK;
6352}
6353
6354
6355/* Takes a fully configured proxy locking-style unix file and switches
6356** the local lock file path
6357*/
6358static int switchLockProxyPath(unixFile *pFile, const char *path) {
6359 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6360 char *oldPath = pCtx->lockProxyPath;
6361 int rc = SQLITE_OK;
6362
drh308c2a52010-05-14 11:30:18 +00006363 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006364 return SQLITE_BUSY;
6365 }
6366
6367 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6368 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6369 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6370 return SQLITE_OK;
6371 }else{
6372 unixFile *lockProxy = pCtx->lockProxy;
6373 pCtx->lockProxy=NULL;
6374 pCtx->conchHeld = 0;
6375 if( lockProxy!=NULL ){
6376 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6377 if( rc ) return rc;
6378 sqlite3_free(lockProxy);
6379 }
6380 sqlite3_free(oldPath);
6381 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6382 }
6383
6384 return rc;
6385}
6386
6387/*
6388** pFile is a file that has been opened by a prior xOpen call. dbPath
6389** is a string buffer at least MAXPATHLEN+1 characters in size.
6390**
6391** This routine find the filename associated with pFile and writes it
6392** int dbPath.
6393*/
6394static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006395#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006396 if( pFile->pMethod == &afpIoMethods ){
6397 /* afp style keeps a reference to the db path in the filePath field
6398 ** of the struct */
drhea678832008-12-10 19:26:22 +00006399 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006400 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6401 } else
drh715ff302008-12-03 22:32:44 +00006402#endif
6403 if( pFile->pMethod == &dotlockIoMethods ){
6404 /* dot lock style uses the locking context to store the dot lock
6405 ** file path */
6406 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6407 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6408 }else{
6409 /* all other styles use the locking context to store the db file path */
6410 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006411 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006412 }
6413 return SQLITE_OK;
6414}
6415
6416/*
6417** Takes an already filled in unix file and alters it so all file locking
6418** will be performed on the local proxy lock file. The following fields
6419** are preserved in the locking context so that they can be restored and
6420** the unix structure properly cleaned up at close time:
6421** ->lockingContext
6422** ->pMethod
6423*/
6424static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6425 proxyLockingContext *pCtx;
6426 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6427 char *lockPath=NULL;
6428 int rc = SQLITE_OK;
6429
drh308c2a52010-05-14 11:30:18 +00006430 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006431 return SQLITE_BUSY;
6432 }
6433 proxyGetDbPathForUnixFile(pFile, dbPath);
6434 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6435 lockPath=NULL;
6436 }else{
6437 lockPath=(char *)path;
6438 }
6439
drh308c2a52010-05-14 11:30:18 +00006440 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6441 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006442
6443 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6444 if( pCtx==0 ){
6445 return SQLITE_NOMEM;
6446 }
6447 memset(pCtx, 0, sizeof(*pCtx));
6448
6449 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6450 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006451 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6452 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6453 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6454 ** (c) the file system is read-only, then enable no-locking access.
6455 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6456 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6457 */
6458 struct statfs fsInfo;
6459 struct stat conchInfo;
6460 int goLockless = 0;
6461
drh99ab3b12011-03-02 15:09:07 +00006462 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006463 int err = errno;
6464 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6465 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6466 }
6467 }
6468 if( goLockless ){
6469 pCtx->conchHeld = -1; /* read only FS/ lockless */
6470 rc = SQLITE_OK;
6471 }
6472 }
drh715ff302008-12-03 22:32:44 +00006473 }
6474 if( rc==SQLITE_OK && lockPath ){
6475 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6476 }
6477
6478 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006479 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6480 if( pCtx->dbPath==NULL ){
6481 rc = SQLITE_NOMEM;
6482 }
6483 }
6484 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006485 /* all memory is allocated, proxys are created and assigned,
6486 ** switch the locking context and pMethod then return.
6487 */
drh715ff302008-12-03 22:32:44 +00006488 pCtx->oldLockingContext = pFile->lockingContext;
6489 pFile->lockingContext = pCtx;
6490 pCtx->pOldMethod = pFile->pMethod;
6491 pFile->pMethod = &proxyIoMethods;
6492 }else{
6493 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006494 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006495 sqlite3_free(pCtx->conchFile);
6496 }
drhd56b1212010-08-11 06:14:15 +00006497 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006498 sqlite3_free(pCtx->conchFilePath);
6499 sqlite3_free(pCtx);
6500 }
drh308c2a52010-05-14 11:30:18 +00006501 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6502 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006503 return rc;
6504}
6505
6506
6507/*
6508** This routine handles sqlite3_file_control() calls that are specific
6509** to proxy locking.
6510*/
6511static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6512 switch( op ){
6513 case SQLITE_GET_LOCKPROXYFILE: {
6514 unixFile *pFile = (unixFile*)id;
6515 if( pFile->pMethod == &proxyIoMethods ){
6516 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6517 proxyTakeConch(pFile);
6518 if( pCtx->lockProxyPath ){
6519 *(const char **)pArg = pCtx->lockProxyPath;
6520 }else{
6521 *(const char **)pArg = ":auto: (not held)";
6522 }
6523 } else {
6524 *(const char **)pArg = NULL;
6525 }
6526 return SQLITE_OK;
6527 }
6528 case SQLITE_SET_LOCKPROXYFILE: {
6529 unixFile *pFile = (unixFile*)id;
6530 int rc = SQLITE_OK;
6531 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6532 if( pArg==NULL || (const char *)pArg==0 ){
6533 if( isProxyStyle ){
6534 /* turn off proxy locking - not supported */
6535 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6536 }else{
6537 /* turn off proxy locking - already off - NOOP */
6538 rc = SQLITE_OK;
6539 }
6540 }else{
6541 const char *proxyPath = (const char *)pArg;
6542 if( isProxyStyle ){
6543 proxyLockingContext *pCtx =
6544 (proxyLockingContext*)pFile->lockingContext;
6545 if( !strcmp(pArg, ":auto:")
6546 || (pCtx->lockProxyPath &&
6547 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6548 ){
6549 rc = SQLITE_OK;
6550 }else{
6551 rc = switchLockProxyPath(pFile, proxyPath);
6552 }
6553 }else{
6554 /* turn on proxy file locking */
6555 rc = proxyTransformUnixFile(pFile, proxyPath);
6556 }
6557 }
6558 return rc;
6559 }
6560 default: {
6561 assert( 0 ); /* The call assures that only valid opcodes are sent */
6562 }
6563 }
6564 /*NOTREACHED*/
6565 return SQLITE_ERROR;
6566}
6567
6568/*
6569** Within this division (the proxying locking implementation) the procedures
6570** above this point are all utilities. The lock-related methods of the
6571** proxy-locking sqlite3_io_method object follow.
6572*/
6573
6574
6575/*
6576** This routine checks if there is a RESERVED lock held on the specified
6577** file by this or any other process. If such a lock is held, set *pResOut
6578** to a non-zero value otherwise *pResOut is set to zero. The return value
6579** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6580*/
6581static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6582 unixFile *pFile = (unixFile*)id;
6583 int rc = proxyTakeConch(pFile);
6584 if( rc==SQLITE_OK ){
6585 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006586 if( pCtx->conchHeld>0 ){
6587 unixFile *proxy = pCtx->lockProxy;
6588 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6589 }else{ /* conchHeld < 0 is lockless */
6590 pResOut=0;
6591 }
drh715ff302008-12-03 22:32:44 +00006592 }
6593 return rc;
6594}
6595
6596/*
drh308c2a52010-05-14 11:30:18 +00006597** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006598** of the following:
6599**
6600** (1) SHARED_LOCK
6601** (2) RESERVED_LOCK
6602** (3) PENDING_LOCK
6603** (4) EXCLUSIVE_LOCK
6604**
6605** Sometimes when requesting one lock state, additional lock states
6606** are inserted in between. The locking might fail on one of the later
6607** transitions leaving the lock state different from what it started but
6608** still short of its goal. The following chart shows the allowed
6609** transitions and the inserted intermediate states:
6610**
6611** UNLOCKED -> SHARED
6612** SHARED -> RESERVED
6613** SHARED -> (PENDING) -> EXCLUSIVE
6614** RESERVED -> (PENDING) -> EXCLUSIVE
6615** PENDING -> EXCLUSIVE
6616**
6617** This routine will only increase a lock. Use the sqlite3OsUnlock()
6618** routine to lower a locking level.
6619*/
drh308c2a52010-05-14 11:30:18 +00006620static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006621 unixFile *pFile = (unixFile*)id;
6622 int rc = proxyTakeConch(pFile);
6623 if( rc==SQLITE_OK ){
6624 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006625 if( pCtx->conchHeld>0 ){
6626 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006627 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6628 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006629 }else{
6630 /* conchHeld < 0 is lockless */
6631 }
drh715ff302008-12-03 22:32:44 +00006632 }
6633 return rc;
6634}
6635
6636
6637/*
drh308c2a52010-05-14 11:30:18 +00006638** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006639** must be either NO_LOCK or SHARED_LOCK.
6640**
6641** If the locking level of the file descriptor is already at or below
6642** the requested locking level, this routine is a no-op.
6643*/
drh308c2a52010-05-14 11:30:18 +00006644static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006645 unixFile *pFile = (unixFile*)id;
6646 int rc = proxyTakeConch(pFile);
6647 if( rc==SQLITE_OK ){
6648 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006649 if( pCtx->conchHeld>0 ){
6650 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006651 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6652 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006653 }else{
6654 /* conchHeld < 0 is lockless */
6655 }
drh715ff302008-12-03 22:32:44 +00006656 }
6657 return rc;
6658}
6659
6660/*
6661** Close a file that uses proxy locks.
6662*/
6663static int proxyClose(sqlite3_file *id) {
6664 if( id ){
6665 unixFile *pFile = (unixFile*)id;
6666 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6667 unixFile *lockProxy = pCtx->lockProxy;
6668 unixFile *conchFile = pCtx->conchFile;
6669 int rc = SQLITE_OK;
6670
6671 if( lockProxy ){
6672 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6673 if( rc ) return rc;
6674 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6675 if( rc ) return rc;
6676 sqlite3_free(lockProxy);
6677 pCtx->lockProxy = 0;
6678 }
6679 if( conchFile ){
6680 if( pCtx->conchHeld ){
6681 rc = proxyReleaseConch(pFile);
6682 if( rc ) return rc;
6683 }
6684 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6685 if( rc ) return rc;
6686 sqlite3_free(conchFile);
6687 }
drhd56b1212010-08-11 06:14:15 +00006688 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006689 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006690 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006691 /* restore the original locking context and pMethod then close it */
6692 pFile->lockingContext = pCtx->oldLockingContext;
6693 pFile->pMethod = pCtx->pOldMethod;
6694 sqlite3_free(pCtx);
6695 return pFile->pMethod->xClose(id);
6696 }
6697 return SQLITE_OK;
6698}
6699
6700
6701
drhd2cb50b2009-01-09 21:41:17 +00006702#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006703/*
6704** The proxy locking style is intended for use with AFP filesystems.
6705** And since AFP is only supported on MacOSX, the proxy locking is also
6706** restricted to MacOSX.
6707**
6708**
6709******************* End of the proxy lock implementation **********************
6710******************************************************************************/
6711
drh734c9862008-11-28 15:37:20 +00006712/*
danielk1977e339d652008-06-28 11:23:00 +00006713** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006714**
6715** This routine registers all VFS implementations for unix-like operating
6716** systems. This routine, and the sqlite3_os_end() routine that follows,
6717** should be the only routines in this file that are visible from other
6718** files.
drh6b9d6dd2008-12-03 19:34:47 +00006719**
6720** This routine is called once during SQLite initialization and by a
6721** single thread. The memory allocation and mutex subsystems have not
6722** necessarily been initialized when this routine is called, and so they
6723** should not be used.
drh153c62c2007-08-24 03:51:33 +00006724*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006725int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006726 /*
6727 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006728 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6729 ** to the "finder" function. (pAppData is a pointer to a pointer because
6730 ** silly C90 rules prohibit a void* from being cast to a function pointer
6731 ** and so we have to go through the intermediate pointer to avoid problems
6732 ** when compiling with -pedantic-errors on GCC.)
6733 **
6734 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006735 ** finder-function. The finder-function returns a pointer to the
6736 ** sqlite_io_methods object that implements the desired locking
6737 ** behaviors. See the division above that contains the IOMETHODS
6738 ** macro for addition information on finder-functions.
6739 **
6740 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6741 ** object. But the "autolockIoFinder" available on MacOSX does a little
6742 ** more than that; it looks at the filesystem type that hosts the
6743 ** database file and tries to choose an locking method appropriate for
6744 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006745 */
drh7708e972008-11-29 00:56:52 +00006746 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006747 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006748 sizeof(unixFile), /* szOsFile */ \
6749 MAX_PATHNAME, /* mxPathname */ \
6750 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006751 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006752 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006753 unixOpen, /* xOpen */ \
6754 unixDelete, /* xDelete */ \
6755 unixAccess, /* xAccess */ \
6756 unixFullPathname, /* xFullPathname */ \
6757 unixDlOpen, /* xDlOpen */ \
6758 unixDlError, /* xDlError */ \
6759 unixDlSym, /* xDlSym */ \
6760 unixDlClose, /* xDlClose */ \
6761 unixRandomness, /* xRandomness */ \
6762 unixSleep, /* xSleep */ \
6763 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006764 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006765 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006766 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006767 unixGetSystemCall, /* xGetSystemCall */ \
6768 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006769 }
6770
drh6b9d6dd2008-12-03 19:34:47 +00006771 /*
6772 ** All default VFSes for unix are contained in the following array.
6773 **
6774 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6775 ** by the SQLite core when the VFS is registered. So the following
6776 ** array cannot be const.
6777 */
danielk1977e339d652008-06-28 11:23:00 +00006778 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006779#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006780 UNIXVFS("unix", autolockIoFinder ),
6781#else
6782 UNIXVFS("unix", posixIoFinder ),
6783#endif
6784 UNIXVFS("unix-none", nolockIoFinder ),
6785 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006786 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006787#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006788 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006789#endif
6790#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006791 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006792#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006793 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006794#endif
chw78a13182009-04-07 05:35:03 +00006795#endif
drhd2cb50b2009-01-09 21:41:17 +00006796#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006797 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006798 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006799 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006800#endif
drh153c62c2007-08-24 03:51:33 +00006801 };
drh6b9d6dd2008-12-03 19:34:47 +00006802 unsigned int i; /* Loop counter */
6803
drh2aa5a002011-04-13 13:42:25 +00006804 /* Double-check that the aSyscall[] array has been constructed
6805 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8942d412012-01-02 18:20:14 +00006806 assert( ArraySize(aSyscall)==20 );
drh2aa5a002011-04-13 13:42:25 +00006807
drh6b9d6dd2008-12-03 19:34:47 +00006808 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006809 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006810 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006811 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006812 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006813}
danielk1977e339d652008-06-28 11:23:00 +00006814
6815/*
drh6b9d6dd2008-12-03 19:34:47 +00006816** Shutdown the operating system interface.
6817**
6818** Some operating systems might need to do some cleanup in this routine,
6819** to release dynamically allocated objects. But not on unix.
6820** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006821*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006822int sqlite3_os_end(void){
6823 return SQLITE_OK;
6824}
drhdce8bdb2007-08-16 13:01:44 +00006825
danielk197729bafea2008-06-26 10:41:19 +00006826#endif /* SQLITE_OS_UNIX */