blob: 3f3ebb6bf7b4395b5b6a4de2751c9167e71176f1 [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 */
drh3ee34842012-02-11 21:21:17 +0000214 unsigned short int 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 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drh8f941bc2009-01-14 23:03:40 +0000230#ifndef NDEBUG
231 /* The next group of variables are used to track whether or not the
232 ** transaction counter in bytes 24-27 of database files are updated
233 ** whenever any part of the database changes. An assertion fault will
234 ** occur if a file is updated without also updating the transaction
235 ** counter. This test is made to avoid new problems similar to the
236 ** one described by ticket #3584.
237 */
238 unsigned char transCntrChng; /* True if the transaction counter changed */
239 unsigned char dbUpdate; /* True if any part of database file changed */
240 unsigned char inNormalWrite; /* True if in a normal write operation */
241#endif
danielk1977967a4a12007-08-20 14:23:44 +0000242#ifdef SQLITE_TEST
243 /* In test mode, increase the size of this structure a bit so that
244 ** it is larger than the struct CrashFile defined in test6.c.
245 */
246 char aPadding[32];
247#endif
drh9cbe6352005-11-29 03:13:21 +0000248};
249
drh0ccebe72005-06-07 22:22:50 +0000250/*
drha7e61d82011-03-12 17:02:57 +0000251** Allowed values for the unixFile.ctrlFlags bitmask:
252*/
drhf0b190d2011-07-26 16:03:07 +0000253#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
254#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
255#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000256#ifndef SQLITE_DISABLE_DIRSYNC
257# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
258#else
259# define UNIXFILE_DIRSYNC 0x00
260#endif
drhcb15f352011-12-23 01:04:17 +0000261#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000262#define UNIXFILE_DELETE 0x20 /* Delete on close */
263#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
264#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drh3ee34842012-02-11 21:21:17 +0000265#define UNIXFILE_CHOWN 0x100 /* File ownership was changed */
drha7e61d82011-03-12 17:02:57 +0000266
267/*
drh198bf392006-01-06 21:52:49 +0000268** Include code that is common to all os_*.c files
269*/
270#include "os_common.h"
271
272/*
drh0ccebe72005-06-07 22:22:50 +0000273** Define various macros that are missing from some systems.
274*/
drhbbd42a62004-05-22 17:41:58 +0000275#ifndef O_LARGEFILE
276# define O_LARGEFILE 0
277#endif
278#ifdef SQLITE_DISABLE_LFS
279# undef O_LARGEFILE
280# define O_LARGEFILE 0
281#endif
282#ifndef O_NOFOLLOW
283# define O_NOFOLLOW 0
284#endif
285#ifndef O_BINARY
286# define O_BINARY 0
287#endif
288
289/*
drh2b4b5962005-06-15 17:47:55 +0000290** The threadid macro resolves to the thread-id or to 0. Used for
291** testing and debugging only.
292*/
drhd677b3d2007-08-20 22:48:41 +0000293#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000294#define threadid pthread_self()
295#else
296#define threadid 0
297#endif
298
drh99ab3b12011-03-02 15:09:07 +0000299/*
drh9a3baf12011-04-25 18:01:27 +0000300** Different Unix systems declare open() in different ways. Same use
301** open(const char*,int,mode_t). Others use open(const char*,int,...).
302** The difference is important when using a pointer to the function.
303**
304** The safest way to deal with the problem is to always use this wrapper
305** which always has the same well-defined interface.
306*/
307static int posixOpen(const char *zFile, int flags, int mode){
308 return open(zFile, flags, mode);
309}
310
drh90315a22011-08-10 01:52:12 +0000311/* Forward reference */
312static int openDirectory(const char*, int*);
313
drh9a3baf12011-04-25 18:01:27 +0000314/*
drh99ab3b12011-03-02 15:09:07 +0000315** Many system calls are accessed through pointer-to-functions so that
316** they may be overridden at runtime to facilitate fault injection during
317** testing and sandboxing. The following array holds the names and pointers
318** to all overrideable system calls.
319*/
320static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000321 const char *zName; /* Name of the sytem call */
322 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
323 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000324} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000325 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
326#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000327
drh58ad5802011-03-23 22:02:23 +0000328 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000329#define osClose ((int(*)(int))aSyscall[1].pCurrent)
330
drh58ad5802011-03-23 22:02:23 +0000331 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000332#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
333
drh58ad5802011-03-23 22:02:23 +0000334 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000335#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
336
drh58ad5802011-03-23 22:02:23 +0000337 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000338#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
339
340/*
341** The DJGPP compiler environment looks mostly like Unix, but it
342** lacks the fcntl() system call. So redefine fcntl() to be something
343** that always succeeds. This means that locking does not occur under
344** DJGPP. But it is DOS - what did you expect?
345*/
346#ifdef __DJGPP__
347 { "fstat", 0, 0 },
348#define osFstat(a,b,c) 0
349#else
drh58ad5802011-03-23 22:02:23 +0000350 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
352#endif
353
drh58ad5802011-03-23 22:02:23 +0000354 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
356
drh58ad5802011-03-23 22:02:23 +0000357 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000358#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000359
drh58ad5802011-03-23 22:02:23 +0000360 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000361#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
362
drhd4a80312011-04-15 14:33:20 +0000363#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000364 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000365#else
drh58ad5802011-03-23 22:02:23 +0000366 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000367#endif
368#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
369
370#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000371 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000372#else
drh58ad5802011-03-23 22:02:23 +0000373 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000374#endif
375#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
376
drh58ad5802011-03-23 22:02:23 +0000377 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000378#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
379
drhd4a80312011-04-15 14:33:20 +0000380#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000381 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000384#endif
385#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
386 aSyscall[12].pCurrent)
387
388#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000389 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000390#else
drh58ad5802011-03-23 22:02:23 +0000391 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000392#endif
393#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
394 aSyscall[13].pCurrent)
395
drha6c47492011-04-11 18:35:09 +0000396#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000398#else
399 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000400#endif
drh2aa5a002011-04-13 13:42:25 +0000401#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000402
403#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000404 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
dan0fd7d862011-03-29 10:04:23 +0000408#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000409
drh036ac7f2011-08-08 23:18:05 +0000410 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
411#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
412
drh90315a22011-08-10 01:52:12 +0000413 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
414#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
415
drh9ef6bc42011-11-04 02:24:02 +0000416 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
417#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
418
419 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
420#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
421
drhe562be52011-03-02 18:01:10 +0000422}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000423
424/*
425** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000426** "unix" VFSes. Return SQLITE_OK opon successfully updating the
427** system call pointer, or SQLITE_NOTFOUND if there is no configurable
428** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000429*/
430static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000431 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
432 const char *zName, /* Name of system call to override */
433 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000434){
drh58ad5802011-03-23 22:02:23 +0000435 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000436 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000437
438 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000439 if( zName==0 ){
440 /* If no zName is given, restore all system calls to their default
441 ** settings and return NULL
442 */
dan51438a72011-04-02 17:00:47 +0000443 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000444 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
445 if( aSyscall[i].pDefault ){
446 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000447 }
448 }
449 }else{
450 /* If zName is specified, operate on only the one system call
451 ** specified.
452 */
453 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
454 if( strcmp(zName, aSyscall[i].zName)==0 ){
455 if( aSyscall[i].pDefault==0 ){
456 aSyscall[i].pDefault = aSyscall[i].pCurrent;
457 }
drh1df30962011-03-02 19:06:42 +0000458 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000459 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
460 aSyscall[i].pCurrent = pNewFunc;
461 break;
462 }
463 }
464 }
465 return rc;
466}
467
drh1df30962011-03-02 19:06:42 +0000468/*
469** Return the value of a system call. Return NULL if zName is not a
470** recognized system call name. NULL is also returned if the system call
471** is currently undefined.
472*/
drh58ad5802011-03-23 22:02:23 +0000473static sqlite3_syscall_ptr unixGetSystemCall(
474 sqlite3_vfs *pNotUsed,
475 const char *zName
476){
477 unsigned int i;
478
479 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000480 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
481 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
482 }
483 return 0;
484}
485
486/*
487** Return the name of the first system call after zName. If zName==NULL
488** then return the name of the first system call. Return NULL if zName
489** is the last system call or if zName is not the name of a valid
490** system call.
491*/
492static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000493 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000494
495 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000496 if( zName ){
497 for(i=0; i<ArraySize(aSyscall)-1; i++){
498 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000499 }
500 }
dan0fd7d862011-03-29 10:04:23 +0000501 for(i++; i<ArraySize(aSyscall); i++){
502 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000503 }
504 return 0;
505}
506
drhad4f1e52011-03-04 15:43:57 +0000507/*
508** Retry open() calls that fail due to EINTR
509*/
510static int robust_open(const char *z, int f, int m){
511 int rc;
512 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
513 return rc;
514}
danielk197713adf8a2004-06-03 16:08:41 +0000515
drh107886a2008-11-21 22:21:50 +0000516/*
dan9359c7b2009-08-21 08:29:10 +0000517** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000518** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000519** vxworksFileId objects used by this file, all of which may be
520** shared by multiple threads.
521**
522** Function unixMutexHeld() is used to assert() that the global mutex
523** is held when required. This function is only used as part of assert()
524** statements. e.g.
525**
526** unixEnterMutex()
527** assert( unixMutexHeld() );
528** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000529*/
530static void unixEnterMutex(void){
531 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
532}
533static void unixLeaveMutex(void){
534 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
535}
dan9359c7b2009-08-21 08:29:10 +0000536#ifdef SQLITE_DEBUG
537static int unixMutexHeld(void) {
538 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
539}
540#endif
drh107886a2008-11-21 22:21:50 +0000541
drh734c9862008-11-28 15:37:20 +0000542
drh30ddce62011-10-15 00:16:30 +0000543#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000544/*
545** Helper function for printing out trace information from debugging
546** binaries. This returns the string represetation of the supplied
547** integer lock-type.
548*/
drh308c2a52010-05-14 11:30:18 +0000549static const char *azFileLock(int eFileLock){
550 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000551 case NO_LOCK: return "NONE";
552 case SHARED_LOCK: return "SHARED";
553 case RESERVED_LOCK: return "RESERVED";
554 case PENDING_LOCK: return "PENDING";
555 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000556 }
557 return "ERROR";
558}
559#endif
560
561#ifdef SQLITE_LOCK_TRACE
562/*
563** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000564**
drh734c9862008-11-28 15:37:20 +0000565** This routine is used for troubleshooting locks on multithreaded
566** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
567** command-line option on the compiler. This code is normally
568** turned off.
569*/
570static int lockTrace(int fd, int op, struct flock *p){
571 char *zOpName, *zType;
572 int s;
573 int savedErrno;
574 if( op==F_GETLK ){
575 zOpName = "GETLK";
576 }else if( op==F_SETLK ){
577 zOpName = "SETLK";
578 }else{
drh99ab3b12011-03-02 15:09:07 +0000579 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000580 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
581 return s;
582 }
583 if( p->l_type==F_RDLCK ){
584 zType = "RDLCK";
585 }else if( p->l_type==F_WRLCK ){
586 zType = "WRLCK";
587 }else if( p->l_type==F_UNLCK ){
588 zType = "UNLCK";
589 }else{
590 assert( 0 );
591 }
592 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000593 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000594 savedErrno = errno;
595 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
596 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
597 (int)p->l_pid, s);
598 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
599 struct flock l2;
600 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000601 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000602 if( l2.l_type==F_RDLCK ){
603 zType = "RDLCK";
604 }else if( l2.l_type==F_WRLCK ){
605 zType = "WRLCK";
606 }else if( l2.l_type==F_UNLCK ){
607 zType = "UNLCK";
608 }else{
609 assert( 0 );
610 }
611 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
612 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
613 }
614 errno = savedErrno;
615 return s;
616}
drh99ab3b12011-03-02 15:09:07 +0000617#undef osFcntl
618#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000619#endif /* SQLITE_LOCK_TRACE */
620
drhff812312011-02-23 13:33:46 +0000621/*
622** Retry ftruncate() calls that fail due to EINTR
623*/
drhff812312011-02-23 13:33:46 +0000624static int robust_ftruncate(int h, sqlite3_int64 sz){
625 int rc;
drh99ab3b12011-03-02 15:09:07 +0000626 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000627 return rc;
628}
drh734c9862008-11-28 15:37:20 +0000629
630/*
631** This routine translates a standard POSIX errno code into something
632** useful to the clients of the sqlite3 functions. Specifically, it is
633** intended to translate a variety of "try again" errors into SQLITE_BUSY
634** and a variety of "please close the file descriptor NOW" errors into
635** SQLITE_IOERR
636**
637** Errors during initialization of locks, or file system support for locks,
638** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
639*/
640static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
641 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000642#if 0
643 /* At one point this code was not commented out. In theory, this branch
644 ** should never be hit, as this function should only be called after
645 ** a locking-related function (i.e. fcntl()) has returned non-zero with
646 ** the value of errno as the first argument. Since a system call has failed,
647 ** errno should be non-zero.
648 **
649 ** Despite this, if errno really is zero, we still don't want to return
650 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
651 ** propagated back to the caller. Commenting this branch out means errno==0
652 ** will be handled by the "default:" case below.
653 */
drh734c9862008-11-28 15:37:20 +0000654 case 0:
655 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000656#endif
657
drh734c9862008-11-28 15:37:20 +0000658 case EAGAIN:
659 case ETIMEDOUT:
660 case EBUSY:
661 case EINTR:
662 case ENOLCK:
663 /* random NFS retry error, unless during file system support
664 * introspection, in which it actually means what it says */
665 return SQLITE_BUSY;
666
667 case EACCES:
668 /* EACCES is like EAGAIN during locking operations, but not any other time*/
669 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
670 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
671 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
672 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
673 return SQLITE_BUSY;
674 }
675 /* else fall through */
676 case EPERM:
677 return SQLITE_PERM;
678
danea83bc62011-04-01 11:56:32 +0000679 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
680 ** this module never makes such a call. And the code in SQLite itself
681 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
682 ** this case is also commented out. If the system does set errno to EDEADLK,
683 ** the default SQLITE_IOERR_XXX code will be returned. */
684#if 0
drh734c9862008-11-28 15:37:20 +0000685 case EDEADLK:
686 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000687#endif
drh734c9862008-11-28 15:37:20 +0000688
689#if EOPNOTSUPP!=ENOTSUP
690 case EOPNOTSUPP:
691 /* something went terribly awry, unless during file system support
692 * introspection, in which it actually means what it says */
693#endif
694#ifdef ENOTSUP
695 case ENOTSUP:
696 /* invalid fd, unless during file system support introspection, in which
697 * it actually means what it says */
698#endif
699 case EIO:
700 case EBADF:
701 case EINVAL:
702 case ENOTCONN:
703 case ENODEV:
704 case ENXIO:
705 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000706#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000707 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000708#endif
drh734c9862008-11-28 15:37:20 +0000709 case ENOSYS:
710 /* these should force the client to close the file and reconnect */
711
712 default:
713 return sqliteIOErr;
714 }
715}
716
717
718
719/******************************************************************************
720****************** Begin Unique File ID Utility Used By VxWorks ***************
721**
722** On most versions of unix, we can get a unique ID for a file by concatenating
723** the device number and the inode number. But this does not work on VxWorks.
724** On VxWorks, a unique file id must be based on the canonical filename.
725**
726** A pointer to an instance of the following structure can be used as a
727** unique file ID in VxWorks. Each instance of this structure contains
728** a copy of the canonical filename. There is also a reference count.
729** The structure is reclaimed when the number of pointers to it drops to
730** zero.
731**
732** There are never very many files open at one time and lookups are not
733** a performance-critical path, so it is sufficient to put these
734** structures on a linked list.
735*/
736struct vxworksFileId {
737 struct vxworksFileId *pNext; /* Next in a list of them all */
738 int nRef; /* Number of references to this one */
739 int nName; /* Length of the zCanonicalName[] string */
740 char *zCanonicalName; /* Canonical filename */
741};
742
743#if OS_VXWORKS
744/*
drh9b35ea62008-11-29 02:20:26 +0000745** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000746** variable:
747*/
748static struct vxworksFileId *vxworksFileList = 0;
749
750/*
751** Simplify a filename into its canonical form
752** by making the following changes:
753**
754** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000755** * convert /./ into just /
756** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000757**
758** Changes are made in-place. Return the new name length.
759**
760** The original filename is in z[0..n-1]. Return the number of
761** characters in the simplified name.
762*/
763static int vxworksSimplifyName(char *z, int n){
764 int i, j;
765 while( n>1 && z[n-1]=='/' ){ n--; }
766 for(i=j=0; i<n; i++){
767 if( z[i]=='/' ){
768 if( z[i+1]=='/' ) continue;
769 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
770 i += 1;
771 continue;
772 }
773 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
774 while( j>0 && z[j-1]!='/' ){ j--; }
775 if( j>0 ){ j--; }
776 i += 2;
777 continue;
778 }
779 }
780 z[j++] = z[i];
781 }
782 z[j] = 0;
783 return j;
784}
785
786/*
787** Find a unique file ID for the given absolute pathname. Return
788** a pointer to the vxworksFileId object. This pointer is the unique
789** file ID.
790**
791** The nRef field of the vxworksFileId object is incremented before
792** the object is returned. A new vxworksFileId object is created
793** and added to the global list if necessary.
794**
795** If a memory allocation error occurs, return NULL.
796*/
797static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
798 struct vxworksFileId *pNew; /* search key and new file ID */
799 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
800 int n; /* Length of zAbsoluteName string */
801
802 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000803 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000804 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
805 if( pNew==0 ) return 0;
806 pNew->zCanonicalName = (char*)&pNew[1];
807 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
808 n = vxworksSimplifyName(pNew->zCanonicalName, n);
809
810 /* Search for an existing entry that matching the canonical name.
811 ** If found, increment the reference count and return a pointer to
812 ** the existing file ID.
813 */
814 unixEnterMutex();
815 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
816 if( pCandidate->nName==n
817 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
818 ){
819 sqlite3_free(pNew);
820 pCandidate->nRef++;
821 unixLeaveMutex();
822 return pCandidate;
823 }
824 }
825
826 /* No match was found. We will make a new file ID */
827 pNew->nRef = 1;
828 pNew->nName = n;
829 pNew->pNext = vxworksFileList;
830 vxworksFileList = pNew;
831 unixLeaveMutex();
832 return pNew;
833}
834
835/*
836** Decrement the reference count on a vxworksFileId object. Free
837** the object when the reference count reaches zero.
838*/
839static void vxworksReleaseFileId(struct vxworksFileId *pId){
840 unixEnterMutex();
841 assert( pId->nRef>0 );
842 pId->nRef--;
843 if( pId->nRef==0 ){
844 struct vxworksFileId **pp;
845 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
846 assert( *pp==pId );
847 *pp = pId->pNext;
848 sqlite3_free(pId);
849 }
850 unixLeaveMutex();
851}
852#endif /* OS_VXWORKS */
853/*************** End of Unique File ID Utility Used By VxWorks ****************
854******************************************************************************/
855
856
857/******************************************************************************
858*************************** Posix Advisory Locking ****************************
859**
drh9b35ea62008-11-29 02:20:26 +0000860** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000861** section 6.5.2.2 lines 483 through 490 specify that when a process
862** sets or clears a lock, that operation overrides any prior locks set
863** by the same process. It does not explicitly say so, but this implies
864** that it overrides locks set by the same process using a different
865** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000866**
867** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000868** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
869**
870** Suppose ./file1 and ./file2 are really the same file (because
871** one is a hard or symbolic link to the other) then if you set
872** an exclusive lock on fd1, then try to get an exclusive lock
873** on fd2, it works. I would have expected the second lock to
874** fail since there was already a lock on the file due to fd1.
875** But not so. Since both locks came from the same process, the
876** second overrides the first, even though they were on different
877** file descriptors opened on different file names.
878**
drh734c9862008-11-28 15:37:20 +0000879** This means that we cannot use POSIX locks to synchronize file access
880** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000881** to synchronize access for threads in separate processes, but not
882** threads within the same process.
883**
884** To work around the problem, SQLite has to manage file locks internally
885** on its own. Whenever a new database is opened, we have to find the
886** specific inode of the database file (the inode is determined by the
887** st_dev and st_ino fields of the stat structure that fstat() fills in)
888** and check for locks already existing on that inode. When locks are
889** created or removed, we have to look at our own internal record of the
890** locks to see if another thread has previously set a lock on that same
891** inode.
892**
drh9b35ea62008-11-29 02:20:26 +0000893** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
894** For VxWorks, we have to use the alternative unique ID system based on
895** canonical filename and implemented in the previous division.)
896**
danielk1977ad94b582007-08-20 06:44:22 +0000897** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000898** descriptor. It is now a structure that holds the integer file
899** descriptor and a pointer to a structure that describes the internal
900** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000901** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000902** point to the same locking structure. The locking structure keeps
903** a reference count (so we will know when to delete it) and a "cnt"
904** field that tells us its internal lock status. cnt==0 means the
905** file is unlocked. cnt==-1 means the file has an exclusive lock.
906** cnt>0 means there are cnt shared locks on the file.
907**
908** Any attempt to lock or unlock a file first checks the locking
909** structure. The fcntl() system call is only invoked to set a
910** POSIX lock if the internal lock structure transitions between
911** a locked and an unlocked state.
912**
drh734c9862008-11-28 15:37:20 +0000913** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000914**
915** If you close a file descriptor that points to a file that has locks,
916** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000917** released. To work around this problem, each unixInodeInfo object
918** maintains a count of the number of pending locks on tha inode.
919** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000920** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000921** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000922** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000923** be closed and that list is walked (and cleared) when the last lock
924** clears.
925**
drh9b35ea62008-11-29 02:20:26 +0000926** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000927**
drh9b35ea62008-11-29 02:20:26 +0000928** Many older versions of linux use the LinuxThreads library which is
929** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000930** A cannot be modified or overridden by a different thread B.
931** Only thread A can modify the lock. Locking behavior is correct
932** if the appliation uses the newer Native Posix Thread Library (NPTL)
933** on linux - with NPTL a lock created by thread A can override locks
934** in thread B. But there is no way to know at compile-time which
935** threading library is being used. So there is no way to know at
936** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000937** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000938** current process.
drh5fdae772004-06-29 03:29:00 +0000939**
drh8af6c222010-05-14 12:43:01 +0000940** SQLite used to support LinuxThreads. But support for LinuxThreads
941** was dropped beginning with version 3.7.0. SQLite will still work with
942** LinuxThreads provided that (1) there is no more than one connection
943** per database file in the same process and (2) database connections
944** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000945*/
946
947/*
948** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000949** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000950*/
951struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000952 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000953#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000954 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000955#else
drh107886a2008-11-21 22:21:50 +0000956 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000957#endif
958};
959
960/*
drhbbd42a62004-05-22 17:41:58 +0000961** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000962** inode. Or, on LinuxThreads, there is one of these structures for
963** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000964**
danielk1977ad94b582007-08-20 06:44:22 +0000965** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000966** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000967** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000968*/
drh8af6c222010-05-14 12:43:01 +0000969struct unixInodeInfo {
970 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000971 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000972 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
973 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000974 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000975 unixShmNode *pShmNode; /* Shared memory associated with this inode */
976 int nLock; /* Number of outstanding file locks */
977 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
978 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
979 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000980#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000981 unsigned long long sharedByte; /* for AFP simulated shared lock */
982#endif
drh6c7d5c52008-11-21 20:32:33 +0000983#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000984 sem_t *pSem; /* Named POSIX semaphore */
985 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000986#endif
drhbbd42a62004-05-22 17:41:58 +0000987};
988
drhda0e7682008-07-30 15:27:54 +0000989/*
drh8af6c222010-05-14 12:43:01 +0000990** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000991*/
drhd91c68f2010-05-14 14:52:25 +0000992static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000993
drh5fdae772004-06-29 03:29:00 +0000994/*
dane18d4952011-02-21 11:46:24 +0000995**
996** This function - unixLogError_x(), is only ever called via the macro
997** unixLogError().
998**
999** It is invoked after an error occurs in an OS function and errno has been
1000** set. It logs a message using sqlite3_log() containing the current value of
1001** errno and, if possible, the human-readable equivalent from strerror() or
1002** strerror_r().
1003**
1004** The first argument passed to the macro should be the error code that
1005** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1006** The two subsequent arguments should be the name of the OS function that
1007** failed (e.g. "unlink", "open") and the the associated file-system path,
1008** if any.
1009*/
drh0e9365c2011-03-02 02:08:13 +00001010#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1011static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001012 int errcode, /* SQLite error code */
1013 const char *zFunc, /* Name of OS function that failed */
1014 const char *zPath, /* File path associated with error */
1015 int iLine /* Source line number where error occurred */
1016){
1017 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001018 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001019
1020 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1021 ** the strerror() function to obtain the human-readable error message
1022 ** equivalent to errno. Otherwise, use strerror_r().
1023 */
1024#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1025 char aErr[80];
1026 memset(aErr, 0, sizeof(aErr));
1027 zErr = aErr;
1028
1029 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1030 ** assume that the system provides the the GNU version of strerror_r() that
1031 ** returns a pointer to a buffer containing the error message. That pointer
1032 ** may point to aErr[], or it may point to some static storage somewhere.
1033 ** Otherwise, assume that the system provides the POSIX version of
1034 ** strerror_r(), which always writes an error message into aErr[].
1035 **
1036 ** If the code incorrectly assumes that it is the POSIX version that is
1037 ** available, the error message will often be an empty string. Not a
1038 ** huge problem. Incorrectly concluding that the GNU version is available
1039 ** could lead to a segfault though.
1040 */
1041#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1042 zErr =
1043# endif
drh0e9365c2011-03-02 02:08:13 +00001044 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001045
1046#elif SQLITE_THREADSAFE
1047 /* This is a threadsafe build, but strerror_r() is not available. */
1048 zErr = "";
1049#else
1050 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001051 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001052#endif
1053
1054 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001055 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001056 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001057 "os_unix.c:%d: (%d) %s(%s) - %s",
1058 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001059 );
1060
1061 return errcode;
1062}
1063
drh0e9365c2011-03-02 02:08:13 +00001064/*
1065** Close a file descriptor.
1066**
1067** We assume that close() almost always works, since it is only in a
1068** very sick application or on a very sick platform that it might fail.
1069** If it does fail, simply leak the file descriptor, but do log the
1070** error.
1071**
1072** Note that it is not safe to retry close() after EINTR since the
1073** file descriptor might have already been reused by another thread.
1074** So we don't even try to recover from an EINTR. Just log the error
1075** and move on.
1076*/
1077static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001078 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001079 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1080 pFile ? pFile->zPath : 0, lineno);
1081 }
1082}
dane18d4952011-02-21 11:46:24 +00001083
1084/*
danb0ac3e32010-06-16 10:55:42 +00001085** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001086*/
drh0e9365c2011-03-02 02:08:13 +00001087static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001088 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001089 UnixUnusedFd *p;
1090 UnixUnusedFd *pNext;
1091 for(p=pInode->pUnused; p; p=pNext){
1092 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001093 robust_close(pFile, p->fd, __LINE__);
1094 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001095 }
drh0e9365c2011-03-02 02:08:13 +00001096 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001097}
1098
1099/*
drh8af6c222010-05-14 12:43:01 +00001100** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001101**
1102** The mutex entered using the unixEnterMutex() function must be held
1103** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001104*/
danb0ac3e32010-06-16 10:55:42 +00001105static void releaseInodeInfo(unixFile *pFile){
1106 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001107 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001108 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001109 pInode->nRef--;
1110 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001111 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001112 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001113 if( pInode->pPrev ){
1114 assert( pInode->pPrev->pNext==pInode );
1115 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001116 }else{
drh8af6c222010-05-14 12:43:01 +00001117 assert( inodeList==pInode );
1118 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001119 }
drh8af6c222010-05-14 12:43:01 +00001120 if( pInode->pNext ){
1121 assert( pInode->pNext->pPrev==pInode );
1122 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001123 }
drh8af6c222010-05-14 12:43:01 +00001124 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001125 }
drhbbd42a62004-05-22 17:41:58 +00001126 }
1127}
1128
1129/*
drh8af6c222010-05-14 12:43:01 +00001130** Given a file descriptor, locate the unixInodeInfo object that
1131** describes that file descriptor. Create a new one if necessary. The
1132** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001133**
dan9359c7b2009-08-21 08:29:10 +00001134** The mutex entered using the unixEnterMutex() function must be held
1135** when this function is called.
1136**
drh6c7d5c52008-11-21 20:32:33 +00001137** Return an appropriate error code.
1138*/
drh8af6c222010-05-14 12:43:01 +00001139static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001140 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001141 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001142){
1143 int rc; /* System call return code */
1144 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001145 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1146 struct stat statbuf; /* Low-level file information */
1147 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001148
dan9359c7b2009-08-21 08:29:10 +00001149 assert( unixMutexHeld() );
1150
drh6c7d5c52008-11-21 20:32:33 +00001151 /* Get low-level information about the file that we can used to
1152 ** create a unique name for the file.
1153 */
1154 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001155 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001156 if( rc!=0 ){
1157 pFile->lastErrno = errno;
1158#ifdef EOVERFLOW
1159 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1160#endif
1161 return SQLITE_IOERR;
1162 }
1163
drheb0d74f2009-02-03 15:27:02 +00001164#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001165 /* On OS X on an msdos filesystem, the inode number is reported
1166 ** incorrectly for zero-size files. See ticket #3260. To work
1167 ** around this problem (we consider it a bug in OS X, not SQLite)
1168 ** we always increase the file size to 1 by writing a single byte
1169 ** prior to accessing the inode number. The one byte written is
1170 ** an ASCII 'S' character which also happens to be the first byte
1171 ** in the header of every SQLite database. In this way, if there
1172 ** is a race condition such that another thread has already populated
1173 ** the first page of the database, no damage is done.
1174 */
drh7ed97b92010-01-20 13:07:21 +00001175 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001176 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001177 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001178 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001179 return SQLITE_IOERR;
1180 }
drh99ab3b12011-03-02 15:09:07 +00001181 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001182 if( rc!=0 ){
1183 pFile->lastErrno = errno;
1184 return SQLITE_IOERR;
1185 }
1186 }
drheb0d74f2009-02-03 15:27:02 +00001187#endif
drh6c7d5c52008-11-21 20:32:33 +00001188
drh8af6c222010-05-14 12:43:01 +00001189 memset(&fileId, 0, sizeof(fileId));
1190 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001191#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001192 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001193#else
drh8af6c222010-05-14 12:43:01 +00001194 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001195#endif
drh8af6c222010-05-14 12:43:01 +00001196 pInode = inodeList;
1197 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1198 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001199 }
drh8af6c222010-05-14 12:43:01 +00001200 if( pInode==0 ){
1201 pInode = sqlite3_malloc( sizeof(*pInode) );
1202 if( pInode==0 ){
1203 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001204 }
drh8af6c222010-05-14 12:43:01 +00001205 memset(pInode, 0, sizeof(*pInode));
1206 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1207 pInode->nRef = 1;
1208 pInode->pNext = inodeList;
1209 pInode->pPrev = 0;
1210 if( inodeList ) inodeList->pPrev = pInode;
1211 inodeList = pInode;
1212 }else{
1213 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001214 }
drh8af6c222010-05-14 12:43:01 +00001215 *ppInode = pInode;
1216 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001217}
drh6c7d5c52008-11-21 20:32:33 +00001218
aswift5b1a2562008-08-22 00:22:35 +00001219
1220/*
danielk197713adf8a2004-06-03 16:08:41 +00001221** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001222** file by this or any other process. If such a lock is held, set *pResOut
1223** to a non-zero value otherwise *pResOut is set to zero. The return value
1224** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001225*/
danielk1977861f7452008-06-05 11:39:11 +00001226static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001227 int rc = SQLITE_OK;
1228 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001229 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001230
danielk1977861f7452008-06-05 11:39:11 +00001231 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1232
drh054889e2005-11-30 03:20:31 +00001233 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001234 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001235
1236 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001237 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001238 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001239 }
1240
drh2ac3ee92004-06-07 16:27:46 +00001241 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001242 */
danielk197709480a92009-02-09 05:32:32 +00001243#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001244 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001245 struct flock lock;
1246 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001247 lock.l_start = RESERVED_BYTE;
1248 lock.l_len = 1;
1249 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001250 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1251 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1252 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001253 } else if( lock.l_type!=F_UNLCK ){
1254 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001255 }
1256 }
danielk197709480a92009-02-09 05:32:32 +00001257#endif
danielk197713adf8a2004-06-03 16:08:41 +00001258
drh6c7d5c52008-11-21 20:32:33 +00001259 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001260 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001261
aswift5b1a2562008-08-22 00:22:35 +00001262 *pResOut = reserved;
1263 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001264}
1265
1266/*
drha7e61d82011-03-12 17:02:57 +00001267** Attempt to set a system-lock on the file pFile. The lock is
1268** described by pLock.
1269**
drh77197112011-03-15 19:08:48 +00001270** If the pFile was opened read/write from unix-excl, then the only lock
1271** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001272** the first time any lock is attempted. All subsequent system locking
1273** operations become no-ops. Locking operations still happen internally,
1274** in order to coordinate access between separate database connections
1275** within this process, but all of that is handled in memory and the
1276** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001277**
1278** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1279** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1280** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001281**
1282** Zero is returned if the call completes successfully, or -1 if a call
1283** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001284*/
1285static int unixFileLock(unixFile *pFile, struct flock *pLock){
1286 int rc;
drh3cb93392011-03-12 18:10:44 +00001287 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001288 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001289 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001290 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1291 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1292 ){
drh3cb93392011-03-12 18:10:44 +00001293 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001294 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001295 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001296 lock.l_whence = SEEK_SET;
1297 lock.l_start = SHARED_FIRST;
1298 lock.l_len = SHARED_SIZE;
1299 lock.l_type = F_WRLCK;
1300 rc = osFcntl(pFile->h, F_SETLK, &lock);
1301 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001302 pInode->bProcessLock = 1;
1303 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001304 }else{
1305 rc = 0;
1306 }
1307 }else{
1308 rc = osFcntl(pFile->h, F_SETLK, pLock);
1309 }
1310 return rc;
1311}
1312
1313/*
drh308c2a52010-05-14 11:30:18 +00001314** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001315** of the following:
1316**
drh2ac3ee92004-06-07 16:27:46 +00001317** (1) SHARED_LOCK
1318** (2) RESERVED_LOCK
1319** (3) PENDING_LOCK
1320** (4) EXCLUSIVE_LOCK
1321**
drhb3e04342004-06-08 00:47:47 +00001322** Sometimes when requesting one lock state, additional lock states
1323** are inserted in between. The locking might fail on one of the later
1324** transitions leaving the lock state different from what it started but
1325** still short of its goal. The following chart shows the allowed
1326** transitions and the inserted intermediate states:
1327**
1328** UNLOCKED -> SHARED
1329** SHARED -> RESERVED
1330** SHARED -> (PENDING) -> EXCLUSIVE
1331** RESERVED -> (PENDING) -> EXCLUSIVE
1332** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001333**
drha6abd042004-06-09 17:37:22 +00001334** This routine will only increase a lock. Use the sqlite3OsUnlock()
1335** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001336*/
drh308c2a52010-05-14 11:30:18 +00001337static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001338 /* The following describes the implementation of the various locks and
1339 ** lock transitions in terms of the POSIX advisory shared and exclusive
1340 ** lock primitives (called read-locks and write-locks below, to avoid
1341 ** confusion with SQLite lock names). The algorithms are complicated
1342 ** slightly in order to be compatible with windows systems simultaneously
1343 ** accessing the same database file, in case that is ever required.
1344 **
1345 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1346 ** byte', each single bytes at well known offsets, and the 'shared byte
1347 ** range', a range of 510 bytes at a well known offset.
1348 **
1349 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1350 ** byte'. If this is successful, a random byte from the 'shared byte
1351 ** range' is read-locked and the lock on the 'pending byte' released.
1352 **
danielk197790ba3bd2004-06-25 08:32:25 +00001353 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1354 ** A RESERVED lock is implemented by grabbing a write-lock on the
1355 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001356 **
1357 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001358 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1359 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1360 ** obtained, but existing SHARED locks are allowed to persist. A process
1361 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1362 ** This property is used by the algorithm for rolling back a journal file
1363 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001364 **
danielk197790ba3bd2004-06-25 08:32:25 +00001365 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1366 ** implemented by obtaining a write-lock on the entire 'shared byte
1367 ** range'. Since all other locks require a read-lock on one of the bytes
1368 ** within this range, this ensures that no other locks are held on the
1369 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001370 **
1371 ** The reason a single byte cannot be used instead of the 'shared byte
1372 ** range' is that some versions of windows do not support read-locks. By
1373 ** locking a random byte from a range, concurrent SHARED locks may exist
1374 ** even if the locking primitive used is always a write-lock.
1375 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001376 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001377 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001378 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001379 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001380 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001381
drh054889e2005-11-30 03:20:31 +00001382 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001383 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1384 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001385 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001386
1387 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001388 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001389 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001390 */
drh308c2a52010-05-14 11:30:18 +00001391 if( pFile->eFileLock>=eFileLock ){
1392 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1393 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001394 return SQLITE_OK;
1395 }
1396
drh0c2694b2009-09-03 16:23:44 +00001397 /* Make sure the locking sequence is correct.
1398 ** (1) We never move from unlocked to anything higher than shared lock.
1399 ** (2) SQLite never explicitly requests a pendig lock.
1400 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001401 */
drh308c2a52010-05-14 11:30:18 +00001402 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1403 assert( eFileLock!=PENDING_LOCK );
1404 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001405
drh8af6c222010-05-14 12:43:01 +00001406 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001407 */
drh6c7d5c52008-11-21 20:32:33 +00001408 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001409 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001410
danielk1977ad94b582007-08-20 06:44:22 +00001411 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001412 ** handle that precludes the requested lock, return BUSY.
1413 */
drh8af6c222010-05-14 12:43:01 +00001414 if( (pFile->eFileLock!=pInode->eFileLock &&
1415 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001416 ){
1417 rc = SQLITE_BUSY;
1418 goto end_lock;
1419 }
1420
1421 /* If a SHARED lock is requested, and some thread using this PID already
1422 ** has a SHARED or RESERVED lock, then increment reference counts and
1423 ** return SQLITE_OK.
1424 */
drh308c2a52010-05-14 11:30:18 +00001425 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001426 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001427 assert( eFileLock==SHARED_LOCK );
1428 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001429 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001430 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001431 pInode->nShared++;
1432 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001433 goto end_lock;
1434 }
1435
danielk19779a1d0ab2004-06-01 14:09:28 +00001436
drh3cde3bb2004-06-12 02:17:14 +00001437 /* A PENDING lock is needed before acquiring a SHARED lock and before
1438 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1439 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001440 */
drh0c2694b2009-09-03 16:23:44 +00001441 lock.l_len = 1L;
1442 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001443 if( eFileLock==SHARED_LOCK
1444 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001445 ){
drh308c2a52010-05-14 11:30:18 +00001446 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001447 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001448 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001449 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001450 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001451 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001452 pFile->lastErrno = tErrno;
1453 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001454 goto end_lock;
1455 }
drh3cde3bb2004-06-12 02:17:14 +00001456 }
1457
1458
1459 /* If control gets to this point, then actually go ahead and make
1460 ** operating system calls for the specified lock.
1461 */
drh308c2a52010-05-14 11:30:18 +00001462 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001463 assert( pInode->nShared==0 );
1464 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001465 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001466
drh2ac3ee92004-06-07 16:27:46 +00001467 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001468 lock.l_start = SHARED_FIRST;
1469 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001470 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001471 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001472 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001473 }
dan661d71a2011-03-30 19:08:03 +00001474
drh2ac3ee92004-06-07 16:27:46 +00001475 /* Drop the temporary PENDING lock */
1476 lock.l_start = PENDING_BYTE;
1477 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001478 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001479 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1480 /* This could happen with a network mount */
1481 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001482 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001483 }
dan661d71a2011-03-30 19:08:03 +00001484
1485 if( rc ){
1486 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001487 pFile->lastErrno = tErrno;
1488 }
dan661d71a2011-03-30 19:08:03 +00001489 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001490 }else{
drh308c2a52010-05-14 11:30:18 +00001491 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001492 pInode->nLock++;
1493 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001494 }
drh8af6c222010-05-14 12:43:01 +00001495 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001496 /* We are trying for an exclusive lock but another thread in this
1497 ** same process is still holding a shared lock. */
1498 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001499 }else{
drh3cde3bb2004-06-12 02:17:14 +00001500 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001501 ** assumed that there is a SHARED or greater lock on the file
1502 ** already.
1503 */
drh308c2a52010-05-14 11:30:18 +00001504 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001505 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001506
1507 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1508 if( eFileLock==RESERVED_LOCK ){
1509 lock.l_start = RESERVED_BYTE;
1510 lock.l_len = 1L;
1511 }else{
1512 lock.l_start = SHARED_FIRST;
1513 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001514 }
dan661d71a2011-03-30 19:08:03 +00001515
1516 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001517 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001518 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001519 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001520 pFile->lastErrno = tErrno;
1521 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001522 }
drhbbd42a62004-05-22 17:41:58 +00001523 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001524
drh8f941bc2009-01-14 23:03:40 +00001525
1526#ifndef NDEBUG
1527 /* Set up the transaction-counter change checking flags when
1528 ** transitioning from a SHARED to a RESERVED lock. The change
1529 ** from SHARED to RESERVED marks the beginning of a normal
1530 ** write operation (not a hot journal rollback).
1531 */
1532 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001533 && pFile->eFileLock<=SHARED_LOCK
1534 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001535 ){
1536 pFile->transCntrChng = 0;
1537 pFile->dbUpdate = 0;
1538 pFile->inNormalWrite = 1;
1539 }
1540#endif
1541
1542
danielk1977ecb2a962004-06-02 06:30:16 +00001543 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001544 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001545 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001546 }else if( eFileLock==EXCLUSIVE_LOCK ){
1547 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001548 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001549 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001550
1551end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001552 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001553 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1554 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001555 return rc;
1556}
1557
1558/*
dan08da86a2009-08-21 17:18:03 +00001559** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001560** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001561*/
1562static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001563 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001564 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001565 p->pNext = pInode->pUnused;
1566 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001567 pFile->h = -1;
1568 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001569}
1570
1571/*
drh308c2a52010-05-14 11:30:18 +00001572** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001573** must be either NO_LOCK or SHARED_LOCK.
1574**
1575** If the locking level of the file descriptor is already at or below
1576** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001577**
1578** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1579** the byte range is divided into 2 parts and the first part is unlocked then
1580** set to a read lock, then the other part is simply unlocked. This works
1581** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1582** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001583*/
drha7e61d82011-03-12 17:02:57 +00001584static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001585 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001586 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001587 struct flock lock;
1588 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001589
drh054889e2005-11-30 03:20:31 +00001590 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001591 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001592 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001593 getpid()));
drha6abd042004-06-09 17:37:22 +00001594
drh308c2a52010-05-14 11:30:18 +00001595 assert( eFileLock<=SHARED_LOCK );
1596 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001597 return SQLITE_OK;
1598 }
drh6c7d5c52008-11-21 20:32:33 +00001599 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001600 pInode = pFile->pInode;
1601 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001602 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001603 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001604
1605#ifndef NDEBUG
1606 /* When reducing a lock such that other processes can start
1607 ** reading the database file again, make sure that the
1608 ** transaction counter was updated if any part of the database
1609 ** file changed. If the transaction counter is not updated,
1610 ** other connections to the same file might not realize that
1611 ** the file has changed and hence might not know to flush their
1612 ** cache. The use of a stale cache can lead to database corruption.
1613 */
drh8f941bc2009-01-14 23:03:40 +00001614 pFile->inNormalWrite = 0;
1615#endif
1616
drh7ed97b92010-01-20 13:07:21 +00001617 /* downgrading to a shared lock on NFS involves clearing the write lock
1618 ** before establishing the readlock - to avoid a race condition we downgrade
1619 ** the lock in 2 blocks, so that part of the range will be covered by a
1620 ** write lock until the rest is covered by a read lock:
1621 ** 1: [WWWWW]
1622 ** 2: [....W]
1623 ** 3: [RRRRW]
1624 ** 4: [RRRR.]
1625 */
drh308c2a52010-05-14 11:30:18 +00001626 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001627
1628#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001629 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001630 assert( handleNFSUnlock==0 );
1631#endif
1632#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001633 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001634 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001635 off_t divSize = SHARED_SIZE - 1;
1636
1637 lock.l_type = F_UNLCK;
1638 lock.l_whence = SEEK_SET;
1639 lock.l_start = SHARED_FIRST;
1640 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001641 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001642 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001643 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001644 if( IS_LOCK_ERROR(rc) ){
1645 pFile->lastErrno = tErrno;
1646 }
1647 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001648 }
drh7ed97b92010-01-20 13:07:21 +00001649 lock.l_type = F_RDLCK;
1650 lock.l_whence = SEEK_SET;
1651 lock.l_start = SHARED_FIRST;
1652 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001653 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001654 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001655 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1656 if( IS_LOCK_ERROR(rc) ){
1657 pFile->lastErrno = tErrno;
1658 }
1659 goto end_unlock;
1660 }
1661 lock.l_type = F_UNLCK;
1662 lock.l_whence = SEEK_SET;
1663 lock.l_start = SHARED_FIRST+divSize;
1664 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001665 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001666 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001667 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001668 if( IS_LOCK_ERROR(rc) ){
1669 pFile->lastErrno = tErrno;
1670 }
1671 goto end_unlock;
1672 }
drh30f776f2011-02-25 03:25:07 +00001673 }else
1674#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1675 {
drh7ed97b92010-01-20 13:07:21 +00001676 lock.l_type = F_RDLCK;
1677 lock.l_whence = SEEK_SET;
1678 lock.l_start = SHARED_FIRST;
1679 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001680 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001681 /* In theory, the call to unixFileLock() cannot fail because another
1682 ** process is holding an incompatible lock. If it does, this
1683 ** indicates that the other process is not following the locking
1684 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1685 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1686 ** an assert to fail). */
1687 rc = SQLITE_IOERR_RDLOCK;
1688 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001689 goto end_unlock;
1690 }
drh9c105bb2004-10-02 20:38:28 +00001691 }
1692 }
drhbbd42a62004-05-22 17:41:58 +00001693 lock.l_type = F_UNLCK;
1694 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001695 lock.l_start = PENDING_BYTE;
1696 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001697 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001698 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001699 }else{
danea83bc62011-04-01 11:56:32 +00001700 rc = SQLITE_IOERR_UNLOCK;
1701 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001702 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001703 }
drhbbd42a62004-05-22 17:41:58 +00001704 }
drh308c2a52010-05-14 11:30:18 +00001705 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001706 /* Decrement the shared lock counter. Release the lock using an
1707 ** OS call only when all threads in this same process have released
1708 ** the lock.
1709 */
drh8af6c222010-05-14 12:43:01 +00001710 pInode->nShared--;
1711 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001712 lock.l_type = F_UNLCK;
1713 lock.l_whence = SEEK_SET;
1714 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001715 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001716 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001717 }else{
danea83bc62011-04-01 11:56:32 +00001718 rc = SQLITE_IOERR_UNLOCK;
1719 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001720 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001721 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001722 }
drha6abd042004-06-09 17:37:22 +00001723 }
1724
drhbbd42a62004-05-22 17:41:58 +00001725 /* Decrement the count of locks against this same file. When the
1726 ** count reaches zero, close any other file descriptors whose close
1727 ** was deferred because of outstanding locks.
1728 */
drh8af6c222010-05-14 12:43:01 +00001729 pInode->nLock--;
1730 assert( pInode->nLock>=0 );
1731 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001732 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001733 }
1734 }
aswift5b1a2562008-08-22 00:22:35 +00001735
1736end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001737 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001738 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001739 return rc;
drhbbd42a62004-05-22 17:41:58 +00001740}
1741
1742/*
drh308c2a52010-05-14 11:30:18 +00001743** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001744** must be either NO_LOCK or SHARED_LOCK.
1745**
1746** If the locking level of the file descriptor is already at or below
1747** the requested locking level, this routine is a no-op.
1748*/
drh308c2a52010-05-14 11:30:18 +00001749static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001750 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001751}
1752
1753/*
danielk1977e339d652008-06-28 11:23:00 +00001754** This function performs the parts of the "close file" operation
1755** common to all locking schemes. It closes the directory and file
1756** handles, if they are valid, and sets all fields of the unixFile
1757** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001758**
1759** It is *not* necessary to hold the mutex when this routine is called,
1760** even on VxWorks. A mutex will be acquired on VxWorks by the
1761** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001762*/
1763static int closeUnixFile(sqlite3_file *id){
1764 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001765 if( pFile->h>=0 ){
1766 robust_close(pFile, pFile->h, __LINE__);
1767 pFile->h = -1;
1768 }
1769#if OS_VXWORKS
1770 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001771 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001772 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001773 }
1774 vxworksReleaseFileId(pFile->pId);
1775 pFile->pId = 0;
1776 }
1777#endif
1778 OSTRACE(("CLOSE %-3d\n", pFile->h));
1779 OpenCounter(-1);
1780 sqlite3_free(pFile->pUnused);
1781 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001782 return SQLITE_OK;
1783}
1784
1785/*
danielk1977e3026632004-06-22 11:29:02 +00001786** Close a file.
1787*/
danielk197762079062007-08-15 17:08:46 +00001788static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001789 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001790 unixFile *pFile = (unixFile *)id;
1791 unixUnlock(id, NO_LOCK);
1792 unixEnterMutex();
1793
1794 /* unixFile.pInode is always valid here. Otherwise, a different close
1795 ** routine (e.g. nolockClose()) would be called instead.
1796 */
1797 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1798 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1799 /* If there are outstanding locks, do not actually close the file just
1800 ** yet because that would clear those locks. Instead, add the file
1801 ** descriptor to pInode->pUnused list. It will be automatically closed
1802 ** when the last lock is cleared.
1803 */
1804 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001805 }
dan661d71a2011-03-30 19:08:03 +00001806 releaseInodeInfo(pFile);
1807 rc = closeUnixFile(id);
1808 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001809 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001810}
1811
drh734c9862008-11-28 15:37:20 +00001812/************** End of the posix advisory lock implementation *****************
1813******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001814
drh734c9862008-11-28 15:37:20 +00001815/******************************************************************************
1816****************************** No-op Locking **********************************
1817**
1818** Of the various locking implementations available, this is by far the
1819** simplest: locking is ignored. No attempt is made to lock the database
1820** file for reading or writing.
1821**
1822** This locking mode is appropriate for use on read-only databases
1823** (ex: databases that are burned into CD-ROM, for example.) It can
1824** also be used if the application employs some external mechanism to
1825** prevent simultaneous access of the same database by two or more
1826** database connections. But there is a serious risk of database
1827** corruption if this locking mode is used in situations where multiple
1828** database connections are accessing the same database file at the same
1829** time and one or more of those connections are writing.
1830*/
drhbfe66312006-10-03 17:40:40 +00001831
drh734c9862008-11-28 15:37:20 +00001832static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1833 UNUSED_PARAMETER(NotUsed);
1834 *pResOut = 0;
1835 return SQLITE_OK;
1836}
drh734c9862008-11-28 15:37:20 +00001837static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1838 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1839 return SQLITE_OK;
1840}
drh734c9862008-11-28 15:37:20 +00001841static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1842 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1843 return SQLITE_OK;
1844}
1845
1846/*
drh9b35ea62008-11-29 02:20:26 +00001847** Close the file.
drh734c9862008-11-28 15:37:20 +00001848*/
1849static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001850 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001851}
1852
1853/******************* End of the no-op lock implementation *********************
1854******************************************************************************/
1855
1856/******************************************************************************
1857************************* Begin dot-file Locking ******************************
1858**
drh0c2694b2009-09-03 16:23:44 +00001859** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001860** files (really a directory) to control access to the database. This works
1861** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001862**
1863** (1) There is zero concurrency. A single reader blocks all other
1864** connections from reading or writing the database.
1865**
1866** (2) An application crash or power loss can leave stale lock files
1867** sitting around that need to be cleared manually.
1868**
1869** Nevertheless, a dotlock is an appropriate locking mode for use if no
1870** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001871**
drh9ef6bc42011-11-04 02:24:02 +00001872** Dotfile locking works by creating a subdirectory in the same directory as
1873** the database and with the same name but with a ".lock" extension added.
1874** The existance of a lock directory implies an EXCLUSIVE lock. All other
1875** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001876*/
1877
1878/*
1879** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001880** lock directory.
drh734c9862008-11-28 15:37:20 +00001881*/
1882#define DOTLOCK_SUFFIX ".lock"
1883
drh7708e972008-11-29 00:56:52 +00001884/*
1885** This routine checks if there is a RESERVED lock held on the specified
1886** file by this or any other process. If such a lock is held, set *pResOut
1887** to a non-zero value otherwise *pResOut is set to zero. The return value
1888** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1889**
1890** In dotfile locking, either a lock exists or it does not. So in this
1891** variation of CheckReservedLock(), *pResOut is set to true if any lock
1892** is held on the file and false if the file is unlocked.
1893*/
drh734c9862008-11-28 15:37:20 +00001894static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1895 int rc = SQLITE_OK;
1896 int reserved = 0;
1897 unixFile *pFile = (unixFile*)id;
1898
1899 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1900
1901 assert( pFile );
1902
1903 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001904 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001905 /* Either this connection or some other connection in the same process
1906 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001907 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001908 }else{
1909 /* The lock is held if and only if the lockfile exists */
1910 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001911 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001912 }
drh308c2a52010-05-14 11:30:18 +00001913 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001914 *pResOut = reserved;
1915 return rc;
1916}
1917
drh7708e972008-11-29 00:56:52 +00001918/*
drh308c2a52010-05-14 11:30:18 +00001919** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001920** of the following:
1921**
1922** (1) SHARED_LOCK
1923** (2) RESERVED_LOCK
1924** (3) PENDING_LOCK
1925** (4) EXCLUSIVE_LOCK
1926**
1927** Sometimes when requesting one lock state, additional lock states
1928** are inserted in between. The locking might fail on one of the later
1929** transitions leaving the lock state different from what it started but
1930** still short of its goal. The following chart shows the allowed
1931** transitions and the inserted intermediate states:
1932**
1933** UNLOCKED -> SHARED
1934** SHARED -> RESERVED
1935** SHARED -> (PENDING) -> EXCLUSIVE
1936** RESERVED -> (PENDING) -> EXCLUSIVE
1937** PENDING -> EXCLUSIVE
1938**
1939** This routine will only increase a lock. Use the sqlite3OsUnlock()
1940** routine to lower a locking level.
1941**
1942** With dotfile locking, we really only support state (4): EXCLUSIVE.
1943** But we track the other locking levels internally.
1944*/
drh308c2a52010-05-14 11:30:18 +00001945static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001946 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001947 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001948 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001949
drh7708e972008-11-29 00:56:52 +00001950
1951 /* If we have any lock, then the lock file already exists. All we have
1952 ** to do is adjust our internal record of the lock level.
1953 */
drh308c2a52010-05-14 11:30:18 +00001954 if( pFile->eFileLock > NO_LOCK ){
1955 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001956 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001957#ifdef HAVE_UTIME
1958 utime(zLockFile, NULL);
1959#else
drh734c9862008-11-28 15:37:20 +00001960 utimes(zLockFile, NULL);
1961#endif
drh7708e972008-11-29 00:56:52 +00001962 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001963 }
1964
1965 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001966 rc = osMkdir(zLockFile, 0777);
1967 if( rc<0 ){
1968 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001969 int tErrno = errno;
1970 if( EEXIST == tErrno ){
1971 rc = SQLITE_BUSY;
1972 } else {
1973 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1974 if( IS_LOCK_ERROR(rc) ){
1975 pFile->lastErrno = tErrno;
1976 }
1977 }
drh7708e972008-11-29 00:56:52 +00001978 return rc;
drh734c9862008-11-28 15:37:20 +00001979 }
drh734c9862008-11-28 15:37:20 +00001980
1981 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001982 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001983 return rc;
1984}
1985
drh7708e972008-11-29 00:56:52 +00001986/*
drh308c2a52010-05-14 11:30:18 +00001987** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001988** must be either NO_LOCK or SHARED_LOCK.
1989**
1990** If the locking level of the file descriptor is already at or below
1991** the requested locking level, this routine is a no-op.
1992**
1993** When the locking level reaches NO_LOCK, delete the lock file.
1994*/
drh308c2a52010-05-14 11:30:18 +00001995static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001996 unixFile *pFile = (unixFile*)id;
1997 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00001998 int rc;
drh734c9862008-11-28 15:37:20 +00001999
2000 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002001 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2002 pFile->eFileLock, getpid()));
2003 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002004
2005 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002006 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002007 return SQLITE_OK;
2008 }
drh7708e972008-11-29 00:56:52 +00002009
2010 /* To downgrade to shared, simply update our internal notion of the
2011 ** lock state. No need to mess with the file on disk.
2012 */
drh308c2a52010-05-14 11:30:18 +00002013 if( eFileLock==SHARED_LOCK ){
2014 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002015 return SQLITE_OK;
2016 }
2017
drh7708e972008-11-29 00:56:52 +00002018 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002019 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002020 rc = osRmdir(zLockFile);
2021 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2022 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002023 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002024 rc = 0;
drh734c9862008-11-28 15:37:20 +00002025 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002026 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002027 }
2028 if( IS_LOCK_ERROR(rc) ){
2029 pFile->lastErrno = tErrno;
2030 }
2031 return rc;
2032 }
drh308c2a52010-05-14 11:30:18 +00002033 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002034 return SQLITE_OK;
2035}
2036
2037/*
drh9b35ea62008-11-29 02:20:26 +00002038** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002039*/
2040static int dotlockClose(sqlite3_file *id) {
2041 int rc;
2042 if( id ){
2043 unixFile *pFile = (unixFile*)id;
2044 dotlockUnlock(id, NO_LOCK);
2045 sqlite3_free(pFile->lockingContext);
2046 }
drh734c9862008-11-28 15:37:20 +00002047 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002048 return rc;
2049}
2050/****************** End of the dot-file lock implementation *******************
2051******************************************************************************/
2052
2053/******************************************************************************
2054************************** Begin flock Locking ********************************
2055**
2056** Use the flock() system call to do file locking.
2057**
drh6b9d6dd2008-12-03 19:34:47 +00002058** flock() locking is like dot-file locking in that the various
2059** fine-grain locking levels supported by SQLite are collapsed into
2060** a single exclusive lock. In other words, SHARED, RESERVED, and
2061** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2062** still works when you do this, but concurrency is reduced since
2063** only a single process can be reading the database at a time.
2064**
drh734c9862008-11-28 15:37:20 +00002065** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2066** compiling for VXWORKS.
2067*/
2068#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002069
drh6b9d6dd2008-12-03 19:34:47 +00002070/*
drhff812312011-02-23 13:33:46 +00002071** Retry flock() calls that fail with EINTR
2072*/
2073#ifdef EINTR
2074static int robust_flock(int fd, int op){
2075 int rc;
2076 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2077 return rc;
2078}
2079#else
drh5c819272011-02-23 14:00:12 +00002080# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002081#endif
2082
2083
2084/*
drh6b9d6dd2008-12-03 19:34:47 +00002085** This routine checks if there is a RESERVED lock held on the specified
2086** file by this or any other process. If such a lock is held, set *pResOut
2087** to a non-zero value otherwise *pResOut is set to zero. The return value
2088** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2089*/
drh734c9862008-11-28 15:37:20 +00002090static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2091 int rc = SQLITE_OK;
2092 int reserved = 0;
2093 unixFile *pFile = (unixFile*)id;
2094
2095 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2096
2097 assert( pFile );
2098
2099 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002100 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002101 reserved = 1;
2102 }
2103
2104 /* Otherwise see if some other process holds it. */
2105 if( !reserved ){
2106 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002107 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002108 if( !lrc ){
2109 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002110 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002111 if ( lrc ) {
2112 int tErrno = errno;
2113 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002114 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002115 if( IS_LOCK_ERROR(lrc) ){
2116 pFile->lastErrno = tErrno;
2117 rc = lrc;
2118 }
2119 }
2120 } else {
2121 int tErrno = errno;
2122 reserved = 1;
2123 /* someone else might have it reserved */
2124 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2125 if( IS_LOCK_ERROR(lrc) ){
2126 pFile->lastErrno = tErrno;
2127 rc = lrc;
2128 }
2129 }
2130 }
drh308c2a52010-05-14 11:30:18 +00002131 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002132
2133#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2134 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2135 rc = SQLITE_OK;
2136 reserved=1;
2137 }
2138#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2139 *pResOut = reserved;
2140 return rc;
2141}
2142
drh6b9d6dd2008-12-03 19:34:47 +00002143/*
drh308c2a52010-05-14 11:30:18 +00002144** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002145** of the following:
2146**
2147** (1) SHARED_LOCK
2148** (2) RESERVED_LOCK
2149** (3) PENDING_LOCK
2150** (4) EXCLUSIVE_LOCK
2151**
2152** Sometimes when requesting one lock state, additional lock states
2153** are inserted in between. The locking might fail on one of the later
2154** transitions leaving the lock state different from what it started but
2155** still short of its goal. The following chart shows the allowed
2156** transitions and the inserted intermediate states:
2157**
2158** UNLOCKED -> SHARED
2159** SHARED -> RESERVED
2160** SHARED -> (PENDING) -> EXCLUSIVE
2161** RESERVED -> (PENDING) -> EXCLUSIVE
2162** PENDING -> EXCLUSIVE
2163**
2164** flock() only really support EXCLUSIVE locks. We track intermediate
2165** lock states in the sqlite3_file structure, but all locks SHARED or
2166** above are really EXCLUSIVE locks and exclude all other processes from
2167** access the file.
2168**
2169** This routine will only increase a lock. Use the sqlite3OsUnlock()
2170** routine to lower a locking level.
2171*/
drh308c2a52010-05-14 11:30:18 +00002172static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002173 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002174 unixFile *pFile = (unixFile*)id;
2175
2176 assert( pFile );
2177
2178 /* if we already have a lock, it is exclusive.
2179 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002180 if (pFile->eFileLock > NO_LOCK) {
2181 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002182 return SQLITE_OK;
2183 }
2184
2185 /* grab an exclusive lock */
2186
drhff812312011-02-23 13:33:46 +00002187 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002188 int tErrno = errno;
2189 /* didn't get, must be busy */
2190 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2191 if( IS_LOCK_ERROR(rc) ){
2192 pFile->lastErrno = tErrno;
2193 }
2194 } else {
2195 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002196 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002197 }
drh308c2a52010-05-14 11:30:18 +00002198 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2199 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002200#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2201 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2202 rc = SQLITE_BUSY;
2203 }
2204#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2205 return rc;
2206}
2207
drh6b9d6dd2008-12-03 19:34:47 +00002208
2209/*
drh308c2a52010-05-14 11:30:18 +00002210** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002211** must be either NO_LOCK or SHARED_LOCK.
2212**
2213** If the locking level of the file descriptor is already at or below
2214** the requested locking level, this routine is a no-op.
2215*/
drh308c2a52010-05-14 11:30:18 +00002216static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002217 unixFile *pFile = (unixFile*)id;
2218
2219 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002220 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2221 pFile->eFileLock, getpid()));
2222 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002223
2224 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002225 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002226 return SQLITE_OK;
2227 }
2228
2229 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002230 if (eFileLock==SHARED_LOCK) {
2231 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002232 return SQLITE_OK;
2233 }
2234
2235 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002236 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002237#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002238 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002239#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002240 return SQLITE_IOERR_UNLOCK;
2241 }else{
drh308c2a52010-05-14 11:30:18 +00002242 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002243 return SQLITE_OK;
2244 }
2245}
2246
2247/*
2248** Close a file.
2249*/
2250static int flockClose(sqlite3_file *id) {
2251 if( id ){
2252 flockUnlock(id, NO_LOCK);
2253 }
2254 return closeUnixFile(id);
2255}
2256
2257#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2258
2259/******************* End of the flock lock implementation *********************
2260******************************************************************************/
2261
2262/******************************************************************************
2263************************ Begin Named Semaphore Locking ************************
2264**
2265** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002266**
2267** Semaphore locking is like dot-lock and flock in that it really only
2268** supports EXCLUSIVE locking. Only a single process can read or write
2269** the database file at a time. This reduces potential concurrency, but
2270** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002271*/
2272#if OS_VXWORKS
2273
drh6b9d6dd2008-12-03 19:34:47 +00002274/*
2275** This routine checks if there is a RESERVED lock held on the specified
2276** file by this or any other process. If such a lock is held, set *pResOut
2277** to a non-zero value otherwise *pResOut is set to zero. The return value
2278** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2279*/
drh734c9862008-11-28 15:37:20 +00002280static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2281 int rc = SQLITE_OK;
2282 int reserved = 0;
2283 unixFile *pFile = (unixFile*)id;
2284
2285 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2286
2287 assert( pFile );
2288
2289 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002290 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002291 reserved = 1;
2292 }
2293
2294 /* Otherwise see if some other process holds it. */
2295 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002296 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002297 struct stat statBuf;
2298
2299 if( sem_trywait(pSem)==-1 ){
2300 int tErrno = errno;
2301 if( EAGAIN != tErrno ){
2302 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2303 pFile->lastErrno = tErrno;
2304 } else {
2305 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002306 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002307 }
2308 }else{
2309 /* we could have it if we want it */
2310 sem_post(pSem);
2311 }
2312 }
drh308c2a52010-05-14 11:30:18 +00002313 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002314
2315 *pResOut = reserved;
2316 return rc;
2317}
2318
drh6b9d6dd2008-12-03 19:34:47 +00002319/*
drh308c2a52010-05-14 11:30:18 +00002320** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002321** of the following:
2322**
2323** (1) SHARED_LOCK
2324** (2) RESERVED_LOCK
2325** (3) PENDING_LOCK
2326** (4) EXCLUSIVE_LOCK
2327**
2328** Sometimes when requesting one lock state, additional lock states
2329** are inserted in between. The locking might fail on one of the later
2330** transitions leaving the lock state different from what it started but
2331** still short of its goal. The following chart shows the allowed
2332** transitions and the inserted intermediate states:
2333**
2334** UNLOCKED -> SHARED
2335** SHARED -> RESERVED
2336** SHARED -> (PENDING) -> EXCLUSIVE
2337** RESERVED -> (PENDING) -> EXCLUSIVE
2338** PENDING -> EXCLUSIVE
2339**
2340** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2341** lock states in the sqlite3_file structure, but all locks SHARED or
2342** above are really EXCLUSIVE locks and exclude all other processes from
2343** access the file.
2344**
2345** This routine will only increase a lock. Use the sqlite3OsUnlock()
2346** routine to lower a locking level.
2347*/
drh308c2a52010-05-14 11:30:18 +00002348static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002349 unixFile *pFile = (unixFile*)id;
2350 int fd;
drh8af6c222010-05-14 12:43:01 +00002351 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002352 int rc = SQLITE_OK;
2353
2354 /* if we already have a lock, it is exclusive.
2355 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002356 if (pFile->eFileLock > NO_LOCK) {
2357 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002358 rc = SQLITE_OK;
2359 goto sem_end_lock;
2360 }
2361
2362 /* lock semaphore now but bail out when already locked. */
2363 if( sem_trywait(pSem)==-1 ){
2364 rc = SQLITE_BUSY;
2365 goto sem_end_lock;
2366 }
2367
2368 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002369 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002370
2371 sem_end_lock:
2372 return rc;
2373}
2374
drh6b9d6dd2008-12-03 19:34:47 +00002375/*
drh308c2a52010-05-14 11:30:18 +00002376** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002377** must be either NO_LOCK or SHARED_LOCK.
2378**
2379** If the locking level of the file descriptor is already at or below
2380** the requested locking level, this routine is a no-op.
2381*/
drh308c2a52010-05-14 11:30:18 +00002382static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002383 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002384 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002385
2386 assert( pFile );
2387 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002388 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2389 pFile->eFileLock, getpid()));
2390 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002391
2392 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002393 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002394 return SQLITE_OK;
2395 }
2396
2397 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002398 if (eFileLock==SHARED_LOCK) {
2399 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002400 return SQLITE_OK;
2401 }
2402
2403 /* no, really unlock. */
2404 if ( sem_post(pSem)==-1 ) {
2405 int rc, tErrno = errno;
2406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2407 if( IS_LOCK_ERROR(rc) ){
2408 pFile->lastErrno = tErrno;
2409 }
2410 return rc;
2411 }
drh308c2a52010-05-14 11:30:18 +00002412 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002413 return SQLITE_OK;
2414}
2415
2416/*
2417 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002418 */
drh734c9862008-11-28 15:37:20 +00002419static int semClose(sqlite3_file *id) {
2420 if( id ){
2421 unixFile *pFile = (unixFile*)id;
2422 semUnlock(id, NO_LOCK);
2423 assert( pFile );
2424 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002425 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002426 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002427 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002428 }
2429 return SQLITE_OK;
2430}
2431
2432#endif /* OS_VXWORKS */
2433/*
2434** Named semaphore locking is only available on VxWorks.
2435**
2436*************** End of the named semaphore lock implementation ****************
2437******************************************************************************/
2438
2439
2440/******************************************************************************
2441*************************** Begin AFP Locking *********************************
2442**
2443** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2444** on Apple Macintosh computers - both OS9 and OSX.
2445**
2446** Third-party implementations of AFP are available. But this code here
2447** only works on OSX.
2448*/
2449
drhd2cb50b2009-01-09 21:41:17 +00002450#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002451/*
2452** The afpLockingContext structure contains all afp lock specific state
2453*/
drhbfe66312006-10-03 17:40:40 +00002454typedef struct afpLockingContext afpLockingContext;
2455struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002456 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002457 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002458};
2459
2460struct ByteRangeLockPB2
2461{
2462 unsigned long long offset; /* offset to first byte to lock */
2463 unsigned long long length; /* nbr of bytes to lock */
2464 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2465 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2466 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2467 int fd; /* file desc to assoc this lock with */
2468};
2469
drhfd131da2007-08-07 17:13:03 +00002470#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002471
drh6b9d6dd2008-12-03 19:34:47 +00002472/*
2473** This is a utility for setting or clearing a bit-range lock on an
2474** AFP filesystem.
2475**
2476** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2477*/
2478static int afpSetLock(
2479 const char *path, /* Name of the file to be locked or unlocked */
2480 unixFile *pFile, /* Open file descriptor on path */
2481 unsigned long long offset, /* First byte to be locked */
2482 unsigned long long length, /* Number of bytes to lock */
2483 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002484){
drh6b9d6dd2008-12-03 19:34:47 +00002485 struct ByteRangeLockPB2 pb;
2486 int err;
drhbfe66312006-10-03 17:40:40 +00002487
2488 pb.unLockFlag = setLockFlag ? 0 : 1;
2489 pb.startEndFlag = 0;
2490 pb.offset = offset;
2491 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002492 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002493
drh308c2a52010-05-14 11:30:18 +00002494 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002495 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002496 offset, length));
drhbfe66312006-10-03 17:40:40 +00002497 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2498 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002499 int rc;
2500 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002501 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2502 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002503#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2504 rc = SQLITE_BUSY;
2505#else
drh734c9862008-11-28 15:37:20 +00002506 rc = sqliteErrorFromPosixError(tErrno,
2507 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002508#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002509 if( IS_LOCK_ERROR(rc) ){
2510 pFile->lastErrno = tErrno;
2511 }
2512 return rc;
drhbfe66312006-10-03 17:40:40 +00002513 } else {
aswift5b1a2562008-08-22 00:22:35 +00002514 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002515 }
2516}
2517
drh6b9d6dd2008-12-03 19:34:47 +00002518/*
2519** This routine checks if there is a RESERVED lock held on the specified
2520** file by this or any other process. If such a lock is held, set *pResOut
2521** to a non-zero value otherwise *pResOut is set to zero. The return value
2522** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2523*/
danielk1977e339d652008-06-28 11:23:00 +00002524static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002525 int rc = SQLITE_OK;
2526 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002527 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002528 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002529
aswift5b1a2562008-08-22 00:22:35 +00002530 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2531
2532 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002533 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002534 if( context->reserved ){
2535 *pResOut = 1;
2536 return SQLITE_OK;
2537 }
drh8af6c222010-05-14 12:43:01 +00002538 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002539
2540 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002541 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002542 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002543 }
2544
2545 /* Otherwise see if some other process holds it.
2546 */
aswift5b1a2562008-08-22 00:22:35 +00002547 if( !reserved ){
2548 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002549 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002550 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002551 /* if we succeeded in taking the reserved lock, unlock it to restore
2552 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002553 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002554 } else {
2555 /* if we failed to get the lock then someone else must have it */
2556 reserved = 1;
2557 }
2558 if( IS_LOCK_ERROR(lrc) ){
2559 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002560 }
2561 }
drhbfe66312006-10-03 17:40:40 +00002562
drh7ed97b92010-01-20 13:07:21 +00002563 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002564 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002565
2566 *pResOut = reserved;
2567 return rc;
drhbfe66312006-10-03 17:40:40 +00002568}
2569
drh6b9d6dd2008-12-03 19:34:47 +00002570/*
drh308c2a52010-05-14 11:30:18 +00002571** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002572** of the following:
2573**
2574** (1) SHARED_LOCK
2575** (2) RESERVED_LOCK
2576** (3) PENDING_LOCK
2577** (4) EXCLUSIVE_LOCK
2578**
2579** Sometimes when requesting one lock state, additional lock states
2580** are inserted in between. The locking might fail on one of the later
2581** transitions leaving the lock state different from what it started but
2582** still short of its goal. The following chart shows the allowed
2583** transitions and the inserted intermediate states:
2584**
2585** UNLOCKED -> SHARED
2586** SHARED -> RESERVED
2587** SHARED -> (PENDING) -> EXCLUSIVE
2588** RESERVED -> (PENDING) -> EXCLUSIVE
2589** PENDING -> EXCLUSIVE
2590**
2591** This routine will only increase a lock. Use the sqlite3OsUnlock()
2592** routine to lower a locking level.
2593*/
drh308c2a52010-05-14 11:30:18 +00002594static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002595 int rc = SQLITE_OK;
2596 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002597 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002598 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002599
2600 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002601 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2602 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002603 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002604
drhbfe66312006-10-03 17:40:40 +00002605 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002606 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002607 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002608 */
drh308c2a52010-05-14 11:30:18 +00002609 if( pFile->eFileLock>=eFileLock ){
2610 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2611 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002612 return SQLITE_OK;
2613 }
2614
2615 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002616 ** (1) We never move from unlocked to anything higher than shared lock.
2617 ** (2) SQLite never explicitly requests a pendig lock.
2618 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002619 */
drh308c2a52010-05-14 11:30:18 +00002620 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2621 assert( eFileLock!=PENDING_LOCK );
2622 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002623
drh8af6c222010-05-14 12:43:01 +00002624 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002625 */
drh6c7d5c52008-11-21 20:32:33 +00002626 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002627 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002628
2629 /* If some thread using this PID has a lock via a different unixFile*
2630 ** handle that precludes the requested lock, return BUSY.
2631 */
drh8af6c222010-05-14 12:43:01 +00002632 if( (pFile->eFileLock!=pInode->eFileLock &&
2633 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002634 ){
2635 rc = SQLITE_BUSY;
2636 goto afp_end_lock;
2637 }
2638
2639 /* If a SHARED lock is requested, and some thread using this PID already
2640 ** has a SHARED or RESERVED lock, then increment reference counts and
2641 ** return SQLITE_OK.
2642 */
drh308c2a52010-05-14 11:30:18 +00002643 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002644 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002645 assert( eFileLock==SHARED_LOCK );
2646 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002647 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002648 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002649 pInode->nShared++;
2650 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002651 goto afp_end_lock;
2652 }
drhbfe66312006-10-03 17:40:40 +00002653
2654 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002655 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2656 ** be released.
2657 */
drh308c2a52010-05-14 11:30:18 +00002658 if( eFileLock==SHARED_LOCK
2659 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002660 ){
2661 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002662 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002663 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002664 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002665 goto afp_end_lock;
2666 }
2667 }
2668
2669 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002670 ** operating system calls for the specified lock.
2671 */
drh308c2a52010-05-14 11:30:18 +00002672 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002673 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002674 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002675
drh8af6c222010-05-14 12:43:01 +00002676 assert( pInode->nShared==0 );
2677 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002678
2679 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002680 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002681 /* note that the quality of the randomness doesn't matter that much */
2682 lk = random();
drh8af6c222010-05-14 12:43:01 +00002683 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002684 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002685 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002686 if( IS_LOCK_ERROR(lrc1) ){
2687 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002688 }
aswift5b1a2562008-08-22 00:22:35 +00002689 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002690 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002691
aswift5b1a2562008-08-22 00:22:35 +00002692 if( IS_LOCK_ERROR(lrc1) ) {
2693 pFile->lastErrno = lrc1Errno;
2694 rc = lrc1;
2695 goto afp_end_lock;
2696 } else if( IS_LOCK_ERROR(lrc2) ){
2697 rc = lrc2;
2698 goto afp_end_lock;
2699 } else if( lrc1 != SQLITE_OK ) {
2700 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002701 } else {
drh308c2a52010-05-14 11:30:18 +00002702 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002703 pInode->nLock++;
2704 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002705 }
drh8af6c222010-05-14 12:43:01 +00002706 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002707 /* We are trying for an exclusive lock but another thread in this
2708 ** same process is still holding a shared lock. */
2709 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002710 }else{
2711 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2712 ** assumed that there is a SHARED or greater lock on the file
2713 ** already.
2714 */
2715 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002716 assert( 0!=pFile->eFileLock );
2717 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002718 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002719 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002720 if( !failed ){
2721 context->reserved = 1;
2722 }
drhbfe66312006-10-03 17:40:40 +00002723 }
drh308c2a52010-05-14 11:30:18 +00002724 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002725 /* Acquire an EXCLUSIVE lock */
2726
2727 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002728 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002729 */
drh6b9d6dd2008-12-03 19:34:47 +00002730 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002731 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002732 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002733 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002734 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002735 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002736 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002737 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002738 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2739 ** a critical I/O error
2740 */
2741 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2742 SQLITE_IOERR_LOCK;
2743 goto afp_end_lock;
2744 }
2745 }else{
aswift5b1a2562008-08-22 00:22:35 +00002746 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002747 }
2748 }
aswift5b1a2562008-08-22 00:22:35 +00002749 if( failed ){
2750 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002751 }
2752 }
2753
2754 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002755 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002756 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002757 }else if( eFileLock==EXCLUSIVE_LOCK ){
2758 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002759 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002760 }
2761
2762afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002763 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002764 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2765 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002766 return rc;
2767}
2768
2769/*
drh308c2a52010-05-14 11:30:18 +00002770** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002771** must be either NO_LOCK or SHARED_LOCK.
2772**
2773** If the locking level of the file descriptor is already at or below
2774** the requested locking level, this routine is a no-op.
2775*/
drh308c2a52010-05-14 11:30:18 +00002776static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002777 int rc = SQLITE_OK;
2778 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002779 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002780 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2781 int skipShared = 0;
2782#ifdef SQLITE_TEST
2783 int h = pFile->h;
2784#endif
drhbfe66312006-10-03 17:40:40 +00002785
2786 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002787 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002788 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002789 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002790
drh308c2a52010-05-14 11:30:18 +00002791 assert( eFileLock<=SHARED_LOCK );
2792 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002793 return SQLITE_OK;
2794 }
drh6c7d5c52008-11-21 20:32:33 +00002795 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002796 pInode = pFile->pInode;
2797 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002798 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002799 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002800 SimulateIOErrorBenign(1);
2801 SimulateIOError( h=(-1) )
2802 SimulateIOErrorBenign(0);
2803
2804#ifndef NDEBUG
2805 /* When reducing a lock such that other processes can start
2806 ** reading the database file again, make sure that the
2807 ** transaction counter was updated if any part of the database
2808 ** file changed. If the transaction counter is not updated,
2809 ** other connections to the same file might not realize that
2810 ** the file has changed and hence might not know to flush their
2811 ** cache. The use of a stale cache can lead to database corruption.
2812 */
2813 assert( pFile->inNormalWrite==0
2814 || pFile->dbUpdate==0
2815 || pFile->transCntrChng==1 );
2816 pFile->inNormalWrite = 0;
2817#endif
aswiftaebf4132008-11-21 00:10:35 +00002818
drh308c2a52010-05-14 11:30:18 +00002819 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002820 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002821 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002822 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002823 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002824 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2825 } else {
2826 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002827 }
2828 }
drh308c2a52010-05-14 11:30:18 +00002829 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002830 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002831 }
drh308c2a52010-05-14 11:30:18 +00002832 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002833 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2834 if( !rc ){
2835 context->reserved = 0;
2836 }
aswiftaebf4132008-11-21 00:10:35 +00002837 }
drh8af6c222010-05-14 12:43:01 +00002838 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2839 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002840 }
aswiftaebf4132008-11-21 00:10:35 +00002841 }
drh308c2a52010-05-14 11:30:18 +00002842 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002843
drh7ed97b92010-01-20 13:07:21 +00002844 /* Decrement the shared lock counter. Release the lock using an
2845 ** OS call only when all threads in this same process have released
2846 ** the lock.
2847 */
drh8af6c222010-05-14 12:43:01 +00002848 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2849 pInode->nShared--;
2850 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002851 SimulateIOErrorBenign(1);
2852 SimulateIOError( h=(-1) )
2853 SimulateIOErrorBenign(0);
2854 if( !skipShared ){
2855 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2856 }
2857 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002858 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002859 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002860 }
2861 }
2862 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002863 pInode->nLock--;
2864 assert( pInode->nLock>=0 );
2865 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002866 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002867 }
2868 }
drhbfe66312006-10-03 17:40:40 +00002869 }
drh7ed97b92010-01-20 13:07:21 +00002870
drh6c7d5c52008-11-21 20:32:33 +00002871 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002872 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002873 return rc;
2874}
2875
2876/*
drh339eb0b2008-03-07 15:34:11 +00002877** Close a file & cleanup AFP specific locking context
2878*/
danielk1977e339d652008-06-28 11:23:00 +00002879static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002880 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002881 if( id ){
2882 unixFile *pFile = (unixFile*)id;
2883 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002884 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002885 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002886 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002887 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002888 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002889 ** the last lock is cleared.
2890 */
dan08da86a2009-08-21 17:18:03 +00002891 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002892 }
danb0ac3e32010-06-16 10:55:42 +00002893 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002894 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002895 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002896 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002897 }
drh7ed97b92010-01-20 13:07:21 +00002898 return rc;
drhbfe66312006-10-03 17:40:40 +00002899}
2900
drhd2cb50b2009-01-09 21:41:17 +00002901#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002902/*
2903** The code above is the AFP lock implementation. The code is specific
2904** to MacOSX and does not work on other unix platforms. No alternative
2905** is available. If you don't compile for a mac, then the "unix-afp"
2906** VFS is not available.
2907**
2908********************* End of the AFP lock implementation **********************
2909******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002910
drh7ed97b92010-01-20 13:07:21 +00002911/******************************************************************************
2912*************************** Begin NFS Locking ********************************/
2913
2914#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2915/*
drh308c2a52010-05-14 11:30:18 +00002916 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002917 ** must be either NO_LOCK or SHARED_LOCK.
2918 **
2919 ** If the locking level of the file descriptor is already at or below
2920 ** the requested locking level, this routine is a no-op.
2921 */
drh308c2a52010-05-14 11:30:18 +00002922static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002923 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002924}
2925
2926#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2927/*
2928** The code above is the NFS lock implementation. The code is specific
2929** to MacOSX and does not work on other unix platforms. No alternative
2930** is available.
2931**
2932********************* End of the NFS lock implementation **********************
2933******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002934
2935/******************************************************************************
2936**************** Non-locking sqlite3_file methods *****************************
2937**
2938** The next division contains implementations for all methods of the
2939** sqlite3_file object other than the locking methods. The locking
2940** methods were defined in divisions above (one locking method per
2941** division). Those methods that are common to all locking modes
2942** are gather together into this division.
2943*/
drhbfe66312006-10-03 17:40:40 +00002944
2945/*
drh734c9862008-11-28 15:37:20 +00002946** Seek to the offset passed as the second argument, then read cnt
2947** bytes into pBuf. Return the number of bytes actually read.
2948**
2949** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2950** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2951** one system to another. Since SQLite does not define USE_PREAD
2952** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2953** See tickets #2741 and #2681.
2954**
2955** To avoid stomping the errno value on a failed read the lastErrno value
2956** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002957*/
drh734c9862008-11-28 15:37:20 +00002958static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2959 int got;
drh58024642011-11-07 18:16:00 +00002960 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002961#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002962 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002963#endif
drh734c9862008-11-28 15:37:20 +00002964 TIMER_START;
drh58024642011-11-07 18:16:00 +00002965 do{
drh734c9862008-11-28 15:37:20 +00002966#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002967 got = osPread(id->h, pBuf, cnt, offset);
2968 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002969#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00002970 got = osPread64(id->h, pBuf, cnt, offset);
2971 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002972#else
drh58024642011-11-07 18:16:00 +00002973 newOffset = lseek(id->h, offset, SEEK_SET);
2974 SimulateIOError( newOffset-- );
2975 if( newOffset!=offset ){
2976 if( newOffset == -1 ){
2977 ((unixFile*)id)->lastErrno = errno;
2978 }else{
2979 ((unixFile*)id)->lastErrno = 0;
2980 }
2981 return -1;
drh734c9862008-11-28 15:37:20 +00002982 }
drh58024642011-11-07 18:16:00 +00002983 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00002984#endif
drh58024642011-11-07 18:16:00 +00002985 if( got==cnt ) break;
2986 if( got<0 ){
2987 if( errno==EINTR ){ got = 1; continue; }
2988 prior = 0;
2989 ((unixFile*)id)->lastErrno = errno;
2990 break;
2991 }else if( got>0 ){
2992 cnt -= got;
2993 offset += got;
2994 prior += got;
2995 pBuf = (void*)(got + (char*)pBuf);
2996 }
2997 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00002998 TIMER_END;
drh58024642011-11-07 18:16:00 +00002999 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3000 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3001 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003002}
3003
3004/*
drh734c9862008-11-28 15:37:20 +00003005** Read data from a file into a buffer. Return SQLITE_OK if all
3006** bytes were read successfully and SQLITE_IOERR if anything goes
3007** wrong.
drh339eb0b2008-03-07 15:34:11 +00003008*/
drh734c9862008-11-28 15:37:20 +00003009static int unixRead(
3010 sqlite3_file *id,
3011 void *pBuf,
3012 int amt,
3013 sqlite3_int64 offset
3014){
dan08da86a2009-08-21 17:18:03 +00003015 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003016 int got;
3017 assert( id );
drh08c6d442009-02-09 17:34:07 +00003018
dan08da86a2009-08-21 17:18:03 +00003019 /* If this is a database file (not a journal, master-journal or temp
3020 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003021#if 0
dane946c392009-08-22 11:39:46 +00003022 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003023 || offset>=PENDING_BYTE+512
3024 || offset+amt<=PENDING_BYTE
3025 );
dan7c246102010-04-12 19:00:29 +00003026#endif
drh08c6d442009-02-09 17:34:07 +00003027
dan08da86a2009-08-21 17:18:03 +00003028 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003029 if( got==amt ){
3030 return SQLITE_OK;
3031 }else if( got<0 ){
3032 /* lastErrno set by seekAndRead */
3033 return SQLITE_IOERR_READ;
3034 }else{
dan08da86a2009-08-21 17:18:03 +00003035 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003036 /* Unread parts of the buffer must be zero-filled */
3037 memset(&((char*)pBuf)[got], 0, amt-got);
3038 return SQLITE_IOERR_SHORT_READ;
3039 }
3040}
3041
3042/*
3043** Seek to the offset in id->offset then read cnt bytes into pBuf.
3044** Return the number of bytes actually read. Update the offset.
3045**
3046** To avoid stomping the errno value on a failed write the lastErrno value
3047** is set before returning.
3048*/
3049static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3050 int got;
drh7ed97b92010-01-20 13:07:21 +00003051#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003052 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003053#endif
drh734c9862008-11-28 15:37:20 +00003054 TIMER_START;
3055#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003056 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003057#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003058 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003059#else
drhbd1e50c2011-08-19 14:54:12 +00003060 do{
3061 newOffset = lseek(id->h, offset, SEEK_SET);
3062 SimulateIOError( newOffset-- );
3063 if( newOffset!=offset ){
3064 if( newOffset == -1 ){
3065 ((unixFile*)id)->lastErrno = errno;
3066 }else{
3067 ((unixFile*)id)->lastErrno = 0;
3068 }
3069 return -1;
drh734c9862008-11-28 15:37:20 +00003070 }
drhbd1e50c2011-08-19 14:54:12 +00003071 got = osWrite(id->h, pBuf, cnt);
3072 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003073#endif
3074 TIMER_END;
3075 if( got<0 ){
3076 ((unixFile*)id)->lastErrno = errno;
3077 }
3078
drh308c2a52010-05-14 11:30:18 +00003079 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003080 return got;
3081}
3082
3083
3084/*
3085** Write data from a buffer into a file. Return SQLITE_OK on success
3086** or some other error code on failure.
3087*/
3088static int unixWrite(
3089 sqlite3_file *id,
3090 const void *pBuf,
3091 int amt,
3092 sqlite3_int64 offset
3093){
dan08da86a2009-08-21 17:18:03 +00003094 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003095 int wrote = 0;
3096 assert( id );
3097 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003098
dan08da86a2009-08-21 17:18:03 +00003099 /* If this is a database file (not a journal, master-journal or temp
3100 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003101#if 0
dane946c392009-08-22 11:39:46 +00003102 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003103 || offset>=PENDING_BYTE+512
3104 || offset+amt<=PENDING_BYTE
3105 );
dan7c246102010-04-12 19:00:29 +00003106#endif
drh08c6d442009-02-09 17:34:07 +00003107
drh8f941bc2009-01-14 23:03:40 +00003108#ifndef NDEBUG
3109 /* If we are doing a normal write to a database file (as opposed to
3110 ** doing a hot-journal rollback or a write to some file other than a
3111 ** normal database file) then record the fact that the database
3112 ** has changed. If the transaction counter is modified, record that
3113 ** fact too.
3114 */
dan08da86a2009-08-21 17:18:03 +00003115 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003116 pFile->dbUpdate = 1; /* The database has been modified */
3117 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003118 int rc;
drh8f941bc2009-01-14 23:03:40 +00003119 char oldCntr[4];
3120 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003121 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003122 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003123 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003124 pFile->transCntrChng = 1; /* The transaction counter has changed */
3125 }
3126 }
3127 }
3128#endif
3129
dan08da86a2009-08-21 17:18:03 +00003130 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003131 amt -= wrote;
3132 offset += wrote;
3133 pBuf = &((char*)pBuf)[wrote];
3134 }
3135 SimulateIOError(( wrote=(-1), amt=1 ));
3136 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003137
drh734c9862008-11-28 15:37:20 +00003138 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003139 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003140 /* lastErrno set by seekAndWrite */
3141 return SQLITE_IOERR_WRITE;
3142 }else{
dan08da86a2009-08-21 17:18:03 +00003143 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003144 return SQLITE_FULL;
3145 }
3146 }
dan6e09d692010-07-27 18:34:15 +00003147
drh734c9862008-11-28 15:37:20 +00003148 return SQLITE_OK;
3149}
3150
3151#ifdef SQLITE_TEST
3152/*
3153** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003154** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003155*/
3156int sqlite3_sync_count = 0;
3157int sqlite3_fullsync_count = 0;
3158#endif
3159
3160/*
drh89240432009-03-25 01:06:01 +00003161** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003162** Others do no. To be safe, we will stick with the (slightly slower)
3163** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003164** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003165*/
drh20f8e132011-08-31 21:01:55 +00003166#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003167# define fdatasync fsync
3168#endif
3169
3170/*
3171** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3172** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3173** only available on Mac OS X. But that could change.
3174*/
3175#ifdef F_FULLFSYNC
3176# define HAVE_FULLFSYNC 1
3177#else
3178# define HAVE_FULLFSYNC 0
3179#endif
3180
3181
3182/*
3183** The fsync() system call does not work as advertised on many
3184** unix systems. The following procedure is an attempt to make
3185** it work better.
3186**
3187** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3188** for testing when we want to run through the test suite quickly.
3189** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3190** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3191** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003192**
3193** SQLite sets the dataOnly flag if the size of the file is unchanged.
3194** The idea behind dataOnly is that it should only write the file content
3195** to disk, not the inode. We only set dataOnly if the file size is
3196** unchanged since the file size is part of the inode. However,
3197** Ted Ts'o tells us that fdatasync() will also write the inode if the
3198** file size has changed. The only real difference between fdatasync()
3199** and fsync(), Ted tells us, is that fdatasync() will not flush the
3200** inode if the mtime or owner or other inode attributes have changed.
3201** We only care about the file size, not the other file attributes, so
3202** as far as SQLite is concerned, an fdatasync() is always adequate.
3203** So, we always use fdatasync() if it is available, regardless of
3204** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003205*/
3206static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003207 int rc;
drh734c9862008-11-28 15:37:20 +00003208
3209 /* The following "ifdef/elif/else/" block has the same structure as
3210 ** the one below. It is replicated here solely to avoid cluttering
3211 ** up the real code with the UNUSED_PARAMETER() macros.
3212 */
3213#ifdef SQLITE_NO_SYNC
3214 UNUSED_PARAMETER(fd);
3215 UNUSED_PARAMETER(fullSync);
3216 UNUSED_PARAMETER(dataOnly);
3217#elif HAVE_FULLFSYNC
3218 UNUSED_PARAMETER(dataOnly);
3219#else
3220 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003221 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003222#endif
3223
3224 /* Record the number of times that we do a normal fsync() and
3225 ** FULLSYNC. This is used during testing to verify that this procedure
3226 ** gets called with the correct arguments.
3227 */
3228#ifdef SQLITE_TEST
3229 if( fullSync ) sqlite3_fullsync_count++;
3230 sqlite3_sync_count++;
3231#endif
3232
3233 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3234 ** no-op
3235 */
3236#ifdef SQLITE_NO_SYNC
3237 rc = SQLITE_OK;
3238#elif HAVE_FULLFSYNC
3239 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003240 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003241 }else{
3242 rc = 1;
3243 }
3244 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003245 ** It shouldn't be possible for fullfsync to fail on the local
3246 ** file system (on OSX), so failure indicates that FULLFSYNC
3247 ** isn't supported for this file system. So, attempt an fsync
3248 ** and (for now) ignore the overhead of a superfluous fcntl call.
3249 ** It'd be better to detect fullfsync support once and avoid
3250 ** the fcntl call every time sync is called.
3251 */
drh734c9862008-11-28 15:37:20 +00003252 if( rc ) rc = fsync(fd);
3253
drh7ed97b92010-01-20 13:07:21 +00003254#elif defined(__APPLE__)
3255 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3256 ** so currently we default to the macro that redefines fdatasync to fsync
3257 */
3258 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003259#else
drh0b647ff2009-03-21 14:41:04 +00003260 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003261#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003262 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003263 rc = fsync(fd);
3264 }
drh0b647ff2009-03-21 14:41:04 +00003265#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003266#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3267
3268 if( OS_VXWORKS && rc!= -1 ){
3269 rc = 0;
3270 }
chw97185482008-11-17 08:05:31 +00003271 return rc;
drhbfe66312006-10-03 17:40:40 +00003272}
3273
drh734c9862008-11-28 15:37:20 +00003274/*
drh0059eae2011-08-08 23:48:40 +00003275** Open a file descriptor to the directory containing file zFilename.
3276** If successful, *pFd is set to the opened file descriptor and
3277** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3278** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3279** value.
3280**
drh90315a22011-08-10 01:52:12 +00003281** The directory file descriptor is used for only one thing - to
3282** fsync() a directory to make sure file creation and deletion events
3283** are flushed to disk. Such fsyncs are not needed on newer
3284** journaling filesystems, but are required on older filesystems.
3285**
3286** This routine can be overridden using the xSetSysCall interface.
3287** The ability to override this routine was added in support of the
3288** chromium sandbox. Opening a directory is a security risk (we are
3289** told) so making it overrideable allows the chromium sandbox to
3290** replace this routine with a harmless no-op. To make this routine
3291** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3292** *pFd set to a negative number.
3293**
drh0059eae2011-08-08 23:48:40 +00003294** If SQLITE_OK is returned, the caller is responsible for closing
3295** the file descriptor *pFd using close().
3296*/
3297static int openDirectory(const char *zFilename, int *pFd){
3298 int ii;
3299 int fd = -1;
3300 char zDirname[MAX_PATHNAME+1];
3301
3302 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3303 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3304 if( ii>0 ){
3305 zDirname[ii] = '\0';
3306 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3307 if( fd>=0 ){
3308#ifdef FD_CLOEXEC
3309 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3310#endif
3311 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3312 }
3313 }
3314 *pFd = fd;
3315 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3316}
3317
3318/*
drh734c9862008-11-28 15:37:20 +00003319** Make sure all writes to a particular file are committed to disk.
3320**
3321** If dataOnly==0 then both the file itself and its metadata (file
3322** size, access time, etc) are synced. If dataOnly!=0 then only the
3323** file data is synced.
3324**
3325** Under Unix, also make sure that the directory entry for the file
3326** has been created by fsync-ing the directory that contains the file.
3327** If we do not do this and we encounter a power failure, the directory
3328** entry for the journal might not exist after we reboot. The next
3329** SQLite to access the file will not know that the journal exists (because
3330** the directory entry for the journal was never created) and the transaction
3331** will not roll back - possibly leading to database corruption.
3332*/
3333static int unixSync(sqlite3_file *id, int flags){
3334 int rc;
3335 unixFile *pFile = (unixFile*)id;
3336
3337 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3338 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3339
3340 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3341 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3342 || (flags&0x0F)==SQLITE_SYNC_FULL
3343 );
3344
3345 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3346 ** line is to test that doing so does not cause any problems.
3347 */
3348 SimulateDiskfullError( return SQLITE_FULL );
3349
3350 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003351 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003352 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3353 SimulateIOError( rc=1 );
3354 if( rc ){
3355 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003356 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003357 }
drh0059eae2011-08-08 23:48:40 +00003358
3359 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003360 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3361 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003362 */
3363 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3364 int dirfd;
3365 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003366 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003367 rc = osOpenDirectory(pFile->zPath, &dirfd);
3368 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003369 full_fsync(dirfd, 0, 0);
3370 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003371 }else if( rc==SQLITE_CANTOPEN ){
3372 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003373 }
drh0059eae2011-08-08 23:48:40 +00003374 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003375 }
3376 return rc;
3377}
3378
3379/*
3380** Truncate an open file to a specified size
3381*/
3382static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003383 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003384 int rc;
dan6e09d692010-07-27 18:34:15 +00003385 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003386 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003387
3388 /* If the user has configured a chunk-size for this file, truncate the
3389 ** file so that it consists of an integer number of chunks (i.e. the
3390 ** actual file size after the operation may be larger than the requested
3391 ** size).
3392 */
3393 if( pFile->szChunk ){
3394 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3395 }
3396
drhff812312011-02-23 13:33:46 +00003397 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003398 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003399 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003400 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003401 }else{
drh3313b142009-11-06 04:13:18 +00003402#ifndef NDEBUG
3403 /* If we are doing a normal write to a database file (as opposed to
3404 ** doing a hot-journal rollback or a write to some file other than a
3405 ** normal database file) and we truncate the file to zero length,
3406 ** that effectively updates the change counter. This might happen
3407 ** when restoring a database using the backup API from a zero-length
3408 ** source.
3409 */
dan6e09d692010-07-27 18:34:15 +00003410 if( pFile->inNormalWrite && nByte==0 ){
3411 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003412 }
3413#endif
3414
drh734c9862008-11-28 15:37:20 +00003415 return SQLITE_OK;
3416 }
3417}
3418
3419/*
3420** Determine the current size of a file in bytes
3421*/
3422static int unixFileSize(sqlite3_file *id, i64 *pSize){
3423 int rc;
3424 struct stat buf;
3425 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003426 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003427 SimulateIOError( rc=1 );
3428 if( rc!=0 ){
3429 ((unixFile*)id)->lastErrno = errno;
3430 return SQLITE_IOERR_FSTAT;
3431 }
3432 *pSize = buf.st_size;
3433
drh8af6c222010-05-14 12:43:01 +00003434 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003435 ** writes a single byte into that file in order to work around a bug
3436 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3437 ** layers, we need to report this file size as zero even though it is
3438 ** really 1. Ticket #3260.
3439 */
3440 if( *pSize==1 ) *pSize = 0;
3441
3442
3443 return SQLITE_OK;
3444}
3445
drhd2cb50b2009-01-09 21:41:17 +00003446#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003447/*
3448** Handler for proxy-locking file-control verbs. Defined below in the
3449** proxying locking division.
3450*/
3451static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003452#endif
drh715ff302008-12-03 22:32:44 +00003453
dan502019c2010-07-28 14:26:17 +00003454/*
3455** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003456** file-control operation. Enlarge the database to nBytes in size
3457** (rounded up to the next chunk-size). If the database is already
3458** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003459*/
3460static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003461 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003462 i64 nSize; /* Required file size */
3463 struct stat buf; /* Used to hold return values of fstat() */
3464
drh99ab3b12011-03-02 15:09:07 +00003465 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003466
3467 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3468 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003469
dan502019c2010-07-28 14:26:17 +00003470#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003471 /* The code below is handling the return value of osFallocate()
3472 ** correctly. posix_fallocate() is defined to "returns zero on success,
3473 ** or an error number on failure". See the manpage for details. */
3474 int err;
drhff812312011-02-23 13:33:46 +00003475 do{
dan661d71a2011-03-30 19:08:03 +00003476 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3477 }while( err==EINTR );
3478 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003479#else
3480 /* If the OS does not have posix_fallocate(), fake it. First use
3481 ** ftruncate() to set the file size, then write a single byte to
3482 ** the last byte in each block within the extended region. This
3483 ** is the same technique used by glibc to implement posix_fallocate()
3484 ** on systems that do not have a real fallocate() system call.
3485 */
3486 int nBlk = buf.st_blksize; /* File-system block size */
3487 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003488
drhff812312011-02-23 13:33:46 +00003489 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003490 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003491 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003492 }
3493 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003494 while( iWrite<nSize ){
3495 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3496 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003497 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003498 }
dan502019c2010-07-28 14:26:17 +00003499#endif
3500 }
3501 }
3502
3503 return SQLITE_OK;
3504}
danielk1977ad94b582007-08-20 06:44:22 +00003505
danielk1977e3026632004-06-22 11:29:02 +00003506/*
drhf12b3f62011-12-21 14:42:29 +00003507** If *pArg is inititially negative then this is a query. Set *pArg to
3508** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3509**
3510** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3511*/
3512static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3513 if( *pArg<0 ){
3514 *pArg = (pFile->ctrlFlags & mask)!=0;
3515 }else if( (*pArg)==0 ){
3516 pFile->ctrlFlags &= ~mask;
3517 }else{
3518 pFile->ctrlFlags |= mask;
3519 }
3520}
3521
3522/*
drh9e33c2c2007-08-31 18:34:59 +00003523** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003524*/
drhcc6bb3e2007-08-31 16:11:35 +00003525static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003526 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003527 switch( op ){
3528 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003529 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003530 return SQLITE_OK;
3531 }
drh7708e972008-11-29 00:56:52 +00003532 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003533 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003534 return SQLITE_OK;
3535 }
dan6e09d692010-07-27 18:34:15 +00003536 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003537 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003538 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003539 }
drh9ff27ec2010-05-19 19:26:05 +00003540 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003541 int rc;
3542 SimulateIOErrorBenign(1);
3543 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3544 SimulateIOErrorBenign(0);
3545 return rc;
drhf0b190d2011-07-26 16:03:07 +00003546 }
3547 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003548 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3549 return SQLITE_OK;
3550 }
drhcb15f352011-12-23 01:04:17 +00003551 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3552 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003553 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003554 }
drhde60fc22011-12-14 17:53:36 +00003555 case SQLITE_FCNTL_VFSNAME: {
3556 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3557 return SQLITE_OK;
3558 }
drh8f941bc2009-01-14 23:03:40 +00003559#ifndef NDEBUG
3560 /* The pager calls this method to signal that it has done
3561 ** a rollback and that the database is therefore unchanged and
3562 ** it hence it is OK for the transaction change counter to be
3563 ** unchanged.
3564 */
3565 case SQLITE_FCNTL_DB_UNCHANGED: {
3566 ((unixFile*)id)->dbUpdate = 0;
3567 return SQLITE_OK;
3568 }
3569#endif
drhd2cb50b2009-01-09 21:41:17 +00003570#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003571 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003572 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003573 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003574 }
drhd2cb50b2009-01-09 21:41:17 +00003575#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003576 }
drh0b52b7d2011-01-26 19:46:22 +00003577 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003578}
3579
3580/*
danielk1977a3d4c882007-03-23 10:08:38 +00003581** Return the sector size in bytes of the underlying block device for
3582** the specified file. This is almost always 512 bytes, but may be
3583** larger for some devices.
3584**
3585** SQLite code assumes this function cannot fail. It also assumes that
3586** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003587** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003588** same for both.
3589*/
drh1da88f02011-12-17 16:09:16 +00003590static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003591 (void)pFile;
3592 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003593}
3594
danielk197790949c22007-08-17 16:50:38 +00003595/*
drhf12b3f62011-12-21 14:42:29 +00003596** Return the device characteristics for the file.
3597**
drhcb15f352011-12-23 01:04:17 +00003598** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3599** However, that choice is contraversial since technically the underlying
3600** file system does not always provide powersafe overwrites. (In other
3601** words, after a power-loss event, parts of the file that were never
3602** written might end up being altered.) However, non-PSOW behavior is very,
3603** very rare. And asserting PSOW makes a large reduction in the amount
3604** of required I/O for journaling, since a lot of padding is eliminated.
3605** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3606** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003607*/
drhf12b3f62011-12-21 14:42:29 +00003608static int unixDeviceCharacteristics(sqlite3_file *id){
3609 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003610 if( p->ctrlFlags & UNIXFILE_PSOW ){
3611 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3612 }else{
3613 return 0;
3614 }
danielk197762079062007-08-15 17:08:46 +00003615}
3616
drhd9e5c4f2010-05-12 18:01:39 +00003617#ifndef SQLITE_OMIT_WAL
3618
3619
3620/*
drhd91c68f2010-05-14 14:52:25 +00003621** Object used to represent an shared memory buffer.
3622**
3623** When multiple threads all reference the same wal-index, each thread
3624** has its own unixShm object, but they all point to a single instance
3625** of this unixShmNode object. In other words, each wal-index is opened
3626** only once per process.
3627**
3628** Each unixShmNode object is connected to a single unixInodeInfo object.
3629** We could coalesce this object into unixInodeInfo, but that would mean
3630** every open file that does not use shared memory (in other words, most
3631** open files) would have to carry around this extra information. So
3632** the unixInodeInfo object contains a pointer to this unixShmNode object
3633** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003634**
3635** unixMutexHeld() must be true when creating or destroying
3636** this object or while reading or writing the following fields:
3637**
3638** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003639**
3640** The following fields are read-only after the object is created:
3641**
3642** fid
3643** zFilename
3644**
drhd91c68f2010-05-14 14:52:25 +00003645** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003646** unixMutexHeld() is true when reading or writing any other field
3647** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003648*/
drhd91c68f2010-05-14 14:52:25 +00003649struct unixShmNode {
3650 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003651 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003652 char *zFilename; /* Name of the mmapped file */
3653 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003654 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003655 u16 nRegion; /* Size of array apRegion */
3656 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003657 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003658 int nRef; /* Number of unixShm objects pointing to this */
3659 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003660#ifdef SQLITE_DEBUG
3661 u8 exclMask; /* Mask of exclusive locks held */
3662 u8 sharedMask; /* Mask of shared locks held */
3663 u8 nextShmId; /* Next available unixShm.id value */
3664#endif
3665};
3666
3667/*
drhd9e5c4f2010-05-12 18:01:39 +00003668** Structure used internally by this VFS to record the state of an
3669** open shared memory connection.
3670**
drhd91c68f2010-05-14 14:52:25 +00003671** The following fields are initialized when this object is created and
3672** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003673**
drhd91c68f2010-05-14 14:52:25 +00003674** unixShm.pFile
3675** unixShm.id
3676**
3677** All other fields are read/write. The unixShm.pFile->mutex must be held
3678** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003679*/
3680struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003681 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3682 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003683 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003684 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003685 u16 sharedMask; /* Mask of shared locks held */
3686 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003687};
3688
3689/*
drhd9e5c4f2010-05-12 18:01:39 +00003690** Constants used for locking
3691*/
drhbd9676c2010-06-23 17:58:38 +00003692#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003693#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003694
drhd9e5c4f2010-05-12 18:01:39 +00003695/*
drh73b64e42010-05-30 19:55:15 +00003696** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003697**
3698** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3699** otherwise.
3700*/
3701static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003702 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3703 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003704 int ofst, /* First byte of the locking range */
3705 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003706){
3707 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003708 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003709
drhd91c68f2010-05-14 14:52:25 +00003710 /* Access to the unixShmNode object is serialized by the caller */
3711 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003712
drh73b64e42010-05-30 19:55:15 +00003713 /* Shared locks never span more than one byte */
3714 assert( n==1 || lockType!=F_RDLCK );
3715
3716 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003717 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003718
drh3cb93392011-03-12 18:10:44 +00003719 if( pShmNode->h>=0 ){
3720 /* Initialize the locking parameters */
3721 memset(&f, 0, sizeof(f));
3722 f.l_type = lockType;
3723 f.l_whence = SEEK_SET;
3724 f.l_start = ofst;
3725 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003726
drh3cb93392011-03-12 18:10:44 +00003727 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3728 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3729 }
drhd9e5c4f2010-05-12 18:01:39 +00003730
3731 /* Update the global lock state and do debug tracing */
3732#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003733 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003734 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003735 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003736 if( rc==SQLITE_OK ){
3737 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003738 OSTRACE(("unlock %d ok", ofst));
3739 pShmNode->exclMask &= ~mask;
3740 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003741 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003742 OSTRACE(("read-lock %d ok", ofst));
3743 pShmNode->exclMask &= ~mask;
3744 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003745 }else{
3746 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003747 OSTRACE(("write-lock %d ok", ofst));
3748 pShmNode->exclMask |= mask;
3749 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003750 }
3751 }else{
3752 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003753 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003754 }else if( lockType==F_RDLCK ){
3755 OSTRACE(("read-lock failed"));
3756 }else{
3757 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003758 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003759 }
3760 }
drh20e1f082010-05-31 16:10:12 +00003761 OSTRACE((" - afterwards %03x,%03x\n",
3762 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003763 }
drhd9e5c4f2010-05-12 18:01:39 +00003764#endif
3765
3766 return rc;
3767}
3768
drhd9e5c4f2010-05-12 18:01:39 +00003769
3770/*
drhd91c68f2010-05-14 14:52:25 +00003771** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003772**
3773** This is not a VFS shared-memory method; it is a utility function called
3774** by VFS shared-memory methods.
3775*/
drhd91c68f2010-05-14 14:52:25 +00003776static void unixShmPurge(unixFile *pFd){
3777 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003778 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003779 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003780 int i;
drhd91c68f2010-05-14 14:52:25 +00003781 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003782 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003783 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003784 if( p->h>=0 ){
3785 munmap(p->apRegion[i], p->szRegion);
3786 }else{
3787 sqlite3_free(p->apRegion[i]);
3788 }
dan13a3cb82010-06-11 19:04:21 +00003789 }
dan18801912010-06-14 14:07:50 +00003790 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003791 if( p->h>=0 ){
3792 robust_close(pFd, p->h, __LINE__);
3793 p->h = -1;
3794 }
drhd91c68f2010-05-14 14:52:25 +00003795 p->pInode->pShmNode = 0;
3796 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003797 }
3798}
3799
3800/*
danda9fe0c2010-07-13 18:44:03 +00003801** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003802** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003803**
drh7234c6d2010-06-19 15:10:09 +00003804** The file used to implement shared-memory is in the same directory
3805** as the open database file and has the same name as the open database
3806** file with the "-shm" suffix added. For example, if the database file
3807** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003808** for shared memory will be called "/home/user1/config.db-shm".
3809**
3810** Another approach to is to use files in /dev/shm or /dev/tmp or an
3811** some other tmpfs mount. But if a file in a different directory
3812** from the database file is used, then differing access permissions
3813** or a chroot() might cause two different processes on the same
3814** database to end up using different files for shared memory -
3815** meaning that their memory would not really be shared - resulting
3816** in database corruption. Nevertheless, this tmpfs file usage
3817** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3818** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3819** option results in an incompatible build of SQLite; builds of SQLite
3820** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3821** same database file at the same time, database corruption will likely
3822** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3823** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003824**
3825** When opening a new shared-memory file, if no other instances of that
3826** file are currently open, in this process or in other processes, then
3827** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003828**
3829** If the original database file (pDbFd) is using the "unix-excl" VFS
3830** that means that an exclusive lock is held on the database file and
3831** that no other processes are able to read or write the database. In
3832** that case, we do not really need shared memory. No shared memory
3833** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003834*/
danda9fe0c2010-07-13 18:44:03 +00003835static int unixOpenSharedMemory(unixFile *pDbFd){
3836 struct unixShm *p = 0; /* The connection to be opened */
3837 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3838 int rc; /* Result code */
3839 unixInodeInfo *pInode; /* The inode of fd */
3840 char *zShmFilename; /* Name of the file used for SHM */
3841 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003842
danda9fe0c2010-07-13 18:44:03 +00003843 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003844 p = sqlite3_malloc( sizeof(*p) );
3845 if( p==0 ) return SQLITE_NOMEM;
3846 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003847 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003848
danda9fe0c2010-07-13 18:44:03 +00003849 /* Check to see if a unixShmNode object already exists. Reuse an existing
3850 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003851 */
3852 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003853 pInode = pDbFd->pInode;
3854 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003855 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003856 struct stat sStat; /* fstat() info for database file */
3857
3858 /* Call fstat() to figure out the permissions on the database file. If
3859 ** a new *-shm file is created, an attempt will be made to create it
3860 ** with the same permissions. The actual permissions the file is created
3861 ** with are subject to the current umask setting.
3862 */
drh3cb93392011-03-12 18:10:44 +00003863 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003864 rc = SQLITE_IOERR_FSTAT;
3865 goto shm_open_err;
3866 }
3867
drha4ced192010-07-15 18:32:40 +00003868#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003869 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003870#else
drh52bcde02012-01-03 14:50:45 +00003871 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003872#endif
drh7234c6d2010-06-19 15:10:09 +00003873 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003874 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003875 rc = SQLITE_NOMEM;
3876 goto shm_open_err;
3877 }
drh9cb5a0d2012-01-05 21:19:54 +00003878 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003879 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003880#ifdef SQLITE_SHM_DIRECTORY
3881 sqlite3_snprintf(nShmFilename, zShmFilename,
3882 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3883 (u32)sStat.st_ino, (u32)sStat.st_dev);
3884#else
drh7234c6d2010-06-19 15:10:09 +00003885 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003886 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003887#endif
drhd91c68f2010-05-14 14:52:25 +00003888 pShmNode->h = -1;
3889 pDbFd->pInode->pShmNode = pShmNode;
3890 pShmNode->pInode = pDbFd->pInode;
3891 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3892 if( pShmNode->mutex==0 ){
3893 rc = SQLITE_NOMEM;
3894 goto shm_open_err;
3895 }
drhd9e5c4f2010-05-12 18:01:39 +00003896
drh3cb93392011-03-12 18:10:44 +00003897 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003898 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003899 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003900 openFlags = O_RDONLY;
3901 pShmNode->isReadonly = 1;
3902 }
3903 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003904 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003905 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3906 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003907 }
drhac7c3ac2012-02-11 19:23:48 +00003908
3909 /* If this process is running as root, make sure that the SHM file
3910 ** is owned by the same user that owns the original database. Otherwise,
3911 ** the original owner will not be able to connect. If this process is
drh3ee34842012-02-11 21:21:17 +00003912 ** not root, the following fchown() will fail, but we don't care. The
3913 ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
3914 ** warnings.
drhac7c3ac2012-02-11 19:23:48 +00003915 */
drh3ee34842012-02-11 21:21:17 +00003916 if( fchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
3917 pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
3918 }
drh3cb93392011-03-12 18:10:44 +00003919
3920 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003921 ** If not, truncate the file to zero length.
3922 */
3923 rc = SQLITE_OK;
3924 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3925 if( robust_ftruncate(pShmNode->h, 0) ){
3926 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003927 }
3928 }
drh66dfec8b2011-06-01 20:01:49 +00003929 if( rc==SQLITE_OK ){
3930 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3931 }
3932 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003933 }
drhd9e5c4f2010-05-12 18:01:39 +00003934 }
3935
drhd91c68f2010-05-14 14:52:25 +00003936 /* Make the new connection a child of the unixShmNode */
3937 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003938#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003939 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003940#endif
drhd91c68f2010-05-14 14:52:25 +00003941 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003942 pDbFd->pShm = p;
3943 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003944
3945 /* The reference count on pShmNode has already been incremented under
3946 ** the cover of the unixEnterMutex() mutex and the pointer from the
3947 ** new (struct unixShm) object to the pShmNode has been set. All that is
3948 ** left to do is to link the new object into the linked list starting
3949 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3950 ** mutex.
3951 */
3952 sqlite3_mutex_enter(pShmNode->mutex);
3953 p->pNext = pShmNode->pFirst;
3954 pShmNode->pFirst = p;
3955 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003956 return SQLITE_OK;
3957
3958 /* Jump here on any error */
3959shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003960 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003961 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003962 unixLeaveMutex();
3963 return rc;
3964}
3965
3966/*
danda9fe0c2010-07-13 18:44:03 +00003967** This function is called to obtain a pointer to region iRegion of the
3968** shared-memory associated with the database file fd. Shared-memory regions
3969** are numbered starting from zero. Each shared-memory region is szRegion
3970** bytes in size.
3971**
3972** If an error occurs, an error code is returned and *pp is set to NULL.
3973**
3974** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3975** region has not been allocated (by any client, including one running in a
3976** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3977** bExtend is non-zero and the requested shared-memory region has not yet
3978** been allocated, it is allocated by this function.
3979**
3980** If the shared-memory region has already been allocated or is allocated by
3981** this call as described above, then it is mapped into this processes
3982** address space (if it is not already), *pp is set to point to the mapped
3983** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003984*/
danda9fe0c2010-07-13 18:44:03 +00003985static int unixShmMap(
3986 sqlite3_file *fd, /* Handle open on database file */
3987 int iRegion, /* Region to retrieve */
3988 int szRegion, /* Size of regions */
3989 int bExtend, /* True to extend file if necessary */
3990 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003991){
danda9fe0c2010-07-13 18:44:03 +00003992 unixFile *pDbFd = (unixFile*)fd;
3993 unixShm *p;
3994 unixShmNode *pShmNode;
3995 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003996
danda9fe0c2010-07-13 18:44:03 +00003997 /* If the shared-memory file has not yet been opened, open it now. */
3998 if( pDbFd->pShm==0 ){
3999 rc = unixOpenSharedMemory(pDbFd);
4000 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004001 }
drhd9e5c4f2010-05-12 18:01:39 +00004002
danda9fe0c2010-07-13 18:44:03 +00004003 p = pDbFd->pShm;
4004 pShmNode = p->pShmNode;
4005 sqlite3_mutex_enter(pShmNode->mutex);
4006 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004007 assert( pShmNode->pInode==pDbFd->pInode );
4008 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4009 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004010
4011 if( pShmNode->nRegion<=iRegion ){
4012 char **apNew; /* New apRegion[] array */
4013 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4014 struct stat sStat; /* Used by fstat() */
4015
4016 pShmNode->szRegion = szRegion;
4017
drh3cb93392011-03-12 18:10:44 +00004018 if( pShmNode->h>=0 ){
4019 /* The requested region is not mapped into this processes address space.
4020 ** Check to see if it has been allocated (i.e. if the wal-index file is
4021 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004022 */
drh3cb93392011-03-12 18:10:44 +00004023 if( osFstat(pShmNode->h, &sStat) ){
4024 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004025 goto shmpage_out;
4026 }
drh3cb93392011-03-12 18:10:44 +00004027
4028 if( sStat.st_size<nByte ){
4029 /* The requested memory region does not exist. If bExtend is set to
4030 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4031 **
4032 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4033 ** the requested memory region.
4034 */
4035 if( !bExtend ) goto shmpage_out;
4036 if( robust_ftruncate(pShmNode->h, nByte) ){
4037 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4038 pShmNode->zFilename);
4039 goto shmpage_out;
4040 }
4041 }
danda9fe0c2010-07-13 18:44:03 +00004042 }
4043
4044 /* Map the requested memory region into this processes address space. */
4045 apNew = (char **)sqlite3_realloc(
4046 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4047 );
4048 if( !apNew ){
4049 rc = SQLITE_IOERR_NOMEM;
4050 goto shmpage_out;
4051 }
4052 pShmNode->apRegion = apNew;
4053 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004054 void *pMem;
4055 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004056 pMem = mmap(0, szRegion,
4057 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004058 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4059 );
4060 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004061 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004062 goto shmpage_out;
4063 }
4064 }else{
4065 pMem = sqlite3_malloc(szRegion);
4066 if( pMem==0 ){
4067 rc = SQLITE_NOMEM;
4068 goto shmpage_out;
4069 }
4070 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004071 }
4072 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4073 pShmNode->nRegion++;
4074 }
4075 }
4076
4077shmpage_out:
4078 if( pShmNode->nRegion>iRegion ){
4079 *pp = pShmNode->apRegion[iRegion];
4080 }else{
4081 *pp = 0;
4082 }
drh66dfec8b2011-06-01 20:01:49 +00004083 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004084 sqlite3_mutex_leave(pShmNode->mutex);
4085 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004086}
4087
4088/*
drhd9e5c4f2010-05-12 18:01:39 +00004089** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004090**
4091** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4092** different here than in posix. In xShmLock(), one can go from unlocked
4093** to shared and back or from unlocked to exclusive and back. But one may
4094** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004095*/
4096static int unixShmLock(
4097 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004098 int ofst, /* First lock to acquire or release */
4099 int n, /* Number of locks to acquire or release */
4100 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004101){
drh73b64e42010-05-30 19:55:15 +00004102 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4103 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4104 unixShm *pX; /* For looping over all siblings */
4105 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4106 int rc = SQLITE_OK; /* Result code */
4107 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004108
drhd91c68f2010-05-14 14:52:25 +00004109 assert( pShmNode==pDbFd->pInode->pShmNode );
4110 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004111 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004112 assert( n>=1 );
4113 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4114 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4115 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4116 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4117 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004118 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4119 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004120
drhc99597c2010-05-31 01:41:15 +00004121 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004122 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004123 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004124 if( flags & SQLITE_SHM_UNLOCK ){
4125 u16 allMask = 0; /* Mask of locks held by siblings */
4126
4127 /* See if any siblings hold this same lock */
4128 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4129 if( pX==p ) continue;
4130 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4131 allMask |= pX->sharedMask;
4132 }
4133
4134 /* Unlock the system-level locks */
4135 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004136 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004137 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004138 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004139 }
drh73b64e42010-05-30 19:55:15 +00004140
4141 /* Undo the local locks */
4142 if( rc==SQLITE_OK ){
4143 p->exclMask &= ~mask;
4144 p->sharedMask &= ~mask;
4145 }
4146 }else if( flags & SQLITE_SHM_SHARED ){
4147 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4148
4149 /* Find out which shared locks are already held by sibling connections.
4150 ** If any sibling already holds an exclusive lock, go ahead and return
4151 ** SQLITE_BUSY.
4152 */
4153 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004154 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004155 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004156 break;
4157 }
4158 allShared |= pX->sharedMask;
4159 }
4160
4161 /* Get shared locks at the system level, if necessary */
4162 if( rc==SQLITE_OK ){
4163 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004164 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004165 }else{
drh73b64e42010-05-30 19:55:15 +00004166 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004167 }
drhd9e5c4f2010-05-12 18:01:39 +00004168 }
drh73b64e42010-05-30 19:55:15 +00004169
4170 /* Get the local shared locks */
4171 if( rc==SQLITE_OK ){
4172 p->sharedMask |= mask;
4173 }
4174 }else{
4175 /* Make sure no sibling connections hold locks that will block this
4176 ** lock. If any do, return SQLITE_BUSY right away.
4177 */
4178 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004179 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4180 rc = SQLITE_BUSY;
4181 break;
4182 }
4183 }
4184
4185 /* Get the exclusive locks at the system level. Then if successful
4186 ** also mark the local connection as being locked.
4187 */
4188 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004189 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004190 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004191 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004192 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004193 }
drhd9e5c4f2010-05-12 18:01:39 +00004194 }
4195 }
drhd91c68f2010-05-14 14:52:25 +00004196 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004197 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4198 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004199 return rc;
4200}
4201
drh286a2882010-05-20 23:51:06 +00004202/*
4203** Implement a memory barrier or memory fence on shared memory.
4204**
4205** All loads and stores begun before the barrier must complete before
4206** any load or store begun after the barrier.
4207*/
4208static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004209 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004210){
drhff828942010-06-26 21:34:06 +00004211 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004212 unixEnterMutex();
4213 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004214}
4215
dan18801912010-06-14 14:07:50 +00004216/*
danda9fe0c2010-07-13 18:44:03 +00004217** Close a connection to shared-memory. Delete the underlying
4218** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004219**
4220** If there is no shared memory associated with the connection then this
4221** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004222*/
danda9fe0c2010-07-13 18:44:03 +00004223static int unixShmUnmap(
4224 sqlite3_file *fd, /* The underlying database file */
4225 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004226){
danda9fe0c2010-07-13 18:44:03 +00004227 unixShm *p; /* The connection to be closed */
4228 unixShmNode *pShmNode; /* The underlying shared-memory file */
4229 unixShm **pp; /* For looping over sibling connections */
4230 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004231
danda9fe0c2010-07-13 18:44:03 +00004232 pDbFd = (unixFile*)fd;
4233 p = pDbFd->pShm;
4234 if( p==0 ) return SQLITE_OK;
4235 pShmNode = p->pShmNode;
4236
4237 assert( pShmNode==pDbFd->pInode->pShmNode );
4238 assert( pShmNode->pInode==pDbFd->pInode );
4239
4240 /* Remove connection p from the set of connections associated
4241 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004242 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004243 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4244 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004245
danda9fe0c2010-07-13 18:44:03 +00004246 /* Free the connection p */
4247 sqlite3_free(p);
4248 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004249 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004250
4251 /* If pShmNode->nRef has reached 0, then close the underlying
4252 ** shared-memory file, too */
4253 unixEnterMutex();
4254 assert( pShmNode->nRef>0 );
4255 pShmNode->nRef--;
4256 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004257 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004258 unixShmPurge(pDbFd);
4259 }
4260 unixLeaveMutex();
4261
4262 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004263}
drh286a2882010-05-20 23:51:06 +00004264
danda9fe0c2010-07-13 18:44:03 +00004265
drhd9e5c4f2010-05-12 18:01:39 +00004266#else
drh6b017cc2010-06-14 18:01:46 +00004267# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004268# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004269# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004270# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004271#endif /* #ifndef SQLITE_OMIT_WAL */
4272
drh734c9862008-11-28 15:37:20 +00004273/*
4274** Here ends the implementation of all sqlite3_file methods.
4275**
4276********************** End sqlite3_file Methods *******************************
4277******************************************************************************/
4278
4279/*
drh6b9d6dd2008-12-03 19:34:47 +00004280** This division contains definitions of sqlite3_io_methods objects that
4281** implement various file locking strategies. It also contains definitions
4282** of "finder" functions. A finder-function is used to locate the appropriate
4283** sqlite3_io_methods object for a particular database file. The pAppData
4284** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4285** the correct finder-function for that VFS.
4286**
4287** Most finder functions return a pointer to a fixed sqlite3_io_methods
4288** object. The only interesting finder-function is autolockIoFinder, which
4289** looks at the filesystem type and tries to guess the best locking
4290** strategy from that.
4291**
drh1875f7a2008-12-08 18:19:17 +00004292** For finder-funtion F, two objects are created:
4293**
4294** (1) The real finder-function named "FImpt()".
4295**
dane946c392009-08-22 11:39:46 +00004296** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004297**
4298**
4299** A pointer to the F pointer is used as the pAppData value for VFS
4300** objects. We have to do this instead of letting pAppData point
4301** directly at the finder-function since C90 rules prevent a void*
4302** from be cast into a function pointer.
4303**
drh6b9d6dd2008-12-03 19:34:47 +00004304**
drh7708e972008-11-29 00:56:52 +00004305** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004306**
drh7708e972008-11-29 00:56:52 +00004307** * A constant sqlite3_io_methods object call METHOD that has locking
4308** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4309**
4310** * An I/O method finder function called FINDER that returns a pointer
4311** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004312*/
drhd9e5c4f2010-05-12 18:01:39 +00004313#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004314static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004315 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004316 CLOSE, /* xClose */ \
4317 unixRead, /* xRead */ \
4318 unixWrite, /* xWrite */ \
4319 unixTruncate, /* xTruncate */ \
4320 unixSync, /* xSync */ \
4321 unixFileSize, /* xFileSize */ \
4322 LOCK, /* xLock */ \
4323 UNLOCK, /* xUnlock */ \
4324 CKLOCK, /* xCheckReservedLock */ \
4325 unixFileControl, /* xFileControl */ \
4326 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004327 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004328 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004329 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004330 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004331 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004332}; \
drh0c2694b2009-09-03 16:23:44 +00004333static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4334 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004335 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004336} \
drh0c2694b2009-09-03 16:23:44 +00004337static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004338 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004339
4340/*
4341** Here are all of the sqlite3_io_methods objects for each of the
4342** locking strategies. Functions that return pointers to these methods
4343** are also created.
4344*/
4345IOMETHODS(
4346 posixIoFinder, /* Finder function name */
4347 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004348 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004349 unixClose, /* xClose method */
4350 unixLock, /* xLock method */
4351 unixUnlock, /* xUnlock method */
4352 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004353)
drh7708e972008-11-29 00:56:52 +00004354IOMETHODS(
4355 nolockIoFinder, /* Finder function name */
4356 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004357 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004358 nolockClose, /* xClose method */
4359 nolockLock, /* xLock method */
4360 nolockUnlock, /* xUnlock method */
4361 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004362)
drh7708e972008-11-29 00:56:52 +00004363IOMETHODS(
4364 dotlockIoFinder, /* Finder function name */
4365 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004366 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004367 dotlockClose, /* xClose method */
4368 dotlockLock, /* xLock method */
4369 dotlockUnlock, /* xUnlock method */
4370 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004371)
drh7708e972008-11-29 00:56:52 +00004372
chw78a13182009-04-07 05:35:03 +00004373#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004374IOMETHODS(
4375 flockIoFinder, /* Finder function name */
4376 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004377 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004378 flockClose, /* xClose method */
4379 flockLock, /* xLock method */
4380 flockUnlock, /* xUnlock method */
4381 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004382)
drh7708e972008-11-29 00:56:52 +00004383#endif
4384
drh6c7d5c52008-11-21 20:32:33 +00004385#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004386IOMETHODS(
4387 semIoFinder, /* Finder function name */
4388 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004389 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004390 semClose, /* xClose method */
4391 semLock, /* xLock method */
4392 semUnlock, /* xUnlock method */
4393 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004394)
aswiftaebf4132008-11-21 00:10:35 +00004395#endif
drh7708e972008-11-29 00:56:52 +00004396
drhd2cb50b2009-01-09 21:41:17 +00004397#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004398IOMETHODS(
4399 afpIoFinder, /* Finder function name */
4400 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004401 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004402 afpClose, /* xClose method */
4403 afpLock, /* xLock method */
4404 afpUnlock, /* xUnlock method */
4405 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004406)
drh715ff302008-12-03 22:32:44 +00004407#endif
4408
4409/*
4410** The proxy locking method is a "super-method" in the sense that it
4411** opens secondary file descriptors for the conch and lock files and
4412** it uses proxy, dot-file, AFP, and flock() locking methods on those
4413** secondary files. For this reason, the division that implements
4414** proxy locking is located much further down in the file. But we need
4415** to go ahead and define the sqlite3_io_methods and finder function
4416** for proxy locking here. So we forward declare the I/O methods.
4417*/
drhd2cb50b2009-01-09 21:41:17 +00004418#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004419static int proxyClose(sqlite3_file*);
4420static int proxyLock(sqlite3_file*, int);
4421static int proxyUnlock(sqlite3_file*, int);
4422static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004423IOMETHODS(
4424 proxyIoFinder, /* Finder function name */
4425 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004426 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004427 proxyClose, /* xClose method */
4428 proxyLock, /* xLock method */
4429 proxyUnlock, /* xUnlock method */
4430 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004431)
aswiftaebf4132008-11-21 00:10:35 +00004432#endif
drh7708e972008-11-29 00:56:52 +00004433
drh7ed97b92010-01-20 13:07:21 +00004434/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4435#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4436IOMETHODS(
4437 nfsIoFinder, /* Finder function name */
4438 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004439 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004440 unixClose, /* xClose method */
4441 unixLock, /* xLock method */
4442 nfsUnlock, /* xUnlock method */
4443 unixCheckReservedLock /* xCheckReservedLock method */
4444)
4445#endif
drh7708e972008-11-29 00:56:52 +00004446
drhd2cb50b2009-01-09 21:41:17 +00004447#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004448/*
drh6b9d6dd2008-12-03 19:34:47 +00004449** This "finder" function attempts to determine the best locking strategy
4450** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004451** object that implements that strategy.
4452**
4453** This is for MacOSX only.
4454*/
drh1875f7a2008-12-08 18:19:17 +00004455static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004456 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004457 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004458){
4459 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004460 const char *zFilesystem; /* Filesystem type name */
4461 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004462 } aMap[] = {
4463 { "hfs", &posixIoMethods },
4464 { "ufs", &posixIoMethods },
4465 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004466 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004467 { "webdav", &nolockIoMethods },
4468 { 0, 0 }
4469 };
4470 int i;
4471 struct statfs fsInfo;
4472 struct flock lockInfo;
4473
4474 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004475 /* If filePath==NULL that means we are dealing with a transient file
4476 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004477 return &nolockIoMethods;
4478 }
4479 if( statfs(filePath, &fsInfo) != -1 ){
4480 if( fsInfo.f_flags & MNT_RDONLY ){
4481 return &nolockIoMethods;
4482 }
4483 for(i=0; aMap[i].zFilesystem; i++){
4484 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4485 return aMap[i].pMethods;
4486 }
4487 }
4488 }
4489
4490 /* Default case. Handles, amongst others, "nfs".
4491 ** Test byte-range lock using fcntl(). If the call succeeds,
4492 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004493 */
drh7708e972008-11-29 00:56:52 +00004494 lockInfo.l_len = 1;
4495 lockInfo.l_start = 0;
4496 lockInfo.l_whence = SEEK_SET;
4497 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004498 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004499 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4500 return &nfsIoMethods;
4501 } else {
4502 return &posixIoMethods;
4503 }
drh7708e972008-11-29 00:56:52 +00004504 }else{
4505 return &dotlockIoMethods;
4506 }
4507}
drh0c2694b2009-09-03 16:23:44 +00004508static const sqlite3_io_methods
4509 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004510
drhd2cb50b2009-01-09 21:41:17 +00004511#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004512
chw78a13182009-04-07 05:35:03 +00004513#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4514/*
4515** This "finder" function attempts to determine the best locking strategy
4516** for the database file "filePath". It then returns the sqlite3_io_methods
4517** object that implements that strategy.
4518**
4519** This is for VXWorks only.
4520*/
4521static const sqlite3_io_methods *autolockIoFinderImpl(
4522 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004523 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004524){
4525 struct flock lockInfo;
4526
4527 if( !filePath ){
4528 /* If filePath==NULL that means we are dealing with a transient file
4529 ** that does not need to be locked. */
4530 return &nolockIoMethods;
4531 }
4532
4533 /* Test if fcntl() is supported and use POSIX style locks.
4534 ** Otherwise fall back to the named semaphore method.
4535 */
4536 lockInfo.l_len = 1;
4537 lockInfo.l_start = 0;
4538 lockInfo.l_whence = SEEK_SET;
4539 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004540 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004541 return &posixIoMethods;
4542 }else{
4543 return &semIoMethods;
4544 }
4545}
drh0c2694b2009-09-03 16:23:44 +00004546static const sqlite3_io_methods
4547 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004548
4549#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4550
drh7708e972008-11-29 00:56:52 +00004551/*
4552** An abstract type for a pointer to a IO method finder function:
4553*/
drh0c2694b2009-09-03 16:23:44 +00004554typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004555
aswiftaebf4132008-11-21 00:10:35 +00004556
drh734c9862008-11-28 15:37:20 +00004557/****************************************************************************
4558**************************** sqlite3_vfs methods ****************************
4559**
4560** This division contains the implementation of methods on the
4561** sqlite3_vfs object.
4562*/
4563
danielk1977a3d4c882007-03-23 10:08:38 +00004564/*
danielk1977e339d652008-06-28 11:23:00 +00004565** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004566*/
4567static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004568 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004569 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004570 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004571 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004572 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004573){
drh7708e972008-11-29 00:56:52 +00004574 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004575 unixFile *pNew = (unixFile *)pId;
4576 int rc = SQLITE_OK;
4577
drh8af6c222010-05-14 12:43:01 +00004578 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004579
dan00157392010-10-05 11:33:15 +00004580 /* Usually the path zFilename should not be a relative pathname. The
4581 ** exception is when opening the proxy "conch" file in builds that
4582 ** include the special Apple locking styles.
4583 */
dan00157392010-10-05 11:33:15 +00004584#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004585 assert( zFilename==0 || zFilename[0]=='/'
4586 || pVfs->pAppData==(void*)&autolockIoFinder );
4587#else
4588 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004589#endif
dan00157392010-10-05 11:33:15 +00004590
drhb07028f2011-10-14 21:49:18 +00004591 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004592 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004593
drh308c2a52010-05-14 11:30:18 +00004594 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004595 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004596 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004597 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004598 pNew->ctrlFlags = (u8)ctrlFlags;
4599 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4600 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004601 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004602 }
drha7e61d82011-03-12 17:02:57 +00004603 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004604 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004605 }
drh339eb0b2008-03-07 15:34:11 +00004606
drh6c7d5c52008-11-21 20:32:33 +00004607#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004608 pNew->pId = vxworksFindFileId(zFilename);
4609 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004610 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004611 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004612 }
4613#endif
4614
drhc02a43a2012-01-10 23:18:38 +00004615 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004616 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004617 }else{
drh0c2694b2009-09-03 16:23:44 +00004618 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004619#if SQLITE_ENABLE_LOCKING_STYLE
4620 /* Cache zFilename in the locking context (AFP and dotlock override) for
4621 ** proxyLock activation is possible (remote proxy is based on db name)
4622 ** zFilename remains valid until file is closed, to support */
4623 pNew->lockingContext = (void*)zFilename;
4624#endif
drhda0e7682008-07-30 15:27:54 +00004625 }
danielk1977e339d652008-06-28 11:23:00 +00004626
drh7ed97b92010-01-20 13:07:21 +00004627 if( pLockingStyle == &posixIoMethods
4628#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4629 || pLockingStyle == &nfsIoMethods
4630#endif
4631 ){
drh7708e972008-11-29 00:56:52 +00004632 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004633 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004634 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004635 /* If an error occured in findInodeInfo(), close the file descriptor
4636 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004637 ** in two scenarios:
4638 **
4639 ** (a) A call to fstat() failed.
4640 ** (b) A malloc failed.
4641 **
4642 ** Scenario (b) may only occur if the process is holding no other
4643 ** file descriptors open on the same file. If there were other file
4644 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004645 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004646 ** handle h - as it is guaranteed that no posix locks will be released
4647 ** by doing so.
4648 **
4649 ** If scenario (a) caused the error then things are not so safe. The
4650 ** implicit assumption here is that if fstat() fails, things are in
4651 ** such bad shape that dropping a lock or two doesn't matter much.
4652 */
drh0e9365c2011-03-02 02:08:13 +00004653 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004654 h = -1;
4655 }
drh7708e972008-11-29 00:56:52 +00004656 unixLeaveMutex();
4657 }
danielk1977e339d652008-06-28 11:23:00 +00004658
drhd2cb50b2009-01-09 21:41:17 +00004659#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004660 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004661 /* AFP locking uses the file path so it needs to be included in
4662 ** the afpLockingContext.
4663 */
4664 afpLockingContext *pCtx;
4665 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4666 if( pCtx==0 ){
4667 rc = SQLITE_NOMEM;
4668 }else{
4669 /* NB: zFilename exists and remains valid until the file is closed
4670 ** according to requirement F11141. So we do not need to make a
4671 ** copy of the filename. */
4672 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004673 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004674 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004675 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004676 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004677 if( rc!=SQLITE_OK ){
4678 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004679 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004680 h = -1;
4681 }
drh7708e972008-11-29 00:56:52 +00004682 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004683 }
drh7708e972008-11-29 00:56:52 +00004684 }
4685#endif
danielk1977e339d652008-06-28 11:23:00 +00004686
drh7708e972008-11-29 00:56:52 +00004687 else if( pLockingStyle == &dotlockIoMethods ){
4688 /* Dotfile locking uses the file path so it needs to be included in
4689 ** the dotlockLockingContext
4690 */
4691 char *zLockFile;
4692 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004693 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004694 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004695 zLockFile = (char *)sqlite3_malloc(nFilename);
4696 if( zLockFile==0 ){
4697 rc = SQLITE_NOMEM;
4698 }else{
4699 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004700 }
drh7708e972008-11-29 00:56:52 +00004701 pNew->lockingContext = zLockFile;
4702 }
danielk1977e339d652008-06-28 11:23:00 +00004703
drh6c7d5c52008-11-21 20:32:33 +00004704#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004705 else if( pLockingStyle == &semIoMethods ){
4706 /* Named semaphore locking uses the file path so it needs to be
4707 ** included in the semLockingContext
4708 */
4709 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004710 rc = findInodeInfo(pNew, &pNew->pInode);
4711 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4712 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004713 int n;
drh2238dcc2009-08-27 17:56:20 +00004714 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004715 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004716 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004717 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004718 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4719 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004720 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004721 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004722 }
chw97185482008-11-17 08:05:31 +00004723 }
drh7708e972008-11-29 00:56:52 +00004724 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004725 }
drh7708e972008-11-29 00:56:52 +00004726#endif
aswift5b1a2562008-08-22 00:22:35 +00004727
4728 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004729#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004730 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004731 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004732 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004733 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004734 isDelete = 0;
4735 }
drhc02a43a2012-01-10 23:18:38 +00004736 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004737#endif
danielk1977e339d652008-06-28 11:23:00 +00004738 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004739 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004740 }else{
drh7708e972008-11-29 00:56:52 +00004741 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004742 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004743 }
danielk1977e339d652008-06-28 11:23:00 +00004744 return rc;
drh054889e2005-11-30 03:20:31 +00004745}
drh9c06c952005-11-26 00:25:00 +00004746
danielk1977ad94b582007-08-20 06:44:22 +00004747/*
drh8b3cf822010-06-01 21:02:51 +00004748** Return the name of a directory in which to put temporary files.
4749** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004750*/
drh7234c6d2010-06-19 15:10:09 +00004751static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004752 static const char *azDirs[] = {
4753 0,
aswiftaebf4132008-11-21 00:10:35 +00004754 0,
danielk197717b90b52008-06-06 11:11:25 +00004755 "/var/tmp",
4756 "/usr/tmp",
4757 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004758 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004759 };
drh8b3cf822010-06-01 21:02:51 +00004760 unsigned int i;
4761 struct stat buf;
4762 const char *zDir = 0;
4763
4764 azDirs[0] = sqlite3_temp_directory;
4765 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004766 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004767 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004768 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004769 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004770 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004771 break;
4772 }
4773 return zDir;
4774}
4775
4776/*
4777** Create a temporary file name in zBuf. zBuf must be allocated
4778** by the calling process and must be big enough to hold at least
4779** pVfs->mxPathname bytes.
4780*/
4781static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004782 static const unsigned char zChars[] =
4783 "abcdefghijklmnopqrstuvwxyz"
4784 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4785 "0123456789";
drh41022642008-11-21 00:24:42 +00004786 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004787 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004788
4789 /* It's odd to simulate an io-error here, but really this is just
4790 ** using the io-error infrastructure to test that SQLite handles this
4791 ** function failing.
4792 */
4793 SimulateIOError( return SQLITE_IOERR );
4794
drh7234c6d2010-06-19 15:10:09 +00004795 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004796 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004797
4798 /* Check that the output buffer is large enough for the temporary file
4799 ** name. If it is not, return SQLITE_ERROR.
4800 */
drhc02a43a2012-01-10 23:18:38 +00004801 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004802 return SQLITE_ERROR;
4803 }
4804
4805 do{
drhc02a43a2012-01-10 23:18:38 +00004806 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004807 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004808 sqlite3_randomness(15, &zBuf[j]);
4809 for(i=0; i<15; i++, j++){
4810 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4811 }
4812 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004813 zBuf[j+1] = 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() */
drhac7c3ac2012-02-11 19:23:48 +00004911 mode_t *pMode, /* OUT: Permissions to open file with */
4912 uid_t *pUid, /* OUT: uid to set on the file */
4913 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00004914){
4915 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004916 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drhac7c3ac2012-02-11 19:23:48 +00004917 *pUid = 0;
4918 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00004919 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004920 char zDb[MAX_PATHNAME+1]; /* Database file path */
4921 int nDb; /* Number of valid bytes in zDb */
4922 struct stat sStat; /* Output of stat() on database file */
4923
dana0c989d2010-11-05 18:07:37 +00004924 /* zPath is a path to a WAL or journal file. The following block derives
4925 ** the path to the associated database file from zPath. This block handles
4926 ** the following naming conventions:
4927 **
4928 ** "<path to db>-journal"
4929 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004930 ** "<path to db>-journalNN"
4931 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004932 **
drhd337c5b2011-10-20 18:23:35 +00004933 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004934 ** used by the test_multiplex.c module.
4935 */
4936 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004937#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004938 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004939 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004940#else
4941 while( zPath[nDb]!='-' ){
4942 assert( nDb>0 );
4943 assert( zPath[nDb]!='\n' );
4944 nDb--;
4945 }
4946#endif
danddb0ac42010-07-14 14:48:58 +00004947 memcpy(zDb, zPath, nDb);
4948 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004949
drh58384f12011-07-28 00:14:45 +00004950 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004951 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00004952 *pUid = sStat.st_uid;
4953 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00004954 }else{
4955 rc = SQLITE_IOERR_FSTAT;
4956 }
4957 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4958 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004959 }
4960 return rc;
4961}
4962
4963/*
danielk1977ad94b582007-08-20 06:44:22 +00004964** Open the file zPath.
4965**
danielk1977b4b47412007-08-17 15:53:36 +00004966** Previously, the SQLite OS layer used three functions in place of this
4967** one:
4968**
4969** sqlite3OsOpenReadWrite();
4970** sqlite3OsOpenReadOnly();
4971** sqlite3OsOpenExclusive();
4972**
4973** These calls correspond to the following combinations of flags:
4974**
4975** ReadWrite() -> (READWRITE | CREATE)
4976** ReadOnly() -> (READONLY)
4977** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4978**
4979** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4980** true, the file was configured to be automatically deleted when the
4981** file handle closed. To achieve the same effect using this new
4982** interface, add the DELETEONCLOSE flag to those specified above for
4983** OpenExclusive().
4984*/
4985static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004986 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4987 const char *zPath, /* Pathname of file to be opened */
4988 sqlite3_file *pFile, /* The file descriptor to be filled in */
4989 int flags, /* Input flags to control the opening */
4990 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004991){
dan08da86a2009-08-21 17:18:03 +00004992 unixFile *p = (unixFile *)pFile;
4993 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004994 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004995 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004996 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00004997 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00004998 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00004999
5000 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5001 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5002 int isCreate = (flags & SQLITE_OPEN_CREATE);
5003 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5004 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005005#if SQLITE_ENABLE_LOCKING_STYLE
5006 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5007#endif
drh3d4435b2011-08-26 20:55:50 +00005008#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5009 struct statfs fsInfo;
5010#endif
danielk1977b4b47412007-08-17 15:53:36 +00005011
danielk1977fee2d252007-08-18 10:59:19 +00005012 /* If creating a master or main-file journal, this function will open
5013 ** a file-descriptor on the directory too. The first time unixSync()
5014 ** is called the directory file descriptor will be fsync()ed and close()d.
5015 */
drh0059eae2011-08-08 23:48:40 +00005016 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005017 eType==SQLITE_OPEN_MASTER_JOURNAL
5018 || eType==SQLITE_OPEN_MAIN_JOURNAL
5019 || eType==SQLITE_OPEN_WAL
5020 ));
danielk1977fee2d252007-08-18 10:59:19 +00005021
danielk197717b90b52008-06-06 11:11:25 +00005022 /* If argument zPath is a NULL pointer, this function is required to open
5023 ** a temporary file. Use this buffer to store the file name in.
5024 */
drhc02a43a2012-01-10 23:18:38 +00005025 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005026 const char *zName = zPath;
5027
danielk1977fee2d252007-08-18 10:59:19 +00005028 /* Check the following statements are true:
5029 **
5030 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5031 ** (b) if CREATE is set, then READWRITE must also be set, and
5032 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005033 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005034 */
danielk1977b4b47412007-08-17 15:53:36 +00005035 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005036 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005037 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005038 assert(isDelete==0 || isCreate);
5039
danddb0ac42010-07-14 14:48:58 +00005040 /* The main DB, main journal, WAL file and master journal are never
5041 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005042 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5043 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5044 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005045 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005046
danielk1977fee2d252007-08-18 10:59:19 +00005047 /* Assert that the upper layer has set one of the "file-type" flags. */
5048 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5049 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5050 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005051 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005052 );
5053
dan08da86a2009-08-21 17:18:03 +00005054 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005055
dan08da86a2009-08-21 17:18:03 +00005056 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005057 UnixUnusedFd *pUnused;
5058 pUnused = findReusableFd(zName, flags);
5059 if( pUnused ){
5060 fd = pUnused->fd;
5061 }else{
dan6aa657f2009-08-24 18:57:58 +00005062 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005063 if( !pUnused ){
5064 return SQLITE_NOMEM;
5065 }
5066 }
5067 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005068
5069 /* Database filenames are double-zero terminated if they are not
5070 ** URIs with parameters. Hence, they can always be passed into
5071 ** sqlite3_uri_parameter(). */
5072 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5073
dan08da86a2009-08-21 17:18:03 +00005074 }else if( !zName ){
5075 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005076 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005077 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005078 if( rc!=SQLITE_OK ){
5079 return rc;
5080 }
5081 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005082
5083 /* Generated temporary filenames are always double-zero terminated
5084 ** for use by sqlite3_uri_parameter(). */
5085 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005086 }
5087
dan08da86a2009-08-21 17:18:03 +00005088 /* Determine the value of the flags parameter passed to POSIX function
5089 ** open(). These must be calculated even if open() is not called, as
5090 ** they may be stored as part of the file handle and used by the
5091 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005092 if( isReadonly ) openFlags |= O_RDONLY;
5093 if( isReadWrite ) openFlags |= O_RDWR;
5094 if( isCreate ) openFlags |= O_CREAT;
5095 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5096 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005097
danielk1977b4b47412007-08-17 15:53:36 +00005098 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005099 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005100 uid_t uid; /* Userid for the file */
5101 gid_t gid; /* Groupid for the file */
5102 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005103 if( rc!=SQLITE_OK ){
5104 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005105 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005106 return rc;
5107 }
drhad4f1e52011-03-04 15:43:57 +00005108 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005109 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005110 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5111 /* Failed to open the file for read/write access. Try read-only. */
5112 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005113 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005114 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005115 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005116 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005117 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005118 }
5119 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005120 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005121 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005122 }
drhac7c3ac2012-02-11 19:23:48 +00005123
5124 /* If this process is running as root and if creating a new rollback
5125 ** journal or WAL file, set the ownership of the journal or WAL to be
5126 ** the same as the original database. If we are not running as root,
drh3ee34842012-02-11 21:21:17 +00005127 ** then the fchown() call will fail, but that's ok. The "if(){}" and
5128 ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
5129 ** warnings from gcc.
drhac7c3ac2012-02-11 19:23:48 +00005130 */
5131 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh3ee34842012-02-11 21:21:17 +00005132 if( fchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
drhac7c3ac2012-02-11 19:23:48 +00005133 }
danielk1977b4b47412007-08-17 15:53:36 +00005134 }
dan08da86a2009-08-21 17:18:03 +00005135 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005136 if( pOutFlags ){
5137 *pOutFlags = flags;
5138 }
5139
dane946c392009-08-22 11:39:46 +00005140 if( p->pUnused ){
5141 p->pUnused->fd = fd;
5142 p->pUnused->flags = flags;
5143 }
5144
danielk1977b4b47412007-08-17 15:53:36 +00005145 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005146#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005147 zPath = zName;
5148#else
drh036ac7f2011-08-08 23:18:05 +00005149 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005150#endif
danielk1977b4b47412007-08-17 15:53:36 +00005151 }
drh41022642008-11-21 00:24:42 +00005152#if SQLITE_ENABLE_LOCKING_STYLE
5153 else{
dan08da86a2009-08-21 17:18:03 +00005154 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005155 }
5156#endif
5157
danielk1977e339d652008-06-28 11:23:00 +00005158#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005159 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005160#endif
5161
drhda0e7682008-07-30 15:27:54 +00005162 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005163
drh7ed97b92010-01-20 13:07:21 +00005164
5165#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005166 if( fstatfs(fd, &fsInfo) == -1 ){
5167 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005168 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005169 return SQLITE_IOERR_ACCESS;
5170 }
5171 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5172 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5173 }
5174#endif
drhc02a43a2012-01-10 23:18:38 +00005175
5176 /* Set up appropriate ctrlFlags */
5177 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5178 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5179 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5180 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5181 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5182
drh7ed97b92010-01-20 13:07:21 +00005183#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005184#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005185 isAutoProxy = 1;
5186#endif
5187 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005188 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5189 int useProxy = 0;
5190
dan08da86a2009-08-21 17:18:03 +00005191 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5192 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005193 if( envforce!=NULL ){
5194 useProxy = atoi(envforce)>0;
5195 }else{
aswiftaebf4132008-11-21 00:10:35 +00005196 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005197 /* In theory, the close(fd) call is sub-optimal. If the file opened
5198 ** with fd is a database file, and there are other connections open
5199 ** on that file that are currently holding advisory locks on it,
5200 ** then the call to close() will cancel those locks. In practice,
5201 ** we're assuming that statfs() doesn't fail very often. At least
5202 ** not while other file descriptors opened by the same process on
5203 ** the same file are working. */
5204 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005205 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005206 rc = SQLITE_IOERR_ACCESS;
5207 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005208 }
5209 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5210 }
5211 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005212 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005213 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005214 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005215 if( rc!=SQLITE_OK ){
5216 /* Use unixClose to clean up the resources added in fillInUnixFile
5217 ** and clear all the structure's references. Specifically,
5218 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5219 */
5220 unixClose(pFile);
5221 return rc;
5222 }
aswiftaebf4132008-11-21 00:10:35 +00005223 }
dane946c392009-08-22 11:39:46 +00005224 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005225 }
5226 }
5227#endif
5228
drhc02a43a2012-01-10 23:18:38 +00005229 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5230
dane946c392009-08-22 11:39:46 +00005231open_finished:
5232 if( rc!=SQLITE_OK ){
5233 sqlite3_free(p->pUnused);
5234 }
5235 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005236}
5237
dane946c392009-08-22 11:39:46 +00005238
danielk1977b4b47412007-08-17 15:53:36 +00005239/*
danielk1977fee2d252007-08-18 10:59:19 +00005240** Delete the file at zPath. If the dirSync argument is true, fsync()
5241** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005242*/
drh6b9d6dd2008-12-03 19:34:47 +00005243static int unixDelete(
5244 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5245 const char *zPath, /* Name of file to be deleted */
5246 int dirSync /* If true, fsync() directory after deleting file */
5247){
danielk1977fee2d252007-08-18 10:59:19 +00005248 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005249 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005250 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005251 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005252 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005253 }
danielk1977d39fa702008-10-16 13:27:40 +00005254#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005255 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005256 int fd;
drh90315a22011-08-10 01:52:12 +00005257 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005258 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005259#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005260 if( fsync(fd)==-1 )
5261#else
5262 if( fsync(fd) )
5263#endif
5264 {
dane18d4952011-02-21 11:46:24 +00005265 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005266 }
drh0e9365c2011-03-02 02:08:13 +00005267 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005268 }else if( rc==SQLITE_CANTOPEN ){
5269 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005270 }
5271 }
danielk1977d138dd82008-10-15 16:02:48 +00005272#endif
danielk1977fee2d252007-08-18 10:59:19 +00005273 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005274}
5275
danielk197790949c22007-08-17 16:50:38 +00005276/*
5277** Test the existance of or access permissions of file zPath. The
5278** test performed depends on the value of flags:
5279**
5280** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5281** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5282** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5283**
5284** Otherwise return 0.
5285*/
danielk1977861f7452008-06-05 11:39:11 +00005286static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005287 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5288 const char *zPath, /* Path of the file to examine */
5289 int flags, /* What do we want to learn about the zPath file? */
5290 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005291){
rse25c0d1a2007-09-20 08:38:14 +00005292 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005293 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005294 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005295 switch( flags ){
5296 case SQLITE_ACCESS_EXISTS:
5297 amode = F_OK;
5298 break;
5299 case SQLITE_ACCESS_READWRITE:
5300 amode = W_OK|R_OK;
5301 break;
drh50d3f902007-08-27 21:10:36 +00005302 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005303 amode = R_OK;
5304 break;
5305
5306 default:
5307 assert(!"Invalid flags argument");
5308 }
drh99ab3b12011-03-02 15:09:07 +00005309 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005310 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5311 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005312 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005313 *pResOut = 0;
5314 }
5315 }
danielk1977861f7452008-06-05 11:39:11 +00005316 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005317}
5318
danielk1977b4b47412007-08-17 15:53:36 +00005319
5320/*
5321** Turn a relative pathname into a full pathname. The relative path
5322** is stored as a nul-terminated string in the buffer pointed to by
5323** zPath.
5324**
5325** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5326** (in this case, MAX_PATHNAME bytes). The full-path is written to
5327** this buffer before returning.
5328*/
danielk1977adfb9b02007-09-17 07:02:56 +00005329static int unixFullPathname(
5330 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5331 const char *zPath, /* Possibly relative input path */
5332 int nOut, /* Size of output buffer in bytes */
5333 char *zOut /* Output buffer */
5334){
danielk1977843e65f2007-09-01 16:16:15 +00005335
5336 /* It's odd to simulate an io-error here, but really this is just
5337 ** using the io-error infrastructure to test that SQLite handles this
5338 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005339 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005340 */
5341 SimulateIOError( return SQLITE_ERROR );
5342
drh153c62c2007-08-24 03:51:33 +00005343 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005344 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005345
drh3c7f2dc2007-12-06 13:26:20 +00005346 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005347 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005348 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005349 }else{
5350 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005351 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005352 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005353 }
drhea678832008-12-10 19:26:22 +00005354 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005355 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005356 }
5357 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005358}
5359
drh0ccebe72005-06-07 22:22:50 +00005360
drh761df872006-12-21 01:29:22 +00005361#ifndef SQLITE_OMIT_LOAD_EXTENSION
5362/*
5363** Interfaces for opening a shared library, finding entry points
5364** within the shared library, and closing the shared library.
5365*/
5366#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005367static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5368 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005369 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5370}
danielk197795c8a542007-09-01 06:51:27 +00005371
5372/*
5373** SQLite calls this function immediately after a call to unixDlSym() or
5374** unixDlOpen() fails (returns a null pointer). If a more detailed error
5375** message is available, it is written to zBufOut. If no error message
5376** is available, zBufOut is left unmodified and SQLite uses a default
5377** error message.
5378*/
danielk1977397d65f2008-11-19 11:35:39 +00005379static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005380 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005381 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005382 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005383 zErr = dlerror();
5384 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005385 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005386 }
drh6c7d5c52008-11-21 20:32:33 +00005387 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005388}
drh1875f7a2008-12-08 18:19:17 +00005389static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5390 /*
5391 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5392 ** cast into a pointer to a function. And yet the library dlsym() routine
5393 ** returns a void* which is really a pointer to a function. So how do we
5394 ** use dlsym() with -pedantic-errors?
5395 **
5396 ** Variable x below is defined to be a pointer to a function taking
5397 ** parameters void* and const char* and returning a pointer to a function.
5398 ** We initialize x by assigning it a pointer to the dlsym() function.
5399 ** (That assignment requires a cast.) Then we call the function that
5400 ** x points to.
5401 **
5402 ** This work-around is unlikely to work correctly on any system where
5403 ** you really cannot cast a function pointer into void*. But then, on the
5404 ** other hand, dlsym() will not work on such a system either, so we have
5405 ** not really lost anything.
5406 */
5407 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005408 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005409 x = (void(*(*)(void*,const char*))(void))dlsym;
5410 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005411}
danielk1977397d65f2008-11-19 11:35:39 +00005412static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5413 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005414 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005415}
danielk1977b4b47412007-08-17 15:53:36 +00005416#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5417 #define unixDlOpen 0
5418 #define unixDlError 0
5419 #define unixDlSym 0
5420 #define unixDlClose 0
5421#endif
5422
5423/*
danielk197790949c22007-08-17 16:50:38 +00005424** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005425*/
danielk1977397d65f2008-11-19 11:35:39 +00005426static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5427 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005428 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005429
drhbbd42a62004-05-22 17:41:58 +00005430 /* We have to initialize zBuf to prevent valgrind from reporting
5431 ** errors. The reports issued by valgrind are incorrect - we would
5432 ** prefer that the randomness be increased by making use of the
5433 ** uninitialized space in zBuf - but valgrind errors tend to worry
5434 ** some users. Rather than argue, it seems easier just to initialize
5435 ** the whole array and silence valgrind, even if that means less randomness
5436 ** in the random seed.
5437 **
5438 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005439 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005440 ** tests repeatable.
5441 */
danielk1977b4b47412007-08-17 15:53:36 +00005442 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005443#if !defined(SQLITE_TEST)
5444 {
drhc18b4042012-02-10 03:10:27 +00005445 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005446 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005447 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005448 time_t t;
5449 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005450 memcpy(zBuf, &t, sizeof(t));
5451 pid = getpid();
5452 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005453 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005454 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005455 }else{
drhc18b4042012-02-10 03:10:27 +00005456 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005457 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005458 }
drhbbd42a62004-05-22 17:41:58 +00005459 }
5460#endif
drh72cbd072008-10-14 17:58:38 +00005461 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005462}
5463
danielk1977b4b47412007-08-17 15:53:36 +00005464
drhbbd42a62004-05-22 17:41:58 +00005465/*
5466** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005467** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005468** The return value is the number of microseconds of sleep actually
5469** requested from the underlying operating system, a number which
5470** might be greater than or equal to the argument, but not less
5471** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005472*/
danielk1977397d65f2008-11-19 11:35:39 +00005473static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005474#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005475 struct timespec sp;
5476
5477 sp.tv_sec = microseconds / 1000000;
5478 sp.tv_nsec = (microseconds % 1000000) * 1000;
5479 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005480 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005481 return microseconds;
5482#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005483 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005484 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005485 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005486#else
danielk1977b4b47412007-08-17 15:53:36 +00005487 int seconds = (microseconds+999999)/1000000;
5488 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005489 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005490 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005491#endif
drh88f474a2006-01-02 20:00:12 +00005492}
5493
5494/*
drh6b9d6dd2008-12-03 19:34:47 +00005495** The following variable, if set to a non-zero value, is interpreted as
5496** the number of seconds since 1970 and is used to set the result of
5497** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005498*/
5499#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005500int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005501#endif
5502
5503/*
drhb7e8ea22010-05-03 14:32:30 +00005504** Find the current time (in Universal Coordinated Time). Write into *piNow
5505** the current time and date as a Julian Day number times 86_400_000. In
5506** other words, write into *piNow the number of milliseconds since the Julian
5507** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5508** proleptic Gregorian calendar.
5509**
drh31702252011-10-12 23:13:43 +00005510** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5511** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005512*/
5513static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5514 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005515 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005516#if defined(NO_GETTOD)
5517 time_t t;
5518 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005519 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005520#elif OS_VXWORKS
5521 struct timespec sNow;
5522 clock_gettime(CLOCK_REALTIME, &sNow);
5523 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5524#else
5525 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005526 if( gettimeofday(&sNow, 0)==0 ){
5527 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5528 }else{
5529 rc = SQLITE_ERROR;
5530 }
drhb7e8ea22010-05-03 14:32:30 +00005531#endif
5532
5533#ifdef SQLITE_TEST
5534 if( sqlite3_current_time ){
5535 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5536 }
5537#endif
5538 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005539 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005540}
5541
5542/*
drhbbd42a62004-05-22 17:41:58 +00005543** Find the current time (in Universal Coordinated Time). Write the
5544** current time and date as a Julian Day number into *prNow and
5545** return 0. Return 1 if the time and date cannot be found.
5546*/
danielk1977397d65f2008-11-19 11:35:39 +00005547static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005548 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005549 int rc;
drhff828942010-06-26 21:34:06 +00005550 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005551 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005552 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005553 return rc;
drhbbd42a62004-05-22 17:41:58 +00005554}
danielk1977b4b47412007-08-17 15:53:36 +00005555
drh6b9d6dd2008-12-03 19:34:47 +00005556/*
5557** We added the xGetLastError() method with the intention of providing
5558** better low-level error messages when operating-system problems come up
5559** during SQLite operation. But so far, none of that has been implemented
5560** in the core. So this routine is never called. For now, it is merely
5561** a place-holder.
5562*/
danielk1977397d65f2008-11-19 11:35:39 +00005563static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5564 UNUSED_PARAMETER(NotUsed);
5565 UNUSED_PARAMETER(NotUsed2);
5566 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005567 return 0;
5568}
5569
drhf2424c52010-04-26 00:04:55 +00005570
5571/*
drh734c9862008-11-28 15:37:20 +00005572************************ End of sqlite3_vfs methods ***************************
5573******************************************************************************/
5574
drh715ff302008-12-03 22:32:44 +00005575/******************************************************************************
5576************************** Begin Proxy Locking ********************************
5577**
5578** Proxy locking is a "uber-locking-method" in this sense: It uses the
5579** other locking methods on secondary lock files. Proxy locking is a
5580** meta-layer over top of the primitive locking implemented above. For
5581** this reason, the division that implements of proxy locking is deferred
5582** until late in the file (here) after all of the other I/O methods have
5583** been defined - so that the primitive locking methods are available
5584** as services to help with the implementation of proxy locking.
5585**
5586****
5587**
5588** The default locking schemes in SQLite use byte-range locks on the
5589** database file to coordinate safe, concurrent access by multiple readers
5590** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5591** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5592** as POSIX read & write locks over fixed set of locations (via fsctl),
5593** on AFP and SMB only exclusive byte-range locks are available via fsctl
5594** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5595** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5596** address in the shared range is taken for a SHARED lock, the entire
5597** shared range is taken for an EXCLUSIVE lock):
5598**
5599** PENDING_BYTE 0x40000000
5600** RESERVED_BYTE 0x40000001
5601** SHARED_RANGE 0x40000002 -> 0x40000200
5602**
5603** This works well on the local file system, but shows a nearly 100x
5604** slowdown in read performance on AFP because the AFP client disables
5605** the read cache when byte-range locks are present. Enabling the read
5606** cache exposes a cache coherency problem that is present on all OS X
5607** supported network file systems. NFS and AFP both observe the
5608** close-to-open semantics for ensuring cache coherency
5609** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5610** address the requirements for concurrent database access by multiple
5611** readers and writers
5612** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5613**
5614** To address the performance and cache coherency issues, proxy file locking
5615** changes the way database access is controlled by limiting access to a
5616** single host at a time and moving file locks off of the database file
5617** and onto a proxy file on the local file system.
5618**
5619**
5620** Using proxy locks
5621** -----------------
5622**
5623** C APIs
5624**
5625** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5626** <proxy_path> | ":auto:");
5627** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5628**
5629**
5630** SQL pragmas
5631**
5632** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5633** PRAGMA [database.]lock_proxy_file
5634**
5635** Specifying ":auto:" means that if there is a conch file with a matching
5636** host ID in it, the proxy path in the conch file will be used, otherwise
5637** a proxy path based on the user's temp dir
5638** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5639** actual proxy file name is generated from the name and path of the
5640** database file. For example:
5641**
5642** For database path "/Users/me/foo.db"
5643** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5644**
5645** Once a lock proxy is configured for a database connection, it can not
5646** be removed, however it may be switched to a different proxy path via
5647** the above APIs (assuming the conch file is not being held by another
5648** connection or process).
5649**
5650**
5651** How proxy locking works
5652** -----------------------
5653**
5654** Proxy file locking relies primarily on two new supporting files:
5655**
5656** * conch file to limit access to the database file to a single host
5657** at a time
5658**
5659** * proxy file to act as a proxy for the advisory locks normally
5660** taken on the database
5661**
5662** The conch file - to use a proxy file, sqlite must first "hold the conch"
5663** by taking an sqlite-style shared lock on the conch file, reading the
5664** contents and comparing the host's unique host ID (see below) and lock
5665** proxy path against the values stored in the conch. The conch file is
5666** stored in the same directory as the database file and the file name
5667** is patterned after the database file name as ".<databasename>-conch".
5668** If the conch file does not exist, or it's contents do not match the
5669** host ID and/or proxy path, then the lock is escalated to an exclusive
5670** lock and the conch file contents is updated with the host ID and proxy
5671** path and the lock is downgraded to a shared lock again. If the conch
5672** is held by another process (with a shared lock), the exclusive lock
5673** will fail and SQLITE_BUSY is returned.
5674**
5675** The proxy file - a single-byte file used for all advisory file locks
5676** normally taken on the database file. This allows for safe sharing
5677** of the database file for multiple readers and writers on the same
5678** host (the conch ensures that they all use the same local lock file).
5679**
drh715ff302008-12-03 22:32:44 +00005680** Requesting the lock proxy does not immediately take the conch, it is
5681** only taken when the first request to lock database file is made.
5682** This matches the semantics of the traditional locking behavior, where
5683** opening a connection to a database file does not take a lock on it.
5684** The shared lock and an open file descriptor are maintained until
5685** the connection to the database is closed.
5686**
5687** The proxy file and the lock file are never deleted so they only need
5688** to be created the first time they are used.
5689**
5690** Configuration options
5691** ---------------------
5692**
5693** SQLITE_PREFER_PROXY_LOCKING
5694**
5695** Database files accessed on non-local file systems are
5696** automatically configured for proxy locking, lock files are
5697** named automatically using the same logic as
5698** PRAGMA lock_proxy_file=":auto:"
5699**
5700** SQLITE_PROXY_DEBUG
5701**
5702** Enables the logging of error messages during host id file
5703** retrieval and creation
5704**
drh715ff302008-12-03 22:32:44 +00005705** LOCKPROXYDIR
5706**
5707** Overrides the default directory used for lock proxy files that
5708** are named automatically via the ":auto:" setting
5709**
5710** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5711**
5712** Permissions to use when creating a directory for storing the
5713** lock proxy files, only used when LOCKPROXYDIR is not set.
5714**
5715**
5716** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5717** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5718** force proxy locking to be used for every database file opened, and 0
5719** will force automatic proxy locking to be disabled for all database
5720** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5721** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5722*/
5723
5724/*
5725** Proxy locking is only available on MacOSX
5726*/
drhd2cb50b2009-01-09 21:41:17 +00005727#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005728
drh715ff302008-12-03 22:32:44 +00005729/*
5730** The proxyLockingContext has the path and file structures for the remote
5731** and local proxy files in it
5732*/
5733typedef struct proxyLockingContext proxyLockingContext;
5734struct proxyLockingContext {
5735 unixFile *conchFile; /* Open conch file */
5736 char *conchFilePath; /* Name of the conch file */
5737 unixFile *lockProxy; /* Open proxy lock file */
5738 char *lockProxyPath; /* Name of the proxy lock file */
5739 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005740 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005741 void *oldLockingContext; /* Original lockingcontext to restore on close */
5742 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5743};
5744
drh7ed97b92010-01-20 13:07:21 +00005745/*
5746** The proxy lock file path for the database at dbPath is written into lPath,
5747** which must point to valid, writable memory large enough for a maxLen length
5748** file path.
drh715ff302008-12-03 22:32:44 +00005749*/
drh715ff302008-12-03 22:32:44 +00005750static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5751 int len;
5752 int dbLen;
5753 int i;
5754
5755#ifdef LOCKPROXYDIR
5756 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5757#else
5758# ifdef _CS_DARWIN_USER_TEMP_DIR
5759 {
drh7ed97b92010-01-20 13:07:21 +00005760 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005761 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5762 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005763 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005764 }
drh7ed97b92010-01-20 13:07:21 +00005765 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005766 }
5767# else
5768 len = strlcpy(lPath, "/tmp/", maxLen);
5769# endif
5770#endif
5771
5772 if( lPath[len-1]!='/' ){
5773 len = strlcat(lPath, "/", maxLen);
5774 }
5775
5776 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005777 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005778 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005779 char c = dbPath[i];
5780 lPath[i+len] = (c=='/')?'_':c;
5781 }
5782 lPath[i+len]='\0';
5783 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005784 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005785 return SQLITE_OK;
5786}
5787
drh7ed97b92010-01-20 13:07:21 +00005788/*
5789 ** Creates the lock file and any missing directories in lockPath
5790 */
5791static int proxyCreateLockPath(const char *lockPath){
5792 int i, len;
5793 char buf[MAXPATHLEN];
5794 int start = 0;
5795
5796 assert(lockPath!=NULL);
5797 /* try to create all the intermediate directories */
5798 len = (int)strlen(lockPath);
5799 buf[0] = lockPath[0];
5800 for( i=1; i<len; i++ ){
5801 if( lockPath[i] == '/' && (i - start > 0) ){
5802 /* only mkdir if leaf dir != "." or "/" or ".." */
5803 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5804 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5805 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005806 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005807 int err=errno;
5808 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005809 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005810 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005811 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005812 return err;
5813 }
5814 }
5815 }
5816 start=i+1;
5817 }
5818 buf[i] = lockPath[i];
5819 }
drh308c2a52010-05-14 11:30:18 +00005820 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005821 return 0;
5822}
5823
drh715ff302008-12-03 22:32:44 +00005824/*
5825** Create a new VFS file descriptor (stored in memory obtained from
5826** sqlite3_malloc) and open the file named "path" in the file descriptor.
5827**
5828** The caller is responsible not only for closing the file descriptor
5829** but also for freeing the memory associated with the file descriptor.
5830*/
drh7ed97b92010-01-20 13:07:21 +00005831static int proxyCreateUnixFile(
5832 const char *path, /* path for the new unixFile */
5833 unixFile **ppFile, /* unixFile created and returned by ref */
5834 int islockfile /* if non zero missing dirs will be created */
5835) {
5836 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005837 unixFile *pNew;
5838 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005839 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005840 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005841 int terrno = 0;
5842 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005843
drh7ed97b92010-01-20 13:07:21 +00005844 /* 1. first try to open/create the file
5845 ** 2. if that fails, and this is a lock file (not-conch), try creating
5846 ** the parent directories and then try again.
5847 ** 3. if that fails, try to open the file read-only
5848 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5849 */
5850 pUnused = findReusableFd(path, openFlags);
5851 if( pUnused ){
5852 fd = pUnused->fd;
5853 }else{
5854 pUnused = sqlite3_malloc(sizeof(*pUnused));
5855 if( !pUnused ){
5856 return SQLITE_NOMEM;
5857 }
5858 }
5859 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005860 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005861 terrno = errno;
5862 if( fd<0 && errno==ENOENT && islockfile ){
5863 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005864 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005865 }
5866 }
5867 }
5868 if( fd<0 ){
5869 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005870 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005871 terrno = errno;
5872 }
5873 if( fd<0 ){
5874 if( islockfile ){
5875 return SQLITE_BUSY;
5876 }
5877 switch (terrno) {
5878 case EACCES:
5879 return SQLITE_PERM;
5880 case EIO:
5881 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5882 default:
drh9978c972010-02-23 17:36:32 +00005883 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005884 }
5885 }
5886
5887 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5888 if( pNew==NULL ){
5889 rc = SQLITE_NOMEM;
5890 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005891 }
5892 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005893 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005894 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005895 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005896 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005897 pUnused->fd = fd;
5898 pUnused->flags = openFlags;
5899 pNew->pUnused = pUnused;
5900
drhc02a43a2012-01-10 23:18:38 +00005901 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005902 if( rc==SQLITE_OK ){
5903 *ppFile = pNew;
5904 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005905 }
drh7ed97b92010-01-20 13:07:21 +00005906end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005907 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005908 sqlite3_free(pNew);
5909 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005910 return rc;
5911}
5912
drh7ed97b92010-01-20 13:07:21 +00005913#ifdef SQLITE_TEST
5914/* simulate multiple hosts by creating unique hostid file paths */
5915int sqlite3_hostid_num = 0;
5916#endif
5917
5918#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5919
drh0ab216a2010-07-02 17:10:40 +00005920/* Not always defined in the headers as it ought to be */
5921extern int gethostuuid(uuid_t id, const struct timespec *wait);
5922
drh7ed97b92010-01-20 13:07:21 +00005923/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5924** bytes of writable memory.
5925*/
5926static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005927 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5928 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005929#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5930 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005931 {
5932 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5933 if( gethostuuid(pHostID, &timeout) ){
5934 int err = errno;
5935 if( pError ){
5936 *pError = err;
5937 }
5938 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005939 }
drh7ed97b92010-01-20 13:07:21 +00005940 }
drh3d4435b2011-08-26 20:55:50 +00005941#else
5942 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005943#endif
drh7ed97b92010-01-20 13:07:21 +00005944#ifdef SQLITE_TEST
5945 /* simulate multiple hosts by creating unique hostid file paths */
5946 if( sqlite3_hostid_num != 0){
5947 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5948 }
5949#endif
5950
5951 return SQLITE_OK;
5952}
5953
5954/* The conch file contains the header, host id and lock file path
5955 */
5956#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5957#define PROXY_HEADERLEN 1 /* conch file header length */
5958#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5959#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5960
5961/*
5962** Takes an open conch file, copies the contents to a new path and then moves
5963** it back. The newly created file's file descriptor is assigned to the
5964** conch file structure and finally the original conch file descriptor is
5965** closed. Returns zero if successful.
5966*/
5967static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5968 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5969 unixFile *conchFile = pCtx->conchFile;
5970 char tPath[MAXPATHLEN];
5971 char buf[PROXY_MAXCONCHLEN];
5972 char *cPath = pCtx->conchFilePath;
5973 size_t readLen = 0;
5974 size_t pathLen = 0;
5975 char errmsg[64] = "";
5976 int fd = -1;
5977 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005978 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005979
5980 /* create a new path by replace the trailing '-conch' with '-break' */
5981 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5982 if( pathLen>MAXPATHLEN || pathLen<6 ||
5983 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005984 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005985 goto end_breaklock;
5986 }
5987 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005988 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005989 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005990 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005991 goto end_breaklock;
5992 }
5993 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005994 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5995 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005996 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00005997 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00005998 goto end_breaklock;
5999 }
drhe562be52011-03-02 18:01:10 +00006000 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006001 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006002 goto end_breaklock;
6003 }
6004 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006005 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006006 goto end_breaklock;
6007 }
6008 rc = 0;
6009 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006010 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006011 conchFile->h = fd;
6012 conchFile->openFlags = O_RDWR | O_CREAT;
6013
6014end_breaklock:
6015 if( rc ){
6016 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006017 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006018 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006019 }
6020 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6021 }
6022 return rc;
6023}
6024
6025/* Take the requested lock on the conch file and break a stale lock if the
6026** host id matches.
6027*/
6028static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6029 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6030 unixFile *conchFile = pCtx->conchFile;
6031 int rc = SQLITE_OK;
6032 int nTries = 0;
6033 struct timespec conchModTime;
6034
drh3d4435b2011-08-26 20:55:50 +00006035 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006036 do {
6037 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6038 nTries ++;
6039 if( rc==SQLITE_BUSY ){
6040 /* If the lock failed (busy):
6041 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6042 * 2nd try: fail if the mod time changed or host id is different, wait
6043 * 10 sec and try again
6044 * 3rd try: break the lock unless the mod time has changed.
6045 */
6046 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006047 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006048 pFile->lastErrno = errno;
6049 return SQLITE_IOERR_LOCK;
6050 }
6051
6052 if( nTries==1 ){
6053 conchModTime = buf.st_mtimespec;
6054 usleep(500000); /* wait 0.5 sec and try the lock again*/
6055 continue;
6056 }
6057
6058 assert( nTries>1 );
6059 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6060 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6061 return SQLITE_BUSY;
6062 }
6063
6064 if( nTries==2 ){
6065 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006066 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006067 if( len<0 ){
6068 pFile->lastErrno = errno;
6069 return SQLITE_IOERR_LOCK;
6070 }
6071 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6072 /* don't break the lock if the host id doesn't match */
6073 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6074 return SQLITE_BUSY;
6075 }
6076 }else{
6077 /* don't break the lock on short read or a version mismatch */
6078 return SQLITE_BUSY;
6079 }
6080 usleep(10000000); /* wait 10 sec and try the lock again */
6081 continue;
6082 }
6083
6084 assert( nTries==3 );
6085 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6086 rc = SQLITE_OK;
6087 if( lockType==EXCLUSIVE_LOCK ){
6088 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6089 }
6090 if( !rc ){
6091 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6092 }
6093 }
6094 }
6095 } while( rc==SQLITE_BUSY && nTries<3 );
6096
6097 return rc;
6098}
6099
6100/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006101** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6102** lockPath means that the lockPath in the conch file will be used if the
6103** host IDs match, or a new lock path will be generated automatically
6104** and written to the conch file.
6105*/
6106static int proxyTakeConch(unixFile *pFile){
6107 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6108
drh7ed97b92010-01-20 13:07:21 +00006109 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006110 return SQLITE_OK;
6111 }else{
6112 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006113 uuid_t myHostID;
6114 int pError = 0;
6115 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006116 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006117 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006118 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006119 int createConch = 0;
6120 int hostIdMatch = 0;
6121 int readLen = 0;
6122 int tryOldLockPath = 0;
6123 int forceNewLockPath = 0;
6124
drh308c2a52010-05-14 11:30:18 +00006125 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6126 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006127
drh7ed97b92010-01-20 13:07:21 +00006128 rc = proxyGetHostID(myHostID, &pError);
6129 if( (rc&0xff)==SQLITE_IOERR ){
6130 pFile->lastErrno = pError;
6131 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006132 }
drh7ed97b92010-01-20 13:07:21 +00006133 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006134 if( rc!=SQLITE_OK ){
6135 goto end_takeconch;
6136 }
drh7ed97b92010-01-20 13:07:21 +00006137 /* read the existing conch file */
6138 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6139 if( readLen<0 ){
6140 /* I/O error: lastErrno set by seekAndRead */
6141 pFile->lastErrno = conchFile->lastErrno;
6142 rc = SQLITE_IOERR_READ;
6143 goto end_takeconch;
6144 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6145 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6146 /* a short read or version format mismatch means we need to create a new
6147 ** conch file.
6148 */
6149 createConch = 1;
6150 }
6151 /* if the host id matches and the lock path already exists in the conch
6152 ** we'll try to use the path there, if we can't open that path, we'll
6153 ** retry with a new auto-generated path
6154 */
6155 do { /* in case we need to try again for an :auto: named lock file */
6156
6157 if( !createConch && !forceNewLockPath ){
6158 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6159 PROXY_HOSTIDLEN);
6160 /* if the conch has data compare the contents */
6161 if( !pCtx->lockProxyPath ){
6162 /* for auto-named local lock file, just check the host ID and we'll
6163 ** use the local lock file path that's already in there
6164 */
6165 if( hostIdMatch ){
6166 size_t pathLen = (readLen - PROXY_PATHINDEX);
6167
6168 if( pathLen>=MAXPATHLEN ){
6169 pathLen=MAXPATHLEN-1;
6170 }
6171 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6172 lockPath[pathLen] = 0;
6173 tempLockPath = lockPath;
6174 tryOldLockPath = 1;
6175 /* create a copy of the lock path if the conch is taken */
6176 goto end_takeconch;
6177 }
6178 }else if( hostIdMatch
6179 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6180 readLen-PROXY_PATHINDEX)
6181 ){
6182 /* conch host and lock path match */
6183 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006184 }
drh7ed97b92010-01-20 13:07:21 +00006185 }
6186
6187 /* if the conch isn't writable and doesn't match, we can't take it */
6188 if( (conchFile->openFlags&O_RDWR) == 0 ){
6189 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006190 goto end_takeconch;
6191 }
drh7ed97b92010-01-20 13:07:21 +00006192
6193 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006194 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006195 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6196 tempLockPath = lockPath;
6197 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006198 }
drh7ed97b92010-01-20 13:07:21 +00006199
6200 /* update conch with host and path (this will fail if other process
6201 ** has a shared lock already), if the host id matches, use the big
6202 ** stick.
drh715ff302008-12-03 22:32:44 +00006203 */
drh7ed97b92010-01-20 13:07:21 +00006204 futimes(conchFile->h, NULL);
6205 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006206 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006207 /* We are trying for an exclusive lock but another thread in this
6208 ** same process is still holding a shared lock. */
6209 rc = SQLITE_BUSY;
6210 } else {
6211 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006212 }
drh715ff302008-12-03 22:32:44 +00006213 }else{
drh7ed97b92010-01-20 13:07:21 +00006214 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006215 }
drh7ed97b92010-01-20 13:07:21 +00006216 if( rc==SQLITE_OK ){
6217 char writeBuffer[PROXY_MAXCONCHLEN];
6218 int writeSize = 0;
6219
6220 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6221 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6222 if( pCtx->lockProxyPath!=NULL ){
6223 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6224 }else{
6225 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6226 }
6227 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006228 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006229 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6230 fsync(conchFile->h);
6231 /* If we created a new conch file (not just updated the contents of a
6232 ** valid conch file), try to match the permissions of the database
6233 */
6234 if( rc==SQLITE_OK && createConch ){
6235 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006236 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006237 if( err==0 ){
6238 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6239 S_IROTH|S_IWOTH);
6240 /* try to match the database file R/W permissions, ignore failure */
6241#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006242 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006243#else
drhff812312011-02-23 13:33:46 +00006244 do{
drhe562be52011-03-02 18:01:10 +00006245 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006246 }while( rc==(-1) && errno==EINTR );
6247 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006248 int code = errno;
6249 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6250 cmode, code, strerror(code));
6251 } else {
6252 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6253 }
6254 }else{
6255 int code = errno;
6256 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6257 err, code, strerror(code));
6258#endif
6259 }
drh715ff302008-12-03 22:32:44 +00006260 }
6261 }
drh7ed97b92010-01-20 13:07:21 +00006262 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6263
6264 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006265 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006266 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006267 int fd;
drh7ed97b92010-01-20 13:07:21 +00006268 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006269 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006270 }
6271 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006272 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006273 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006274 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006275 if( fd>=0 ){
6276 pFile->h = fd;
6277 }else{
drh9978c972010-02-23 17:36:32 +00006278 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006279 during locking */
6280 }
6281 }
6282 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6283 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6284 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6285 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6286 /* we couldn't create the proxy lock file with the old lock file path
6287 ** so try again via auto-naming
6288 */
6289 forceNewLockPath = 1;
6290 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006291 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006292 }
6293 }
6294 if( rc==SQLITE_OK ){
6295 /* Need to make a copy of path if we extracted the value
6296 ** from the conch file or the path was allocated on the stack
6297 */
6298 if( tempLockPath ){
6299 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6300 if( !pCtx->lockProxyPath ){
6301 rc = SQLITE_NOMEM;
6302 }
6303 }
6304 }
6305 if( rc==SQLITE_OK ){
6306 pCtx->conchHeld = 1;
6307
6308 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6309 afpLockingContext *afpCtx;
6310 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6311 afpCtx->dbPath = pCtx->lockProxyPath;
6312 }
6313 } else {
6314 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6315 }
drh308c2a52010-05-14 11:30:18 +00006316 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6317 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006318 return rc;
drh308c2a52010-05-14 11:30:18 +00006319 } while (1); /* in case we need to retry the :auto: lock file -
6320 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006321 }
6322}
6323
6324/*
6325** If pFile holds a lock on a conch file, then release that lock.
6326*/
6327static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006328 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006329 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6330 unixFile *conchFile; /* Name of the conch file */
6331
6332 pCtx = (proxyLockingContext *)pFile->lockingContext;
6333 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006334 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006335 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006336 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006337 if( pCtx->conchHeld>0 ){
6338 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6339 }
drh715ff302008-12-03 22:32:44 +00006340 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006341 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6342 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006343 return rc;
6344}
6345
6346/*
6347** Given the name of a database file, compute the name of its conch file.
6348** Store the conch filename in memory obtained from sqlite3_malloc().
6349** Make *pConchPath point to the new name. Return SQLITE_OK on success
6350** or SQLITE_NOMEM if unable to obtain memory.
6351**
6352** The caller is responsible for ensuring that the allocated memory
6353** space is eventually freed.
6354**
6355** *pConchPath is set to NULL if a memory allocation error occurs.
6356*/
6357static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6358 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006359 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006360 char *conchPath; /* buffer in which to construct conch name */
6361
6362 /* Allocate space for the conch filename and initialize the name to
6363 ** the name of the original database file. */
6364 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6365 if( conchPath==0 ){
6366 return SQLITE_NOMEM;
6367 }
6368 memcpy(conchPath, dbPath, len+1);
6369
6370 /* now insert a "." before the last / character */
6371 for( i=(len-1); i>=0; i-- ){
6372 if( conchPath[i]=='/' ){
6373 i++;
6374 break;
6375 }
6376 }
6377 conchPath[i]='.';
6378 while ( i<len ){
6379 conchPath[i+1]=dbPath[i];
6380 i++;
6381 }
6382
6383 /* append the "-conch" suffix to the file */
6384 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006385 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006386
6387 return SQLITE_OK;
6388}
6389
6390
6391/* Takes a fully configured proxy locking-style unix file and switches
6392** the local lock file path
6393*/
6394static int switchLockProxyPath(unixFile *pFile, const char *path) {
6395 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6396 char *oldPath = pCtx->lockProxyPath;
6397 int rc = SQLITE_OK;
6398
drh308c2a52010-05-14 11:30:18 +00006399 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006400 return SQLITE_BUSY;
6401 }
6402
6403 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6404 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6405 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6406 return SQLITE_OK;
6407 }else{
6408 unixFile *lockProxy = pCtx->lockProxy;
6409 pCtx->lockProxy=NULL;
6410 pCtx->conchHeld = 0;
6411 if( lockProxy!=NULL ){
6412 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6413 if( rc ) return rc;
6414 sqlite3_free(lockProxy);
6415 }
6416 sqlite3_free(oldPath);
6417 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6418 }
6419
6420 return rc;
6421}
6422
6423/*
6424** pFile is a file that has been opened by a prior xOpen call. dbPath
6425** is a string buffer at least MAXPATHLEN+1 characters in size.
6426**
6427** This routine find the filename associated with pFile and writes it
6428** int dbPath.
6429*/
6430static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006431#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006432 if( pFile->pMethod == &afpIoMethods ){
6433 /* afp style keeps a reference to the db path in the filePath field
6434 ** of the struct */
drhea678832008-12-10 19:26:22 +00006435 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006436 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6437 } else
drh715ff302008-12-03 22:32:44 +00006438#endif
6439 if( pFile->pMethod == &dotlockIoMethods ){
6440 /* dot lock style uses the locking context to store the dot lock
6441 ** file path */
6442 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6443 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6444 }else{
6445 /* all other styles use the locking context to store the db file path */
6446 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006447 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006448 }
6449 return SQLITE_OK;
6450}
6451
6452/*
6453** Takes an already filled in unix file and alters it so all file locking
6454** will be performed on the local proxy lock file. The following fields
6455** are preserved in the locking context so that they can be restored and
6456** the unix structure properly cleaned up at close time:
6457** ->lockingContext
6458** ->pMethod
6459*/
6460static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6461 proxyLockingContext *pCtx;
6462 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6463 char *lockPath=NULL;
6464 int rc = SQLITE_OK;
6465
drh308c2a52010-05-14 11:30:18 +00006466 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006467 return SQLITE_BUSY;
6468 }
6469 proxyGetDbPathForUnixFile(pFile, dbPath);
6470 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6471 lockPath=NULL;
6472 }else{
6473 lockPath=(char *)path;
6474 }
6475
drh308c2a52010-05-14 11:30:18 +00006476 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6477 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006478
6479 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6480 if( pCtx==0 ){
6481 return SQLITE_NOMEM;
6482 }
6483 memset(pCtx, 0, sizeof(*pCtx));
6484
6485 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6486 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006487 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6488 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6489 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6490 ** (c) the file system is read-only, then enable no-locking access.
6491 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6492 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6493 */
6494 struct statfs fsInfo;
6495 struct stat conchInfo;
6496 int goLockless = 0;
6497
drh99ab3b12011-03-02 15:09:07 +00006498 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006499 int err = errno;
6500 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6501 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6502 }
6503 }
6504 if( goLockless ){
6505 pCtx->conchHeld = -1; /* read only FS/ lockless */
6506 rc = SQLITE_OK;
6507 }
6508 }
drh715ff302008-12-03 22:32:44 +00006509 }
6510 if( rc==SQLITE_OK && lockPath ){
6511 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6512 }
6513
6514 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006515 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6516 if( pCtx->dbPath==NULL ){
6517 rc = SQLITE_NOMEM;
6518 }
6519 }
6520 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006521 /* all memory is allocated, proxys are created and assigned,
6522 ** switch the locking context and pMethod then return.
6523 */
drh715ff302008-12-03 22:32:44 +00006524 pCtx->oldLockingContext = pFile->lockingContext;
6525 pFile->lockingContext = pCtx;
6526 pCtx->pOldMethod = pFile->pMethod;
6527 pFile->pMethod = &proxyIoMethods;
6528 }else{
6529 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006530 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006531 sqlite3_free(pCtx->conchFile);
6532 }
drhd56b1212010-08-11 06:14:15 +00006533 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006534 sqlite3_free(pCtx->conchFilePath);
6535 sqlite3_free(pCtx);
6536 }
drh308c2a52010-05-14 11:30:18 +00006537 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6538 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006539 return rc;
6540}
6541
6542
6543/*
6544** This routine handles sqlite3_file_control() calls that are specific
6545** to proxy locking.
6546*/
6547static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6548 switch( op ){
6549 case SQLITE_GET_LOCKPROXYFILE: {
6550 unixFile *pFile = (unixFile*)id;
6551 if( pFile->pMethod == &proxyIoMethods ){
6552 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6553 proxyTakeConch(pFile);
6554 if( pCtx->lockProxyPath ){
6555 *(const char **)pArg = pCtx->lockProxyPath;
6556 }else{
6557 *(const char **)pArg = ":auto: (not held)";
6558 }
6559 } else {
6560 *(const char **)pArg = NULL;
6561 }
6562 return SQLITE_OK;
6563 }
6564 case SQLITE_SET_LOCKPROXYFILE: {
6565 unixFile *pFile = (unixFile*)id;
6566 int rc = SQLITE_OK;
6567 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6568 if( pArg==NULL || (const char *)pArg==0 ){
6569 if( isProxyStyle ){
6570 /* turn off proxy locking - not supported */
6571 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6572 }else{
6573 /* turn off proxy locking - already off - NOOP */
6574 rc = SQLITE_OK;
6575 }
6576 }else{
6577 const char *proxyPath = (const char *)pArg;
6578 if( isProxyStyle ){
6579 proxyLockingContext *pCtx =
6580 (proxyLockingContext*)pFile->lockingContext;
6581 if( !strcmp(pArg, ":auto:")
6582 || (pCtx->lockProxyPath &&
6583 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6584 ){
6585 rc = SQLITE_OK;
6586 }else{
6587 rc = switchLockProxyPath(pFile, proxyPath);
6588 }
6589 }else{
6590 /* turn on proxy file locking */
6591 rc = proxyTransformUnixFile(pFile, proxyPath);
6592 }
6593 }
6594 return rc;
6595 }
6596 default: {
6597 assert( 0 ); /* The call assures that only valid opcodes are sent */
6598 }
6599 }
6600 /*NOTREACHED*/
6601 return SQLITE_ERROR;
6602}
6603
6604/*
6605** Within this division (the proxying locking implementation) the procedures
6606** above this point are all utilities. The lock-related methods of the
6607** proxy-locking sqlite3_io_method object follow.
6608*/
6609
6610
6611/*
6612** This routine checks if there is a RESERVED lock held on the specified
6613** file by this or any other process. If such a lock is held, set *pResOut
6614** to a non-zero value otherwise *pResOut is set to zero. The return value
6615** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6616*/
6617static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6618 unixFile *pFile = (unixFile*)id;
6619 int rc = proxyTakeConch(pFile);
6620 if( rc==SQLITE_OK ){
6621 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006622 if( pCtx->conchHeld>0 ){
6623 unixFile *proxy = pCtx->lockProxy;
6624 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6625 }else{ /* conchHeld < 0 is lockless */
6626 pResOut=0;
6627 }
drh715ff302008-12-03 22:32:44 +00006628 }
6629 return rc;
6630}
6631
6632/*
drh308c2a52010-05-14 11:30:18 +00006633** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006634** of the following:
6635**
6636** (1) SHARED_LOCK
6637** (2) RESERVED_LOCK
6638** (3) PENDING_LOCK
6639** (4) EXCLUSIVE_LOCK
6640**
6641** Sometimes when requesting one lock state, additional lock states
6642** are inserted in between. The locking might fail on one of the later
6643** transitions leaving the lock state different from what it started but
6644** still short of its goal. The following chart shows the allowed
6645** transitions and the inserted intermediate states:
6646**
6647** UNLOCKED -> SHARED
6648** SHARED -> RESERVED
6649** SHARED -> (PENDING) -> EXCLUSIVE
6650** RESERVED -> (PENDING) -> EXCLUSIVE
6651** PENDING -> EXCLUSIVE
6652**
6653** This routine will only increase a lock. Use the sqlite3OsUnlock()
6654** routine to lower a locking level.
6655*/
drh308c2a52010-05-14 11:30:18 +00006656static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006657 unixFile *pFile = (unixFile*)id;
6658 int rc = proxyTakeConch(pFile);
6659 if( rc==SQLITE_OK ){
6660 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006661 if( pCtx->conchHeld>0 ){
6662 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006663 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6664 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006665 }else{
6666 /* conchHeld < 0 is lockless */
6667 }
drh715ff302008-12-03 22:32:44 +00006668 }
6669 return rc;
6670}
6671
6672
6673/*
drh308c2a52010-05-14 11:30:18 +00006674** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006675** must be either NO_LOCK or SHARED_LOCK.
6676**
6677** If the locking level of the file descriptor is already at or below
6678** the requested locking level, this routine is a no-op.
6679*/
drh308c2a52010-05-14 11:30:18 +00006680static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006681 unixFile *pFile = (unixFile*)id;
6682 int rc = proxyTakeConch(pFile);
6683 if( rc==SQLITE_OK ){
6684 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006685 if( pCtx->conchHeld>0 ){
6686 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006687 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6688 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006689 }else{
6690 /* conchHeld < 0 is lockless */
6691 }
drh715ff302008-12-03 22:32:44 +00006692 }
6693 return rc;
6694}
6695
6696/*
6697** Close a file that uses proxy locks.
6698*/
6699static int proxyClose(sqlite3_file *id) {
6700 if( id ){
6701 unixFile *pFile = (unixFile*)id;
6702 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6703 unixFile *lockProxy = pCtx->lockProxy;
6704 unixFile *conchFile = pCtx->conchFile;
6705 int rc = SQLITE_OK;
6706
6707 if( lockProxy ){
6708 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6709 if( rc ) return rc;
6710 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6711 if( rc ) return rc;
6712 sqlite3_free(lockProxy);
6713 pCtx->lockProxy = 0;
6714 }
6715 if( conchFile ){
6716 if( pCtx->conchHeld ){
6717 rc = proxyReleaseConch(pFile);
6718 if( rc ) return rc;
6719 }
6720 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6721 if( rc ) return rc;
6722 sqlite3_free(conchFile);
6723 }
drhd56b1212010-08-11 06:14:15 +00006724 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006725 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006726 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006727 /* restore the original locking context and pMethod then close it */
6728 pFile->lockingContext = pCtx->oldLockingContext;
6729 pFile->pMethod = pCtx->pOldMethod;
6730 sqlite3_free(pCtx);
6731 return pFile->pMethod->xClose(id);
6732 }
6733 return SQLITE_OK;
6734}
6735
6736
6737
drhd2cb50b2009-01-09 21:41:17 +00006738#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006739/*
6740** The proxy locking style is intended for use with AFP filesystems.
6741** And since AFP is only supported on MacOSX, the proxy locking is also
6742** restricted to MacOSX.
6743**
6744**
6745******************* End of the proxy lock implementation **********************
6746******************************************************************************/
6747
drh734c9862008-11-28 15:37:20 +00006748/*
danielk1977e339d652008-06-28 11:23:00 +00006749** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006750**
6751** This routine registers all VFS implementations for unix-like operating
6752** systems. This routine, and the sqlite3_os_end() routine that follows,
6753** should be the only routines in this file that are visible from other
6754** files.
drh6b9d6dd2008-12-03 19:34:47 +00006755**
6756** This routine is called once during SQLite initialization and by a
6757** single thread. The memory allocation and mutex subsystems have not
6758** necessarily been initialized when this routine is called, and so they
6759** should not be used.
drh153c62c2007-08-24 03:51:33 +00006760*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006761int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006762 /*
6763 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006764 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6765 ** to the "finder" function. (pAppData is a pointer to a pointer because
6766 ** silly C90 rules prohibit a void* from being cast to a function pointer
6767 ** and so we have to go through the intermediate pointer to avoid problems
6768 ** when compiling with -pedantic-errors on GCC.)
6769 **
6770 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006771 ** finder-function. The finder-function returns a pointer to the
6772 ** sqlite_io_methods object that implements the desired locking
6773 ** behaviors. See the division above that contains the IOMETHODS
6774 ** macro for addition information on finder-functions.
6775 **
6776 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6777 ** object. But the "autolockIoFinder" available on MacOSX does a little
6778 ** more than that; it looks at the filesystem type that hosts the
6779 ** database file and tries to choose an locking method appropriate for
6780 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006781 */
drh7708e972008-11-29 00:56:52 +00006782 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006783 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006784 sizeof(unixFile), /* szOsFile */ \
6785 MAX_PATHNAME, /* mxPathname */ \
6786 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006787 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006788 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006789 unixOpen, /* xOpen */ \
6790 unixDelete, /* xDelete */ \
6791 unixAccess, /* xAccess */ \
6792 unixFullPathname, /* xFullPathname */ \
6793 unixDlOpen, /* xDlOpen */ \
6794 unixDlError, /* xDlError */ \
6795 unixDlSym, /* xDlSym */ \
6796 unixDlClose, /* xDlClose */ \
6797 unixRandomness, /* xRandomness */ \
6798 unixSleep, /* xSleep */ \
6799 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006800 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006801 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006802 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006803 unixGetSystemCall, /* xGetSystemCall */ \
6804 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006805 }
6806
drh6b9d6dd2008-12-03 19:34:47 +00006807 /*
6808 ** All default VFSes for unix are contained in the following array.
6809 **
6810 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6811 ** by the SQLite core when the VFS is registered. So the following
6812 ** array cannot be const.
6813 */
danielk1977e339d652008-06-28 11:23:00 +00006814 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006815#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006816 UNIXVFS("unix", autolockIoFinder ),
6817#else
6818 UNIXVFS("unix", posixIoFinder ),
6819#endif
6820 UNIXVFS("unix-none", nolockIoFinder ),
6821 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006822 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006823#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006824 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006825#endif
6826#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006827 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006828#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006829 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006830#endif
chw78a13182009-04-07 05:35:03 +00006831#endif
drhd2cb50b2009-01-09 21:41:17 +00006832#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006833 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006834 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006835 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006836#endif
drh153c62c2007-08-24 03:51:33 +00006837 };
drh6b9d6dd2008-12-03 19:34:47 +00006838 unsigned int i; /* Loop counter */
6839
drh2aa5a002011-04-13 13:42:25 +00006840 /* Double-check that the aSyscall[] array has been constructed
6841 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8942d412012-01-02 18:20:14 +00006842 assert( ArraySize(aSyscall)==20 );
drh2aa5a002011-04-13 13:42:25 +00006843
drh6b9d6dd2008-12-03 19:34:47 +00006844 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006845 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006846 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006847 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006848 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006849}
danielk1977e339d652008-06-28 11:23:00 +00006850
6851/*
drh6b9d6dd2008-12-03 19:34:47 +00006852** Shutdown the operating system interface.
6853**
6854** Some operating systems might need to do some cleanup in this routine,
6855** to release dynamically allocated objects. But not on unix.
6856** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006857*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006858int sqlite3_os_end(void){
6859 return SQLITE_OK;
6860}
drhdce8bdb2007-08-16 13:01:44 +00006861
danielk197729bafea2008-06-26 10:41:19 +00006862#endif /* SQLITE_OS_UNIX */