blob: c6f71adc8ab2054e723852029f1b576147f39103 [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
drh23c4b972012-02-11 23:55:15 +0000422 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
423#define osFchown ((int(*)(const char*,uid_t,gid_t))aSyscall[20].pCurrent)
424
drhe562be52011-03-02 18:01:10 +0000425}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000426
427/*
428** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000429** "unix" VFSes. Return SQLITE_OK opon successfully updating the
430** system call pointer, or SQLITE_NOTFOUND if there is no configurable
431** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000432*/
433static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000434 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
435 const char *zName, /* Name of system call to override */
436 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000437){
drh58ad5802011-03-23 22:02:23 +0000438 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000439 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000440
441 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000442 if( zName==0 ){
443 /* If no zName is given, restore all system calls to their default
444 ** settings and return NULL
445 */
dan51438a72011-04-02 17:00:47 +0000446 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000447 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
448 if( aSyscall[i].pDefault ){
449 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000450 }
451 }
452 }else{
453 /* If zName is specified, operate on only the one system call
454 ** specified.
455 */
456 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
457 if( strcmp(zName, aSyscall[i].zName)==0 ){
458 if( aSyscall[i].pDefault==0 ){
459 aSyscall[i].pDefault = aSyscall[i].pCurrent;
460 }
drh1df30962011-03-02 19:06:42 +0000461 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000462 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
463 aSyscall[i].pCurrent = pNewFunc;
464 break;
465 }
466 }
467 }
468 return rc;
469}
470
drh1df30962011-03-02 19:06:42 +0000471/*
472** Return the value of a system call. Return NULL if zName is not a
473** recognized system call name. NULL is also returned if the system call
474** is currently undefined.
475*/
drh58ad5802011-03-23 22:02:23 +0000476static sqlite3_syscall_ptr unixGetSystemCall(
477 sqlite3_vfs *pNotUsed,
478 const char *zName
479){
480 unsigned int i;
481
482 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000483 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
484 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
485 }
486 return 0;
487}
488
489/*
490** Return the name of the first system call after zName. If zName==NULL
491** then return the name of the first system call. Return NULL if zName
492** is the last system call or if zName is not the name of a valid
493** system call.
494*/
495static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000496 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000497
498 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000499 if( zName ){
500 for(i=0; i<ArraySize(aSyscall)-1; i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000502 }
503 }
dan0fd7d862011-03-29 10:04:23 +0000504 for(i++; i<ArraySize(aSyscall); i++){
505 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000506 }
507 return 0;
508}
509
drhad4f1e52011-03-04 15:43:57 +0000510/*
511** Retry open() calls that fail due to EINTR
512*/
513static int robust_open(const char *z, int f, int m){
514 int rc;
515 do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
516 return rc;
517}
danielk197713adf8a2004-06-03 16:08:41 +0000518
drh107886a2008-11-21 22:21:50 +0000519/*
dan9359c7b2009-08-21 08:29:10 +0000520** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000521** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000522** vxworksFileId objects used by this file, all of which may be
523** shared by multiple threads.
524**
525** Function unixMutexHeld() is used to assert() that the global mutex
526** is held when required. This function is only used as part of assert()
527** statements. e.g.
528**
529** unixEnterMutex()
530** assert( unixMutexHeld() );
531** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000532*/
533static void unixEnterMutex(void){
534 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
535}
536static void unixLeaveMutex(void){
537 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
538}
dan9359c7b2009-08-21 08:29:10 +0000539#ifdef SQLITE_DEBUG
540static int unixMutexHeld(void) {
541 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
542}
543#endif
drh107886a2008-11-21 22:21:50 +0000544
drh734c9862008-11-28 15:37:20 +0000545
drh30ddce62011-10-15 00:16:30 +0000546#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000547/*
548** Helper function for printing out trace information from debugging
549** binaries. This returns the string represetation of the supplied
550** integer lock-type.
551*/
drh308c2a52010-05-14 11:30:18 +0000552static const char *azFileLock(int eFileLock){
553 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000554 case NO_LOCK: return "NONE";
555 case SHARED_LOCK: return "SHARED";
556 case RESERVED_LOCK: return "RESERVED";
557 case PENDING_LOCK: return "PENDING";
558 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000559 }
560 return "ERROR";
561}
562#endif
563
564#ifdef SQLITE_LOCK_TRACE
565/*
566** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000567**
drh734c9862008-11-28 15:37:20 +0000568** This routine is used for troubleshooting locks on multithreaded
569** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
570** command-line option on the compiler. This code is normally
571** turned off.
572*/
573static int lockTrace(int fd, int op, struct flock *p){
574 char *zOpName, *zType;
575 int s;
576 int savedErrno;
577 if( op==F_GETLK ){
578 zOpName = "GETLK";
579 }else if( op==F_SETLK ){
580 zOpName = "SETLK";
581 }else{
drh99ab3b12011-03-02 15:09:07 +0000582 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000583 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
584 return s;
585 }
586 if( p->l_type==F_RDLCK ){
587 zType = "RDLCK";
588 }else if( p->l_type==F_WRLCK ){
589 zType = "WRLCK";
590 }else if( p->l_type==F_UNLCK ){
591 zType = "UNLCK";
592 }else{
593 assert( 0 );
594 }
595 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000596 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000597 savedErrno = errno;
598 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
599 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
600 (int)p->l_pid, s);
601 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
602 struct flock l2;
603 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000604 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000605 if( l2.l_type==F_RDLCK ){
606 zType = "RDLCK";
607 }else if( l2.l_type==F_WRLCK ){
608 zType = "WRLCK";
609 }else if( l2.l_type==F_UNLCK ){
610 zType = "UNLCK";
611 }else{
612 assert( 0 );
613 }
614 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
615 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
616 }
617 errno = savedErrno;
618 return s;
619}
drh99ab3b12011-03-02 15:09:07 +0000620#undef osFcntl
621#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000622#endif /* SQLITE_LOCK_TRACE */
623
drhff812312011-02-23 13:33:46 +0000624/*
625** Retry ftruncate() calls that fail due to EINTR
626*/
drhff812312011-02-23 13:33:46 +0000627static int robust_ftruncate(int h, sqlite3_int64 sz){
628 int rc;
drh99ab3b12011-03-02 15:09:07 +0000629 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000630 return rc;
631}
drh734c9862008-11-28 15:37:20 +0000632
633/*
634** This routine translates a standard POSIX errno code into something
635** useful to the clients of the sqlite3 functions. Specifically, it is
636** intended to translate a variety of "try again" errors into SQLITE_BUSY
637** and a variety of "please close the file descriptor NOW" errors into
638** SQLITE_IOERR
639**
640** Errors during initialization of locks, or file system support for locks,
641** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
642*/
643static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
644 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000645#if 0
646 /* At one point this code was not commented out. In theory, this branch
647 ** should never be hit, as this function should only be called after
648 ** a locking-related function (i.e. fcntl()) has returned non-zero with
649 ** the value of errno as the first argument. Since a system call has failed,
650 ** errno should be non-zero.
651 **
652 ** Despite this, if errno really is zero, we still don't want to return
653 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
654 ** propagated back to the caller. Commenting this branch out means errno==0
655 ** will be handled by the "default:" case below.
656 */
drh734c9862008-11-28 15:37:20 +0000657 case 0:
658 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000659#endif
660
drh734c9862008-11-28 15:37:20 +0000661 case EAGAIN:
662 case ETIMEDOUT:
663 case EBUSY:
664 case EINTR:
665 case ENOLCK:
666 /* random NFS retry error, unless during file system support
667 * introspection, in which it actually means what it says */
668 return SQLITE_BUSY;
669
670 case EACCES:
671 /* EACCES is like EAGAIN during locking operations, but not any other time*/
672 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
673 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
674 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
675 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
676 return SQLITE_BUSY;
677 }
678 /* else fall through */
679 case EPERM:
680 return SQLITE_PERM;
681
danea83bc62011-04-01 11:56:32 +0000682 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
683 ** this module never makes such a call. And the code in SQLite itself
684 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
685 ** this case is also commented out. If the system does set errno to EDEADLK,
686 ** the default SQLITE_IOERR_XXX code will be returned. */
687#if 0
drh734c9862008-11-28 15:37:20 +0000688 case EDEADLK:
689 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000690#endif
drh734c9862008-11-28 15:37:20 +0000691
692#if EOPNOTSUPP!=ENOTSUP
693 case EOPNOTSUPP:
694 /* something went terribly awry, unless during file system support
695 * introspection, in which it actually means what it says */
696#endif
697#ifdef ENOTSUP
698 case ENOTSUP:
699 /* invalid fd, unless during file system support introspection, in which
700 * it actually means what it says */
701#endif
702 case EIO:
703 case EBADF:
704 case EINVAL:
705 case ENOTCONN:
706 case ENODEV:
707 case ENXIO:
708 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000709#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000710 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000711#endif
drh734c9862008-11-28 15:37:20 +0000712 case ENOSYS:
713 /* these should force the client to close the file and reconnect */
714
715 default:
716 return sqliteIOErr;
717 }
718}
719
720
721
722/******************************************************************************
723****************** Begin Unique File ID Utility Used By VxWorks ***************
724**
725** On most versions of unix, we can get a unique ID for a file by concatenating
726** the device number and the inode number. But this does not work on VxWorks.
727** On VxWorks, a unique file id must be based on the canonical filename.
728**
729** A pointer to an instance of the following structure can be used as a
730** unique file ID in VxWorks. Each instance of this structure contains
731** a copy of the canonical filename. There is also a reference count.
732** The structure is reclaimed when the number of pointers to it drops to
733** zero.
734**
735** There are never very many files open at one time and lookups are not
736** a performance-critical path, so it is sufficient to put these
737** structures on a linked list.
738*/
739struct vxworksFileId {
740 struct vxworksFileId *pNext; /* Next in a list of them all */
741 int nRef; /* Number of references to this one */
742 int nName; /* Length of the zCanonicalName[] string */
743 char *zCanonicalName; /* Canonical filename */
744};
745
746#if OS_VXWORKS
747/*
drh9b35ea62008-11-29 02:20:26 +0000748** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000749** variable:
750*/
751static struct vxworksFileId *vxworksFileList = 0;
752
753/*
754** Simplify a filename into its canonical form
755** by making the following changes:
756**
757** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000758** * convert /./ into just /
759** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000760**
761** Changes are made in-place. Return the new name length.
762**
763** The original filename is in z[0..n-1]. Return the number of
764** characters in the simplified name.
765*/
766static int vxworksSimplifyName(char *z, int n){
767 int i, j;
768 while( n>1 && z[n-1]=='/' ){ n--; }
769 for(i=j=0; i<n; i++){
770 if( z[i]=='/' ){
771 if( z[i+1]=='/' ) continue;
772 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
773 i += 1;
774 continue;
775 }
776 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
777 while( j>0 && z[j-1]!='/' ){ j--; }
778 if( j>0 ){ j--; }
779 i += 2;
780 continue;
781 }
782 }
783 z[j++] = z[i];
784 }
785 z[j] = 0;
786 return j;
787}
788
789/*
790** Find a unique file ID for the given absolute pathname. Return
791** a pointer to the vxworksFileId object. This pointer is the unique
792** file ID.
793**
794** The nRef field of the vxworksFileId object is incremented before
795** the object is returned. A new vxworksFileId object is created
796** and added to the global list if necessary.
797**
798** If a memory allocation error occurs, return NULL.
799*/
800static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
801 struct vxworksFileId *pNew; /* search key and new file ID */
802 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
803 int n; /* Length of zAbsoluteName string */
804
805 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000806 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000807 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
808 if( pNew==0 ) return 0;
809 pNew->zCanonicalName = (char*)&pNew[1];
810 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
811 n = vxworksSimplifyName(pNew->zCanonicalName, n);
812
813 /* Search for an existing entry that matching the canonical name.
814 ** If found, increment the reference count and return a pointer to
815 ** the existing file ID.
816 */
817 unixEnterMutex();
818 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
819 if( pCandidate->nName==n
820 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
821 ){
822 sqlite3_free(pNew);
823 pCandidate->nRef++;
824 unixLeaveMutex();
825 return pCandidate;
826 }
827 }
828
829 /* No match was found. We will make a new file ID */
830 pNew->nRef = 1;
831 pNew->nName = n;
832 pNew->pNext = vxworksFileList;
833 vxworksFileList = pNew;
834 unixLeaveMutex();
835 return pNew;
836}
837
838/*
839** Decrement the reference count on a vxworksFileId object. Free
840** the object when the reference count reaches zero.
841*/
842static void vxworksReleaseFileId(struct vxworksFileId *pId){
843 unixEnterMutex();
844 assert( pId->nRef>0 );
845 pId->nRef--;
846 if( pId->nRef==0 ){
847 struct vxworksFileId **pp;
848 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
849 assert( *pp==pId );
850 *pp = pId->pNext;
851 sqlite3_free(pId);
852 }
853 unixLeaveMutex();
854}
855#endif /* OS_VXWORKS */
856/*************** End of Unique File ID Utility Used By VxWorks ****************
857******************************************************************************/
858
859
860/******************************************************************************
861*************************** Posix Advisory Locking ****************************
862**
drh9b35ea62008-11-29 02:20:26 +0000863** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000864** section 6.5.2.2 lines 483 through 490 specify that when a process
865** sets or clears a lock, that operation overrides any prior locks set
866** by the same process. It does not explicitly say so, but this implies
867** that it overrides locks set by the same process using a different
868** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000869**
870** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000871** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
872**
873** Suppose ./file1 and ./file2 are really the same file (because
874** one is a hard or symbolic link to the other) then if you set
875** an exclusive lock on fd1, then try to get an exclusive lock
876** on fd2, it works. I would have expected the second lock to
877** fail since there was already a lock on the file due to fd1.
878** But not so. Since both locks came from the same process, the
879** second overrides the first, even though they were on different
880** file descriptors opened on different file names.
881**
drh734c9862008-11-28 15:37:20 +0000882** This means that we cannot use POSIX locks to synchronize file access
883** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000884** to synchronize access for threads in separate processes, but not
885** threads within the same process.
886**
887** To work around the problem, SQLite has to manage file locks internally
888** on its own. Whenever a new database is opened, we have to find the
889** specific inode of the database file (the inode is determined by the
890** st_dev and st_ino fields of the stat structure that fstat() fills in)
891** and check for locks already existing on that inode. When locks are
892** created or removed, we have to look at our own internal record of the
893** locks to see if another thread has previously set a lock on that same
894** inode.
895**
drh9b35ea62008-11-29 02:20:26 +0000896** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
897** For VxWorks, we have to use the alternative unique ID system based on
898** canonical filename and implemented in the previous division.)
899**
danielk1977ad94b582007-08-20 06:44:22 +0000900** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000901** descriptor. It is now a structure that holds the integer file
902** descriptor and a pointer to a structure that describes the internal
903** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000904** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000905** point to the same locking structure. The locking structure keeps
906** a reference count (so we will know when to delete it) and a "cnt"
907** field that tells us its internal lock status. cnt==0 means the
908** file is unlocked. cnt==-1 means the file has an exclusive lock.
909** cnt>0 means there are cnt shared locks on the file.
910**
911** Any attempt to lock or unlock a file first checks the locking
912** structure. The fcntl() system call is only invoked to set a
913** POSIX lock if the internal lock structure transitions between
914** a locked and an unlocked state.
915**
drh734c9862008-11-28 15:37:20 +0000916** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000917**
918** If you close a file descriptor that points to a file that has locks,
919** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000920** released. To work around this problem, each unixInodeInfo object
921** maintains a count of the number of pending locks on tha inode.
922** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000923** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000924** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000925** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000926** be closed and that list is walked (and cleared) when the last lock
927** clears.
928**
drh9b35ea62008-11-29 02:20:26 +0000929** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000930**
drh9b35ea62008-11-29 02:20:26 +0000931** Many older versions of linux use the LinuxThreads library which is
932** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000933** A cannot be modified or overridden by a different thread B.
934** Only thread A can modify the lock. Locking behavior is correct
935** if the appliation uses the newer Native Posix Thread Library (NPTL)
936** on linux - with NPTL a lock created by thread A can override locks
937** in thread B. But there is no way to know at compile-time which
938** threading library is being used. So there is no way to know at
939** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000940** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000941** current process.
drh5fdae772004-06-29 03:29:00 +0000942**
drh8af6c222010-05-14 12:43:01 +0000943** SQLite used to support LinuxThreads. But support for LinuxThreads
944** was dropped beginning with version 3.7.0. SQLite will still work with
945** LinuxThreads provided that (1) there is no more than one connection
946** per database file in the same process and (2) database connections
947** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000948*/
949
950/*
951** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +0000952** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +0000953*/
954struct unixFileId {
drh107886a2008-11-21 22:21:50 +0000955 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +0000956#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +0000957 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +0000958#else
drh107886a2008-11-21 22:21:50 +0000959 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +0000960#endif
961};
962
963/*
drhbbd42a62004-05-22 17:41:58 +0000964** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +0000965** inode. Or, on LinuxThreads, there is one of these structures for
966** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +0000967**
danielk1977ad94b582007-08-20 06:44:22 +0000968** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +0000969** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +0000970** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +0000971*/
drh8af6c222010-05-14 12:43:01 +0000972struct unixInodeInfo {
973 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +0000974 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +0000975 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
976 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +0000977 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +0000978 unixShmNode *pShmNode; /* Shared memory associated with this inode */
979 int nLock; /* Number of outstanding file locks */
980 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
981 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
982 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +0000983#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +0000984 unsigned long long sharedByte; /* for AFP simulated shared lock */
985#endif
drh6c7d5c52008-11-21 20:32:33 +0000986#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000987 sem_t *pSem; /* Named POSIX semaphore */
988 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +0000989#endif
drhbbd42a62004-05-22 17:41:58 +0000990};
991
drhda0e7682008-07-30 15:27:54 +0000992/*
drh8af6c222010-05-14 12:43:01 +0000993** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +0000994*/
drhd91c68f2010-05-14 14:52:25 +0000995static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +0000996
drh5fdae772004-06-29 03:29:00 +0000997/*
dane18d4952011-02-21 11:46:24 +0000998**
999** This function - unixLogError_x(), is only ever called via the macro
1000** unixLogError().
1001**
1002** It is invoked after an error occurs in an OS function and errno has been
1003** set. It logs a message using sqlite3_log() containing the current value of
1004** errno and, if possible, the human-readable equivalent from strerror() or
1005** strerror_r().
1006**
1007** The first argument passed to the macro should be the error code that
1008** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1009** The two subsequent arguments should be the name of the OS function that
1010** failed (e.g. "unlink", "open") and the the associated file-system path,
1011** if any.
1012*/
drh0e9365c2011-03-02 02:08:13 +00001013#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1014static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001015 int errcode, /* SQLite error code */
1016 const char *zFunc, /* Name of OS function that failed */
1017 const char *zPath, /* File path associated with error */
1018 int iLine /* Source line number where error occurred */
1019){
1020 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001021 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001022
1023 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1024 ** the strerror() function to obtain the human-readable error message
1025 ** equivalent to errno. Otherwise, use strerror_r().
1026 */
1027#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1028 char aErr[80];
1029 memset(aErr, 0, sizeof(aErr));
1030 zErr = aErr;
1031
1032 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
1033 ** assume that the system provides the the GNU version of strerror_r() that
1034 ** returns a pointer to a buffer containing the error message. That pointer
1035 ** may point to aErr[], or it may point to some static storage somewhere.
1036 ** Otherwise, assume that the system provides the POSIX version of
1037 ** strerror_r(), which always writes an error message into aErr[].
1038 **
1039 ** If the code incorrectly assumes that it is the POSIX version that is
1040 ** available, the error message will often be an empty string. Not a
1041 ** huge problem. Incorrectly concluding that the GNU version is available
1042 ** could lead to a segfault though.
1043 */
1044#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1045 zErr =
1046# endif
drh0e9365c2011-03-02 02:08:13 +00001047 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001048
1049#elif SQLITE_THREADSAFE
1050 /* This is a threadsafe build, but strerror_r() is not available. */
1051 zErr = "";
1052#else
1053 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001054 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001055#endif
1056
1057 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001058 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001059 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001060 "os_unix.c:%d: (%d) %s(%s) - %s",
1061 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001062 );
1063
1064 return errcode;
1065}
1066
drh0e9365c2011-03-02 02:08:13 +00001067/*
1068** Close a file descriptor.
1069**
1070** We assume that close() almost always works, since it is only in a
1071** very sick application or on a very sick platform that it might fail.
1072** If it does fail, simply leak the file descriptor, but do log the
1073** error.
1074**
1075** Note that it is not safe to retry close() after EINTR since the
1076** file descriptor might have already been reused by another thread.
1077** So we don't even try to recover from an EINTR. Just log the error
1078** and move on.
1079*/
1080static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001081 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001082 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1083 pFile ? pFile->zPath : 0, lineno);
1084 }
1085}
dane18d4952011-02-21 11:46:24 +00001086
1087/*
danb0ac3e32010-06-16 10:55:42 +00001088** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001089*/
drh0e9365c2011-03-02 02:08:13 +00001090static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001091 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001092 UnixUnusedFd *p;
1093 UnixUnusedFd *pNext;
1094 for(p=pInode->pUnused; p; p=pNext){
1095 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001096 robust_close(pFile, p->fd, __LINE__);
1097 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001098 }
drh0e9365c2011-03-02 02:08:13 +00001099 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001100}
1101
1102/*
drh8af6c222010-05-14 12:43:01 +00001103** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001104**
1105** The mutex entered using the unixEnterMutex() function must be held
1106** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001107*/
danb0ac3e32010-06-16 10:55:42 +00001108static void releaseInodeInfo(unixFile *pFile){
1109 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001110 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001111 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001112 pInode->nRef--;
1113 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001114 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001115 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001116 if( pInode->pPrev ){
1117 assert( pInode->pPrev->pNext==pInode );
1118 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001119 }else{
drh8af6c222010-05-14 12:43:01 +00001120 assert( inodeList==pInode );
1121 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001122 }
drh8af6c222010-05-14 12:43:01 +00001123 if( pInode->pNext ){
1124 assert( pInode->pNext->pPrev==pInode );
1125 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001126 }
drh8af6c222010-05-14 12:43:01 +00001127 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001128 }
drhbbd42a62004-05-22 17:41:58 +00001129 }
1130}
1131
1132/*
drh8af6c222010-05-14 12:43:01 +00001133** Given a file descriptor, locate the unixInodeInfo object that
1134** describes that file descriptor. Create a new one if necessary. The
1135** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001136**
dan9359c7b2009-08-21 08:29:10 +00001137** The mutex entered using the unixEnterMutex() function must be held
1138** when this function is called.
1139**
drh6c7d5c52008-11-21 20:32:33 +00001140** Return an appropriate error code.
1141*/
drh8af6c222010-05-14 12:43:01 +00001142static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001143 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001144 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001145){
1146 int rc; /* System call return code */
1147 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001148 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1149 struct stat statbuf; /* Low-level file information */
1150 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001151
dan9359c7b2009-08-21 08:29:10 +00001152 assert( unixMutexHeld() );
1153
drh6c7d5c52008-11-21 20:32:33 +00001154 /* Get low-level information about the file that we can used to
1155 ** create a unique name for the file.
1156 */
1157 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001158 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001159 if( rc!=0 ){
1160 pFile->lastErrno = errno;
1161#ifdef EOVERFLOW
1162 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1163#endif
1164 return SQLITE_IOERR;
1165 }
1166
drheb0d74f2009-02-03 15:27:02 +00001167#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001168 /* On OS X on an msdos filesystem, the inode number is reported
1169 ** incorrectly for zero-size files. See ticket #3260. To work
1170 ** around this problem (we consider it a bug in OS X, not SQLite)
1171 ** we always increase the file size to 1 by writing a single byte
1172 ** prior to accessing the inode number. The one byte written is
1173 ** an ASCII 'S' character which also happens to be the first byte
1174 ** in the header of every SQLite database. In this way, if there
1175 ** is a race condition such that another thread has already populated
1176 ** the first page of the database, no damage is done.
1177 */
drh7ed97b92010-01-20 13:07:21 +00001178 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001179 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001180 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001181 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001182 return SQLITE_IOERR;
1183 }
drh99ab3b12011-03-02 15:09:07 +00001184 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001185 if( rc!=0 ){
1186 pFile->lastErrno = errno;
1187 return SQLITE_IOERR;
1188 }
1189 }
drheb0d74f2009-02-03 15:27:02 +00001190#endif
drh6c7d5c52008-11-21 20:32:33 +00001191
drh8af6c222010-05-14 12:43:01 +00001192 memset(&fileId, 0, sizeof(fileId));
1193 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001194#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001195 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001196#else
drh8af6c222010-05-14 12:43:01 +00001197 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001198#endif
drh8af6c222010-05-14 12:43:01 +00001199 pInode = inodeList;
1200 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1201 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001202 }
drh8af6c222010-05-14 12:43:01 +00001203 if( pInode==0 ){
1204 pInode = sqlite3_malloc( sizeof(*pInode) );
1205 if( pInode==0 ){
1206 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001207 }
drh8af6c222010-05-14 12:43:01 +00001208 memset(pInode, 0, sizeof(*pInode));
1209 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1210 pInode->nRef = 1;
1211 pInode->pNext = inodeList;
1212 pInode->pPrev = 0;
1213 if( inodeList ) inodeList->pPrev = pInode;
1214 inodeList = pInode;
1215 }else{
1216 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001217 }
drh8af6c222010-05-14 12:43:01 +00001218 *ppInode = pInode;
1219 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001220}
drh6c7d5c52008-11-21 20:32:33 +00001221
aswift5b1a2562008-08-22 00:22:35 +00001222
1223/*
danielk197713adf8a2004-06-03 16:08:41 +00001224** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001225** file by this or any other process. If such a lock is held, set *pResOut
1226** to a non-zero value otherwise *pResOut is set to zero. The return value
1227** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001228*/
danielk1977861f7452008-06-05 11:39:11 +00001229static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001230 int rc = SQLITE_OK;
1231 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001232 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001233
danielk1977861f7452008-06-05 11:39:11 +00001234 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1235
drh054889e2005-11-30 03:20:31 +00001236 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001237 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001238
1239 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001240 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001241 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001242 }
1243
drh2ac3ee92004-06-07 16:27:46 +00001244 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001245 */
danielk197709480a92009-02-09 05:32:32 +00001246#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001247 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001248 struct flock lock;
1249 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001250 lock.l_start = RESERVED_BYTE;
1251 lock.l_len = 1;
1252 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001253 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1254 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1255 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001256 } else if( lock.l_type!=F_UNLCK ){
1257 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001258 }
1259 }
danielk197709480a92009-02-09 05:32:32 +00001260#endif
danielk197713adf8a2004-06-03 16:08:41 +00001261
drh6c7d5c52008-11-21 20:32:33 +00001262 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001263 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001264
aswift5b1a2562008-08-22 00:22:35 +00001265 *pResOut = reserved;
1266 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001267}
1268
1269/*
drha7e61d82011-03-12 17:02:57 +00001270** Attempt to set a system-lock on the file pFile. The lock is
1271** described by pLock.
1272**
drh77197112011-03-15 19:08:48 +00001273** If the pFile was opened read/write from unix-excl, then the only lock
1274** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001275** the first time any lock is attempted. All subsequent system locking
1276** operations become no-ops. Locking operations still happen internally,
1277** in order to coordinate access between separate database connections
1278** within this process, but all of that is handled in memory and the
1279** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001280**
1281** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1282** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1283** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001284**
1285** Zero is returned if the call completes successfully, or -1 if a call
1286** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001287*/
1288static int unixFileLock(unixFile *pFile, struct flock *pLock){
1289 int rc;
drh3cb93392011-03-12 18:10:44 +00001290 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001291 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001292 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001293 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1294 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1295 ){
drh3cb93392011-03-12 18:10:44 +00001296 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001297 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001298 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001299 lock.l_whence = SEEK_SET;
1300 lock.l_start = SHARED_FIRST;
1301 lock.l_len = SHARED_SIZE;
1302 lock.l_type = F_WRLCK;
1303 rc = osFcntl(pFile->h, F_SETLK, &lock);
1304 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001305 pInode->bProcessLock = 1;
1306 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001307 }else{
1308 rc = 0;
1309 }
1310 }else{
1311 rc = osFcntl(pFile->h, F_SETLK, pLock);
1312 }
1313 return rc;
1314}
1315
1316/*
drh308c2a52010-05-14 11:30:18 +00001317** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001318** of the following:
1319**
drh2ac3ee92004-06-07 16:27:46 +00001320** (1) SHARED_LOCK
1321** (2) RESERVED_LOCK
1322** (3) PENDING_LOCK
1323** (4) EXCLUSIVE_LOCK
1324**
drhb3e04342004-06-08 00:47:47 +00001325** Sometimes when requesting one lock state, additional lock states
1326** are inserted in between. The locking might fail on one of the later
1327** transitions leaving the lock state different from what it started but
1328** still short of its goal. The following chart shows the allowed
1329** transitions and the inserted intermediate states:
1330**
1331** UNLOCKED -> SHARED
1332** SHARED -> RESERVED
1333** SHARED -> (PENDING) -> EXCLUSIVE
1334** RESERVED -> (PENDING) -> EXCLUSIVE
1335** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001336**
drha6abd042004-06-09 17:37:22 +00001337** This routine will only increase a lock. Use the sqlite3OsUnlock()
1338** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001339*/
drh308c2a52010-05-14 11:30:18 +00001340static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001341 /* The following describes the implementation of the various locks and
1342 ** lock transitions in terms of the POSIX advisory shared and exclusive
1343 ** lock primitives (called read-locks and write-locks below, to avoid
1344 ** confusion with SQLite lock names). The algorithms are complicated
1345 ** slightly in order to be compatible with windows systems simultaneously
1346 ** accessing the same database file, in case that is ever required.
1347 **
1348 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1349 ** byte', each single bytes at well known offsets, and the 'shared byte
1350 ** range', a range of 510 bytes at a well known offset.
1351 **
1352 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1353 ** byte'. If this is successful, a random byte from the 'shared byte
1354 ** range' is read-locked and the lock on the 'pending byte' released.
1355 **
danielk197790ba3bd2004-06-25 08:32:25 +00001356 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1357 ** A RESERVED lock is implemented by grabbing a write-lock on the
1358 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001359 **
1360 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001361 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1362 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1363 ** obtained, but existing SHARED locks are allowed to persist. A process
1364 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1365 ** This property is used by the algorithm for rolling back a journal file
1366 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001367 **
danielk197790ba3bd2004-06-25 08:32:25 +00001368 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1369 ** implemented by obtaining a write-lock on the entire 'shared byte
1370 ** range'. Since all other locks require a read-lock on one of the bytes
1371 ** within this range, this ensures that no other locks are held on the
1372 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001373 **
1374 ** The reason a single byte cannot be used instead of the 'shared byte
1375 ** range' is that some versions of windows do not support read-locks. By
1376 ** locking a random byte from a range, concurrent SHARED locks may exist
1377 ** even if the locking primitive used is always a write-lock.
1378 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001379 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001380 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001381 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001382 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001383 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001384
drh054889e2005-11-30 03:20:31 +00001385 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001386 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1387 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001388 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001389
1390 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001391 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001392 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001393 */
drh308c2a52010-05-14 11:30:18 +00001394 if( pFile->eFileLock>=eFileLock ){
1395 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1396 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001397 return SQLITE_OK;
1398 }
1399
drh0c2694b2009-09-03 16:23:44 +00001400 /* Make sure the locking sequence is correct.
1401 ** (1) We never move from unlocked to anything higher than shared lock.
1402 ** (2) SQLite never explicitly requests a pendig lock.
1403 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001404 */
drh308c2a52010-05-14 11:30:18 +00001405 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1406 assert( eFileLock!=PENDING_LOCK );
1407 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001408
drh8af6c222010-05-14 12:43:01 +00001409 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001410 */
drh6c7d5c52008-11-21 20:32:33 +00001411 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001412 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001413
danielk1977ad94b582007-08-20 06:44:22 +00001414 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001415 ** handle that precludes the requested lock, return BUSY.
1416 */
drh8af6c222010-05-14 12:43:01 +00001417 if( (pFile->eFileLock!=pInode->eFileLock &&
1418 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001419 ){
1420 rc = SQLITE_BUSY;
1421 goto end_lock;
1422 }
1423
1424 /* If a SHARED lock is requested, and some thread using this PID already
1425 ** has a SHARED or RESERVED lock, then increment reference counts and
1426 ** return SQLITE_OK.
1427 */
drh308c2a52010-05-14 11:30:18 +00001428 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001429 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001430 assert( eFileLock==SHARED_LOCK );
1431 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001432 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001433 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001434 pInode->nShared++;
1435 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001436 goto end_lock;
1437 }
1438
danielk19779a1d0ab2004-06-01 14:09:28 +00001439
drh3cde3bb2004-06-12 02:17:14 +00001440 /* A PENDING lock is needed before acquiring a SHARED lock and before
1441 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1442 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001443 */
drh0c2694b2009-09-03 16:23:44 +00001444 lock.l_len = 1L;
1445 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001446 if( eFileLock==SHARED_LOCK
1447 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001448 ){
drh308c2a52010-05-14 11:30:18 +00001449 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001450 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001451 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001452 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001453 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001454 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001455 pFile->lastErrno = tErrno;
1456 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001457 goto end_lock;
1458 }
drh3cde3bb2004-06-12 02:17:14 +00001459 }
1460
1461
1462 /* If control gets to this point, then actually go ahead and make
1463 ** operating system calls for the specified lock.
1464 */
drh308c2a52010-05-14 11:30:18 +00001465 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001466 assert( pInode->nShared==0 );
1467 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001468 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001469
drh2ac3ee92004-06-07 16:27:46 +00001470 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001471 lock.l_start = SHARED_FIRST;
1472 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001473 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001474 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001475 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001476 }
dan661d71a2011-03-30 19:08:03 +00001477
drh2ac3ee92004-06-07 16:27:46 +00001478 /* Drop the temporary PENDING lock */
1479 lock.l_start = PENDING_BYTE;
1480 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001481 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001482 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1483 /* This could happen with a network mount */
1484 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001485 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001486 }
dan661d71a2011-03-30 19:08:03 +00001487
1488 if( rc ){
1489 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001490 pFile->lastErrno = tErrno;
1491 }
dan661d71a2011-03-30 19:08:03 +00001492 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001493 }else{
drh308c2a52010-05-14 11:30:18 +00001494 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001495 pInode->nLock++;
1496 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001497 }
drh8af6c222010-05-14 12:43:01 +00001498 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001499 /* We are trying for an exclusive lock but another thread in this
1500 ** same process is still holding a shared lock. */
1501 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001502 }else{
drh3cde3bb2004-06-12 02:17:14 +00001503 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001504 ** assumed that there is a SHARED or greater lock on the file
1505 ** already.
1506 */
drh308c2a52010-05-14 11:30:18 +00001507 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001508 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001509
1510 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1511 if( eFileLock==RESERVED_LOCK ){
1512 lock.l_start = RESERVED_BYTE;
1513 lock.l_len = 1L;
1514 }else{
1515 lock.l_start = SHARED_FIRST;
1516 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001517 }
dan661d71a2011-03-30 19:08:03 +00001518
1519 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001520 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001521 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001522 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001523 pFile->lastErrno = tErrno;
1524 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001525 }
drhbbd42a62004-05-22 17:41:58 +00001526 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001527
drh8f941bc2009-01-14 23:03:40 +00001528
1529#ifndef NDEBUG
1530 /* Set up the transaction-counter change checking flags when
1531 ** transitioning from a SHARED to a RESERVED lock. The change
1532 ** from SHARED to RESERVED marks the beginning of a normal
1533 ** write operation (not a hot journal rollback).
1534 */
1535 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001536 && pFile->eFileLock<=SHARED_LOCK
1537 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001538 ){
1539 pFile->transCntrChng = 0;
1540 pFile->dbUpdate = 0;
1541 pFile->inNormalWrite = 1;
1542 }
1543#endif
1544
1545
danielk1977ecb2a962004-06-02 06:30:16 +00001546 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001547 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001548 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001549 }else if( eFileLock==EXCLUSIVE_LOCK ){
1550 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001551 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001552 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001553
1554end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001555 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001556 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1557 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001558 return rc;
1559}
1560
1561/*
dan08da86a2009-08-21 17:18:03 +00001562** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001563** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001564*/
1565static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001566 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001567 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001568 p->pNext = pInode->pUnused;
1569 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001570 pFile->h = -1;
1571 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001572}
1573
1574/*
drh308c2a52010-05-14 11:30:18 +00001575** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001576** must be either NO_LOCK or SHARED_LOCK.
1577**
1578** If the locking level of the file descriptor is already at or below
1579** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001580**
1581** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1582** the byte range is divided into 2 parts and the first part is unlocked then
1583** set to a read lock, then the other part is simply unlocked. This works
1584** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1585** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001586*/
drha7e61d82011-03-12 17:02:57 +00001587static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001588 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001589 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001590 struct flock lock;
1591 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001592
drh054889e2005-11-30 03:20:31 +00001593 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001594 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001595 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001596 getpid()));
drha6abd042004-06-09 17:37:22 +00001597
drh308c2a52010-05-14 11:30:18 +00001598 assert( eFileLock<=SHARED_LOCK );
1599 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001600 return SQLITE_OK;
1601 }
drh6c7d5c52008-11-21 20:32:33 +00001602 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001603 pInode = pFile->pInode;
1604 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001605 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001606 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001607
1608#ifndef NDEBUG
1609 /* When reducing a lock such that other processes can start
1610 ** reading the database file again, make sure that the
1611 ** transaction counter was updated if any part of the database
1612 ** file changed. If the transaction counter is not updated,
1613 ** other connections to the same file might not realize that
1614 ** the file has changed and hence might not know to flush their
1615 ** cache. The use of a stale cache can lead to database corruption.
1616 */
drh8f941bc2009-01-14 23:03:40 +00001617 pFile->inNormalWrite = 0;
1618#endif
1619
drh7ed97b92010-01-20 13:07:21 +00001620 /* downgrading to a shared lock on NFS involves clearing the write lock
1621 ** before establishing the readlock - to avoid a race condition we downgrade
1622 ** the lock in 2 blocks, so that part of the range will be covered by a
1623 ** write lock until the rest is covered by a read lock:
1624 ** 1: [WWWWW]
1625 ** 2: [....W]
1626 ** 3: [RRRRW]
1627 ** 4: [RRRR.]
1628 */
drh308c2a52010-05-14 11:30:18 +00001629 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001630
1631#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001632 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001633 assert( handleNFSUnlock==0 );
1634#endif
1635#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001636 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001637 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001638 off_t divSize = SHARED_SIZE - 1;
1639
1640 lock.l_type = F_UNLCK;
1641 lock.l_whence = SEEK_SET;
1642 lock.l_start = SHARED_FIRST;
1643 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001644 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001645 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001646 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001647 if( IS_LOCK_ERROR(rc) ){
1648 pFile->lastErrno = tErrno;
1649 }
1650 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001651 }
drh7ed97b92010-01-20 13:07:21 +00001652 lock.l_type = F_RDLCK;
1653 lock.l_whence = SEEK_SET;
1654 lock.l_start = SHARED_FIRST;
1655 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001656 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001657 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001658 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1659 if( IS_LOCK_ERROR(rc) ){
1660 pFile->lastErrno = tErrno;
1661 }
1662 goto end_unlock;
1663 }
1664 lock.l_type = F_UNLCK;
1665 lock.l_whence = SEEK_SET;
1666 lock.l_start = SHARED_FIRST+divSize;
1667 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001668 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001669 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001670 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001671 if( IS_LOCK_ERROR(rc) ){
1672 pFile->lastErrno = tErrno;
1673 }
1674 goto end_unlock;
1675 }
drh30f776f2011-02-25 03:25:07 +00001676 }else
1677#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1678 {
drh7ed97b92010-01-20 13:07:21 +00001679 lock.l_type = F_RDLCK;
1680 lock.l_whence = SEEK_SET;
1681 lock.l_start = SHARED_FIRST;
1682 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001683 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001684 /* In theory, the call to unixFileLock() cannot fail because another
1685 ** process is holding an incompatible lock. If it does, this
1686 ** indicates that the other process is not following the locking
1687 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1688 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1689 ** an assert to fail). */
1690 rc = SQLITE_IOERR_RDLOCK;
1691 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001692 goto end_unlock;
1693 }
drh9c105bb2004-10-02 20:38:28 +00001694 }
1695 }
drhbbd42a62004-05-22 17:41:58 +00001696 lock.l_type = F_UNLCK;
1697 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001698 lock.l_start = PENDING_BYTE;
1699 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001700 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001701 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001702 }else{
danea83bc62011-04-01 11:56:32 +00001703 rc = SQLITE_IOERR_UNLOCK;
1704 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001705 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001706 }
drhbbd42a62004-05-22 17:41:58 +00001707 }
drh308c2a52010-05-14 11:30:18 +00001708 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001709 /* Decrement the shared lock counter. Release the lock using an
1710 ** OS call only when all threads in this same process have released
1711 ** the lock.
1712 */
drh8af6c222010-05-14 12:43:01 +00001713 pInode->nShared--;
1714 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001715 lock.l_type = F_UNLCK;
1716 lock.l_whence = SEEK_SET;
1717 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001718 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001719 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001720 }else{
danea83bc62011-04-01 11:56:32 +00001721 rc = SQLITE_IOERR_UNLOCK;
1722 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001723 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001724 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001725 }
drha6abd042004-06-09 17:37:22 +00001726 }
1727
drhbbd42a62004-05-22 17:41:58 +00001728 /* Decrement the count of locks against this same file. When the
1729 ** count reaches zero, close any other file descriptors whose close
1730 ** was deferred because of outstanding locks.
1731 */
drh8af6c222010-05-14 12:43:01 +00001732 pInode->nLock--;
1733 assert( pInode->nLock>=0 );
1734 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001735 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001736 }
1737 }
aswift5b1a2562008-08-22 00:22:35 +00001738
1739end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001740 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001741 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001742 return rc;
drhbbd42a62004-05-22 17:41:58 +00001743}
1744
1745/*
drh308c2a52010-05-14 11:30:18 +00001746** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001747** must be either NO_LOCK or SHARED_LOCK.
1748**
1749** If the locking level of the file descriptor is already at or below
1750** the requested locking level, this routine is a no-op.
1751*/
drh308c2a52010-05-14 11:30:18 +00001752static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001753 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001754}
1755
1756/*
danielk1977e339d652008-06-28 11:23:00 +00001757** This function performs the parts of the "close file" operation
1758** common to all locking schemes. It closes the directory and file
1759** handles, if they are valid, and sets all fields of the unixFile
1760** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001761**
1762** It is *not* necessary to hold the mutex when this routine is called,
1763** even on VxWorks. A mutex will be acquired on VxWorks by the
1764** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001765*/
1766static int closeUnixFile(sqlite3_file *id){
1767 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001768 if( pFile->h>=0 ){
1769 robust_close(pFile, pFile->h, __LINE__);
1770 pFile->h = -1;
1771 }
1772#if OS_VXWORKS
1773 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001774 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001775 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001776 }
1777 vxworksReleaseFileId(pFile->pId);
1778 pFile->pId = 0;
1779 }
1780#endif
1781 OSTRACE(("CLOSE %-3d\n", pFile->h));
1782 OpenCounter(-1);
1783 sqlite3_free(pFile->pUnused);
1784 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001785 return SQLITE_OK;
1786}
1787
1788/*
danielk1977e3026632004-06-22 11:29:02 +00001789** Close a file.
1790*/
danielk197762079062007-08-15 17:08:46 +00001791static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001792 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001793 unixFile *pFile = (unixFile *)id;
1794 unixUnlock(id, NO_LOCK);
1795 unixEnterMutex();
1796
1797 /* unixFile.pInode is always valid here. Otherwise, a different close
1798 ** routine (e.g. nolockClose()) would be called instead.
1799 */
1800 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1801 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1802 /* If there are outstanding locks, do not actually close the file just
1803 ** yet because that would clear those locks. Instead, add the file
1804 ** descriptor to pInode->pUnused list. It will be automatically closed
1805 ** when the last lock is cleared.
1806 */
1807 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001808 }
dan661d71a2011-03-30 19:08:03 +00001809 releaseInodeInfo(pFile);
1810 rc = closeUnixFile(id);
1811 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001812 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001813}
1814
drh734c9862008-11-28 15:37:20 +00001815/************** End of the posix advisory lock implementation *****************
1816******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001817
drh734c9862008-11-28 15:37:20 +00001818/******************************************************************************
1819****************************** No-op Locking **********************************
1820**
1821** Of the various locking implementations available, this is by far the
1822** simplest: locking is ignored. No attempt is made to lock the database
1823** file for reading or writing.
1824**
1825** This locking mode is appropriate for use on read-only databases
1826** (ex: databases that are burned into CD-ROM, for example.) It can
1827** also be used if the application employs some external mechanism to
1828** prevent simultaneous access of the same database by two or more
1829** database connections. But there is a serious risk of database
1830** corruption if this locking mode is used in situations where multiple
1831** database connections are accessing the same database file at the same
1832** time and one or more of those connections are writing.
1833*/
drhbfe66312006-10-03 17:40:40 +00001834
drh734c9862008-11-28 15:37:20 +00001835static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1836 UNUSED_PARAMETER(NotUsed);
1837 *pResOut = 0;
1838 return SQLITE_OK;
1839}
drh734c9862008-11-28 15:37:20 +00001840static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1841 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1842 return SQLITE_OK;
1843}
drh734c9862008-11-28 15:37:20 +00001844static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1845 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1846 return SQLITE_OK;
1847}
1848
1849/*
drh9b35ea62008-11-29 02:20:26 +00001850** Close the file.
drh734c9862008-11-28 15:37:20 +00001851*/
1852static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001853 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001854}
1855
1856/******************* End of the no-op lock implementation *********************
1857******************************************************************************/
1858
1859/******************************************************************************
1860************************* Begin dot-file Locking ******************************
1861**
drh0c2694b2009-09-03 16:23:44 +00001862** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001863** files (really a directory) to control access to the database. This works
1864** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001865**
1866** (1) There is zero concurrency. A single reader blocks all other
1867** connections from reading or writing the database.
1868**
1869** (2) An application crash or power loss can leave stale lock files
1870** sitting around that need to be cleared manually.
1871**
1872** Nevertheless, a dotlock is an appropriate locking mode for use if no
1873** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001874**
drh9ef6bc42011-11-04 02:24:02 +00001875** Dotfile locking works by creating a subdirectory in the same directory as
1876** the database and with the same name but with a ".lock" extension added.
1877** The existance of a lock directory implies an EXCLUSIVE lock. All other
1878** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001879*/
1880
1881/*
1882** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001883** lock directory.
drh734c9862008-11-28 15:37:20 +00001884*/
1885#define DOTLOCK_SUFFIX ".lock"
1886
drh7708e972008-11-29 00:56:52 +00001887/*
1888** This routine checks if there is a RESERVED lock held on the specified
1889** file by this or any other process. If such a lock is held, set *pResOut
1890** to a non-zero value otherwise *pResOut is set to zero. The return value
1891** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1892**
1893** In dotfile locking, either a lock exists or it does not. So in this
1894** variation of CheckReservedLock(), *pResOut is set to true if any lock
1895** is held on the file and false if the file is unlocked.
1896*/
drh734c9862008-11-28 15:37:20 +00001897static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1898 int rc = SQLITE_OK;
1899 int reserved = 0;
1900 unixFile *pFile = (unixFile*)id;
1901
1902 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1903
1904 assert( pFile );
1905
1906 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001907 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001908 /* Either this connection or some other connection in the same process
1909 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001910 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001911 }else{
1912 /* The lock is held if and only if the lockfile exists */
1913 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001914 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001915 }
drh308c2a52010-05-14 11:30:18 +00001916 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001917 *pResOut = reserved;
1918 return rc;
1919}
1920
drh7708e972008-11-29 00:56:52 +00001921/*
drh308c2a52010-05-14 11:30:18 +00001922** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001923** of the following:
1924**
1925** (1) SHARED_LOCK
1926** (2) RESERVED_LOCK
1927** (3) PENDING_LOCK
1928** (4) EXCLUSIVE_LOCK
1929**
1930** Sometimes when requesting one lock state, additional lock states
1931** are inserted in between. The locking might fail on one of the later
1932** transitions leaving the lock state different from what it started but
1933** still short of its goal. The following chart shows the allowed
1934** transitions and the inserted intermediate states:
1935**
1936** UNLOCKED -> SHARED
1937** SHARED -> RESERVED
1938** SHARED -> (PENDING) -> EXCLUSIVE
1939** RESERVED -> (PENDING) -> EXCLUSIVE
1940** PENDING -> EXCLUSIVE
1941**
1942** This routine will only increase a lock. Use the sqlite3OsUnlock()
1943** routine to lower a locking level.
1944**
1945** With dotfile locking, we really only support state (4): EXCLUSIVE.
1946** But we track the other locking levels internally.
1947*/
drh308c2a52010-05-14 11:30:18 +00001948static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001949 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00001950 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00001951 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001952
drh7708e972008-11-29 00:56:52 +00001953
1954 /* If we have any lock, then the lock file already exists. All we have
1955 ** to do is adjust our internal record of the lock level.
1956 */
drh308c2a52010-05-14 11:30:18 +00001957 if( pFile->eFileLock > NO_LOCK ){
1958 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001959 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00001960#ifdef HAVE_UTIME
1961 utime(zLockFile, NULL);
1962#else
drh734c9862008-11-28 15:37:20 +00001963 utimes(zLockFile, NULL);
1964#endif
drh7708e972008-11-29 00:56:52 +00001965 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00001966 }
1967
1968 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00001969 rc = osMkdir(zLockFile, 0777);
1970 if( rc<0 ){
1971 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00001972 int tErrno = errno;
1973 if( EEXIST == tErrno ){
1974 rc = SQLITE_BUSY;
1975 } else {
1976 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1977 if( IS_LOCK_ERROR(rc) ){
1978 pFile->lastErrno = tErrno;
1979 }
1980 }
drh7708e972008-11-29 00:56:52 +00001981 return rc;
drh734c9862008-11-28 15:37:20 +00001982 }
drh734c9862008-11-28 15:37:20 +00001983
1984 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00001985 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00001986 return rc;
1987}
1988
drh7708e972008-11-29 00:56:52 +00001989/*
drh308c2a52010-05-14 11:30:18 +00001990** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00001991** must be either NO_LOCK or SHARED_LOCK.
1992**
1993** If the locking level of the file descriptor is already at or below
1994** the requested locking level, this routine is a no-op.
1995**
1996** When the locking level reaches NO_LOCK, delete the lock file.
1997*/
drh308c2a52010-05-14 11:30:18 +00001998static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001999 unixFile *pFile = (unixFile*)id;
2000 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002001 int rc;
drh734c9862008-11-28 15:37:20 +00002002
2003 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002004 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
2005 pFile->eFileLock, getpid()));
2006 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002007
2008 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002009 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002010 return SQLITE_OK;
2011 }
drh7708e972008-11-29 00:56:52 +00002012
2013 /* To downgrade to shared, simply update our internal notion of the
2014 ** lock state. No need to mess with the file on disk.
2015 */
drh308c2a52010-05-14 11:30:18 +00002016 if( eFileLock==SHARED_LOCK ){
2017 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002018 return SQLITE_OK;
2019 }
2020
drh7708e972008-11-29 00:56:52 +00002021 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002022 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002023 rc = osRmdir(zLockFile);
2024 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2025 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002026 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002027 rc = 0;
drh734c9862008-11-28 15:37:20 +00002028 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002029 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002030 }
2031 if( IS_LOCK_ERROR(rc) ){
2032 pFile->lastErrno = tErrno;
2033 }
2034 return rc;
2035 }
drh308c2a52010-05-14 11:30:18 +00002036 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002037 return SQLITE_OK;
2038}
2039
2040/*
drh9b35ea62008-11-29 02:20:26 +00002041** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002042*/
2043static int dotlockClose(sqlite3_file *id) {
2044 int rc;
2045 if( id ){
2046 unixFile *pFile = (unixFile*)id;
2047 dotlockUnlock(id, NO_LOCK);
2048 sqlite3_free(pFile->lockingContext);
2049 }
drh734c9862008-11-28 15:37:20 +00002050 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002051 return rc;
2052}
2053/****************** End of the dot-file lock implementation *******************
2054******************************************************************************/
2055
2056/******************************************************************************
2057************************** Begin flock Locking ********************************
2058**
2059** Use the flock() system call to do file locking.
2060**
drh6b9d6dd2008-12-03 19:34:47 +00002061** flock() locking is like dot-file locking in that the various
2062** fine-grain locking levels supported by SQLite are collapsed into
2063** a single exclusive lock. In other words, SHARED, RESERVED, and
2064** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2065** still works when you do this, but concurrency is reduced since
2066** only a single process can be reading the database at a time.
2067**
drh734c9862008-11-28 15:37:20 +00002068** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2069** compiling for VXWORKS.
2070*/
2071#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002072
drh6b9d6dd2008-12-03 19:34:47 +00002073/*
drhff812312011-02-23 13:33:46 +00002074** Retry flock() calls that fail with EINTR
2075*/
2076#ifdef EINTR
2077static int robust_flock(int fd, int op){
2078 int rc;
2079 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2080 return rc;
2081}
2082#else
drh5c819272011-02-23 14:00:12 +00002083# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002084#endif
2085
2086
2087/*
drh6b9d6dd2008-12-03 19:34:47 +00002088** This routine checks if there is a RESERVED lock held on the specified
2089** file by this or any other process. If such a lock is held, set *pResOut
2090** to a non-zero value otherwise *pResOut is set to zero. The return value
2091** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2092*/
drh734c9862008-11-28 15:37:20 +00002093static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2094 int rc = SQLITE_OK;
2095 int reserved = 0;
2096 unixFile *pFile = (unixFile*)id;
2097
2098 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2099
2100 assert( pFile );
2101
2102 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002103 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002104 reserved = 1;
2105 }
2106
2107 /* Otherwise see if some other process holds it. */
2108 if( !reserved ){
2109 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002110 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002111 if( !lrc ){
2112 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002113 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002114 if ( lrc ) {
2115 int tErrno = errno;
2116 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002117 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002118 if( IS_LOCK_ERROR(lrc) ){
2119 pFile->lastErrno = tErrno;
2120 rc = lrc;
2121 }
2122 }
2123 } else {
2124 int tErrno = errno;
2125 reserved = 1;
2126 /* someone else might have it reserved */
2127 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2128 if( IS_LOCK_ERROR(lrc) ){
2129 pFile->lastErrno = tErrno;
2130 rc = lrc;
2131 }
2132 }
2133 }
drh308c2a52010-05-14 11:30:18 +00002134 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002135
2136#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2137 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2138 rc = SQLITE_OK;
2139 reserved=1;
2140 }
2141#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2142 *pResOut = reserved;
2143 return rc;
2144}
2145
drh6b9d6dd2008-12-03 19:34:47 +00002146/*
drh308c2a52010-05-14 11:30:18 +00002147** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002148** of the following:
2149**
2150** (1) SHARED_LOCK
2151** (2) RESERVED_LOCK
2152** (3) PENDING_LOCK
2153** (4) EXCLUSIVE_LOCK
2154**
2155** Sometimes when requesting one lock state, additional lock states
2156** are inserted in between. The locking might fail on one of the later
2157** transitions leaving the lock state different from what it started but
2158** still short of its goal. The following chart shows the allowed
2159** transitions and the inserted intermediate states:
2160**
2161** UNLOCKED -> SHARED
2162** SHARED -> RESERVED
2163** SHARED -> (PENDING) -> EXCLUSIVE
2164** RESERVED -> (PENDING) -> EXCLUSIVE
2165** PENDING -> EXCLUSIVE
2166**
2167** flock() only really support EXCLUSIVE locks. We track intermediate
2168** lock states in the sqlite3_file structure, but all locks SHARED or
2169** above are really EXCLUSIVE locks and exclude all other processes from
2170** access the file.
2171**
2172** This routine will only increase a lock. Use the sqlite3OsUnlock()
2173** routine to lower a locking level.
2174*/
drh308c2a52010-05-14 11:30:18 +00002175static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002176 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002177 unixFile *pFile = (unixFile*)id;
2178
2179 assert( pFile );
2180
2181 /* if we already have a lock, it is exclusive.
2182 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002183 if (pFile->eFileLock > NO_LOCK) {
2184 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002185 return SQLITE_OK;
2186 }
2187
2188 /* grab an exclusive lock */
2189
drhff812312011-02-23 13:33:46 +00002190 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002191 int tErrno = errno;
2192 /* didn't get, must be busy */
2193 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2194 if( IS_LOCK_ERROR(rc) ){
2195 pFile->lastErrno = tErrno;
2196 }
2197 } else {
2198 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002199 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002200 }
drh308c2a52010-05-14 11:30:18 +00002201 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2202 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002203#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2204 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2205 rc = SQLITE_BUSY;
2206 }
2207#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2208 return rc;
2209}
2210
drh6b9d6dd2008-12-03 19:34:47 +00002211
2212/*
drh308c2a52010-05-14 11:30:18 +00002213** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002214** must be either NO_LOCK or SHARED_LOCK.
2215**
2216** If the locking level of the file descriptor is already at or below
2217** the requested locking level, this routine is a no-op.
2218*/
drh308c2a52010-05-14 11:30:18 +00002219static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002220 unixFile *pFile = (unixFile*)id;
2221
2222 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002223 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2224 pFile->eFileLock, getpid()));
2225 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002226
2227 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002228 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002229 return SQLITE_OK;
2230 }
2231
2232 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002233 if (eFileLock==SHARED_LOCK) {
2234 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002235 return SQLITE_OK;
2236 }
2237
2238 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002239 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002240#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002241 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002242#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002243 return SQLITE_IOERR_UNLOCK;
2244 }else{
drh308c2a52010-05-14 11:30:18 +00002245 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002246 return SQLITE_OK;
2247 }
2248}
2249
2250/*
2251** Close a file.
2252*/
2253static int flockClose(sqlite3_file *id) {
2254 if( id ){
2255 flockUnlock(id, NO_LOCK);
2256 }
2257 return closeUnixFile(id);
2258}
2259
2260#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2261
2262/******************* End of the flock lock implementation *********************
2263******************************************************************************/
2264
2265/******************************************************************************
2266************************ Begin Named Semaphore Locking ************************
2267**
2268** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002269**
2270** Semaphore locking is like dot-lock and flock in that it really only
2271** supports EXCLUSIVE locking. Only a single process can read or write
2272** the database file at a time. This reduces potential concurrency, but
2273** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002274*/
2275#if OS_VXWORKS
2276
drh6b9d6dd2008-12-03 19:34:47 +00002277/*
2278** This routine checks if there is a RESERVED lock held on the specified
2279** file by this or any other process. If such a lock is held, set *pResOut
2280** to a non-zero value otherwise *pResOut is set to zero. The return value
2281** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2282*/
drh734c9862008-11-28 15:37:20 +00002283static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2284 int rc = SQLITE_OK;
2285 int reserved = 0;
2286 unixFile *pFile = (unixFile*)id;
2287
2288 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2289
2290 assert( pFile );
2291
2292 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002293 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002294 reserved = 1;
2295 }
2296
2297 /* Otherwise see if some other process holds it. */
2298 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002299 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002300 struct stat statBuf;
2301
2302 if( sem_trywait(pSem)==-1 ){
2303 int tErrno = errno;
2304 if( EAGAIN != tErrno ){
2305 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2306 pFile->lastErrno = tErrno;
2307 } else {
2308 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002309 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002310 }
2311 }else{
2312 /* we could have it if we want it */
2313 sem_post(pSem);
2314 }
2315 }
drh308c2a52010-05-14 11:30:18 +00002316 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002317
2318 *pResOut = reserved;
2319 return rc;
2320}
2321
drh6b9d6dd2008-12-03 19:34:47 +00002322/*
drh308c2a52010-05-14 11:30:18 +00002323** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002324** of the following:
2325**
2326** (1) SHARED_LOCK
2327** (2) RESERVED_LOCK
2328** (3) PENDING_LOCK
2329** (4) EXCLUSIVE_LOCK
2330**
2331** Sometimes when requesting one lock state, additional lock states
2332** are inserted in between. The locking might fail on one of the later
2333** transitions leaving the lock state different from what it started but
2334** still short of its goal. The following chart shows the allowed
2335** transitions and the inserted intermediate states:
2336**
2337** UNLOCKED -> SHARED
2338** SHARED -> RESERVED
2339** SHARED -> (PENDING) -> EXCLUSIVE
2340** RESERVED -> (PENDING) -> EXCLUSIVE
2341** PENDING -> EXCLUSIVE
2342**
2343** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2344** lock states in the sqlite3_file structure, but all locks SHARED or
2345** above are really EXCLUSIVE locks and exclude all other processes from
2346** access the file.
2347**
2348** This routine will only increase a lock. Use the sqlite3OsUnlock()
2349** routine to lower a locking level.
2350*/
drh308c2a52010-05-14 11:30:18 +00002351static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002352 unixFile *pFile = (unixFile*)id;
2353 int fd;
drh8af6c222010-05-14 12:43:01 +00002354 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002355 int rc = SQLITE_OK;
2356
2357 /* if we already have a lock, it is exclusive.
2358 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002359 if (pFile->eFileLock > NO_LOCK) {
2360 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002361 rc = SQLITE_OK;
2362 goto sem_end_lock;
2363 }
2364
2365 /* lock semaphore now but bail out when already locked. */
2366 if( sem_trywait(pSem)==-1 ){
2367 rc = SQLITE_BUSY;
2368 goto sem_end_lock;
2369 }
2370
2371 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002372 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002373
2374 sem_end_lock:
2375 return rc;
2376}
2377
drh6b9d6dd2008-12-03 19:34:47 +00002378/*
drh308c2a52010-05-14 11:30:18 +00002379** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002380** must be either NO_LOCK or SHARED_LOCK.
2381**
2382** If the locking level of the file descriptor is already at or below
2383** the requested locking level, this routine is a no-op.
2384*/
drh308c2a52010-05-14 11:30:18 +00002385static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002386 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002387 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002388
2389 assert( pFile );
2390 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002391 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2392 pFile->eFileLock, getpid()));
2393 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002394
2395 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002396 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002397 return SQLITE_OK;
2398 }
2399
2400 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002401 if (eFileLock==SHARED_LOCK) {
2402 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404 }
2405
2406 /* no, really unlock. */
2407 if ( sem_post(pSem)==-1 ) {
2408 int rc, tErrno = errno;
2409 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2410 if( IS_LOCK_ERROR(rc) ){
2411 pFile->lastErrno = tErrno;
2412 }
2413 return rc;
2414 }
drh308c2a52010-05-14 11:30:18 +00002415 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002416 return SQLITE_OK;
2417}
2418
2419/*
2420 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002421 */
drh734c9862008-11-28 15:37:20 +00002422static int semClose(sqlite3_file *id) {
2423 if( id ){
2424 unixFile *pFile = (unixFile*)id;
2425 semUnlock(id, NO_LOCK);
2426 assert( pFile );
2427 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002428 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002429 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002430 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002431 }
2432 return SQLITE_OK;
2433}
2434
2435#endif /* OS_VXWORKS */
2436/*
2437** Named semaphore locking is only available on VxWorks.
2438**
2439*************** End of the named semaphore lock implementation ****************
2440******************************************************************************/
2441
2442
2443/******************************************************************************
2444*************************** Begin AFP Locking *********************************
2445**
2446** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2447** on Apple Macintosh computers - both OS9 and OSX.
2448**
2449** Third-party implementations of AFP are available. But this code here
2450** only works on OSX.
2451*/
2452
drhd2cb50b2009-01-09 21:41:17 +00002453#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002454/*
2455** The afpLockingContext structure contains all afp lock specific state
2456*/
drhbfe66312006-10-03 17:40:40 +00002457typedef struct afpLockingContext afpLockingContext;
2458struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002459 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002460 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002461};
2462
2463struct ByteRangeLockPB2
2464{
2465 unsigned long long offset; /* offset to first byte to lock */
2466 unsigned long long length; /* nbr of bytes to lock */
2467 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2468 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2469 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2470 int fd; /* file desc to assoc this lock with */
2471};
2472
drhfd131da2007-08-07 17:13:03 +00002473#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002474
drh6b9d6dd2008-12-03 19:34:47 +00002475/*
2476** This is a utility for setting or clearing a bit-range lock on an
2477** AFP filesystem.
2478**
2479** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2480*/
2481static int afpSetLock(
2482 const char *path, /* Name of the file to be locked or unlocked */
2483 unixFile *pFile, /* Open file descriptor on path */
2484 unsigned long long offset, /* First byte to be locked */
2485 unsigned long long length, /* Number of bytes to lock */
2486 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002487){
drh6b9d6dd2008-12-03 19:34:47 +00002488 struct ByteRangeLockPB2 pb;
2489 int err;
drhbfe66312006-10-03 17:40:40 +00002490
2491 pb.unLockFlag = setLockFlag ? 0 : 1;
2492 pb.startEndFlag = 0;
2493 pb.offset = offset;
2494 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002495 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002496
drh308c2a52010-05-14 11:30:18 +00002497 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002498 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002499 offset, length));
drhbfe66312006-10-03 17:40:40 +00002500 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2501 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002502 int rc;
2503 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002504 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2505 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002506#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2507 rc = SQLITE_BUSY;
2508#else
drh734c9862008-11-28 15:37:20 +00002509 rc = sqliteErrorFromPosixError(tErrno,
2510 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002511#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002512 if( IS_LOCK_ERROR(rc) ){
2513 pFile->lastErrno = tErrno;
2514 }
2515 return rc;
drhbfe66312006-10-03 17:40:40 +00002516 } else {
aswift5b1a2562008-08-22 00:22:35 +00002517 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002518 }
2519}
2520
drh6b9d6dd2008-12-03 19:34:47 +00002521/*
2522** This routine checks if there is a RESERVED lock held on the specified
2523** file by this or any other process. If such a lock is held, set *pResOut
2524** to a non-zero value otherwise *pResOut is set to zero. The return value
2525** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2526*/
danielk1977e339d652008-06-28 11:23:00 +00002527static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002528 int rc = SQLITE_OK;
2529 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002530 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002531 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002532
aswift5b1a2562008-08-22 00:22:35 +00002533 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2534
2535 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002536 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002537 if( context->reserved ){
2538 *pResOut = 1;
2539 return SQLITE_OK;
2540 }
drh8af6c222010-05-14 12:43:01 +00002541 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002542
2543 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002544 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002545 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002546 }
2547
2548 /* Otherwise see if some other process holds it.
2549 */
aswift5b1a2562008-08-22 00:22:35 +00002550 if( !reserved ){
2551 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002552 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002553 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002554 /* if we succeeded in taking the reserved lock, unlock it to restore
2555 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002556 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002557 } else {
2558 /* if we failed to get the lock then someone else must have it */
2559 reserved = 1;
2560 }
2561 if( IS_LOCK_ERROR(lrc) ){
2562 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002563 }
2564 }
drhbfe66312006-10-03 17:40:40 +00002565
drh7ed97b92010-01-20 13:07:21 +00002566 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002567 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002568
2569 *pResOut = reserved;
2570 return rc;
drhbfe66312006-10-03 17:40:40 +00002571}
2572
drh6b9d6dd2008-12-03 19:34:47 +00002573/*
drh308c2a52010-05-14 11:30:18 +00002574** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002575** of the following:
2576**
2577** (1) SHARED_LOCK
2578** (2) RESERVED_LOCK
2579** (3) PENDING_LOCK
2580** (4) EXCLUSIVE_LOCK
2581**
2582** Sometimes when requesting one lock state, additional lock states
2583** are inserted in between. The locking might fail on one of the later
2584** transitions leaving the lock state different from what it started but
2585** still short of its goal. The following chart shows the allowed
2586** transitions and the inserted intermediate states:
2587**
2588** UNLOCKED -> SHARED
2589** SHARED -> RESERVED
2590** SHARED -> (PENDING) -> EXCLUSIVE
2591** RESERVED -> (PENDING) -> EXCLUSIVE
2592** PENDING -> EXCLUSIVE
2593**
2594** This routine will only increase a lock. Use the sqlite3OsUnlock()
2595** routine to lower a locking level.
2596*/
drh308c2a52010-05-14 11:30:18 +00002597static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002598 int rc = SQLITE_OK;
2599 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002600 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002601 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002602
2603 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002604 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2605 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002606 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002607
drhbfe66312006-10-03 17:40:40 +00002608 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002609 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002610 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002611 */
drh308c2a52010-05-14 11:30:18 +00002612 if( pFile->eFileLock>=eFileLock ){
2613 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2614 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002615 return SQLITE_OK;
2616 }
2617
2618 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002619 ** (1) We never move from unlocked to anything higher than shared lock.
2620 ** (2) SQLite never explicitly requests a pendig lock.
2621 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002622 */
drh308c2a52010-05-14 11:30:18 +00002623 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2624 assert( eFileLock!=PENDING_LOCK );
2625 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002626
drh8af6c222010-05-14 12:43:01 +00002627 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002628 */
drh6c7d5c52008-11-21 20:32:33 +00002629 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002630 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002631
2632 /* If some thread using this PID has a lock via a different unixFile*
2633 ** handle that precludes the requested lock, return BUSY.
2634 */
drh8af6c222010-05-14 12:43:01 +00002635 if( (pFile->eFileLock!=pInode->eFileLock &&
2636 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002637 ){
2638 rc = SQLITE_BUSY;
2639 goto afp_end_lock;
2640 }
2641
2642 /* If a SHARED lock is requested, and some thread using this PID already
2643 ** has a SHARED or RESERVED lock, then increment reference counts and
2644 ** return SQLITE_OK.
2645 */
drh308c2a52010-05-14 11:30:18 +00002646 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002647 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002648 assert( eFileLock==SHARED_LOCK );
2649 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002650 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002651 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002652 pInode->nShared++;
2653 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002654 goto afp_end_lock;
2655 }
drhbfe66312006-10-03 17:40:40 +00002656
2657 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002658 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2659 ** be released.
2660 */
drh308c2a52010-05-14 11:30:18 +00002661 if( eFileLock==SHARED_LOCK
2662 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002663 ){
2664 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002665 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002666 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002667 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002668 goto afp_end_lock;
2669 }
2670 }
2671
2672 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002673 ** operating system calls for the specified lock.
2674 */
drh308c2a52010-05-14 11:30:18 +00002675 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002676 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002677 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002678
drh8af6c222010-05-14 12:43:01 +00002679 assert( pInode->nShared==0 );
2680 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002681
2682 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002683 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002684 /* note that the quality of the randomness doesn't matter that much */
2685 lk = random();
drh8af6c222010-05-14 12:43:01 +00002686 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002687 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002688 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002689 if( IS_LOCK_ERROR(lrc1) ){
2690 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002691 }
aswift5b1a2562008-08-22 00:22:35 +00002692 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002693 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002694
aswift5b1a2562008-08-22 00:22:35 +00002695 if( IS_LOCK_ERROR(lrc1) ) {
2696 pFile->lastErrno = lrc1Errno;
2697 rc = lrc1;
2698 goto afp_end_lock;
2699 } else if( IS_LOCK_ERROR(lrc2) ){
2700 rc = lrc2;
2701 goto afp_end_lock;
2702 } else if( lrc1 != SQLITE_OK ) {
2703 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002704 } else {
drh308c2a52010-05-14 11:30:18 +00002705 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002706 pInode->nLock++;
2707 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002708 }
drh8af6c222010-05-14 12:43:01 +00002709 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002710 /* We are trying for an exclusive lock but another thread in this
2711 ** same process is still holding a shared lock. */
2712 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002713 }else{
2714 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2715 ** assumed that there is a SHARED or greater lock on the file
2716 ** already.
2717 */
2718 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002719 assert( 0!=pFile->eFileLock );
2720 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002721 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002722 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002723 if( !failed ){
2724 context->reserved = 1;
2725 }
drhbfe66312006-10-03 17:40:40 +00002726 }
drh308c2a52010-05-14 11:30:18 +00002727 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002728 /* Acquire an EXCLUSIVE lock */
2729
2730 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002731 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002732 */
drh6b9d6dd2008-12-03 19:34:47 +00002733 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002734 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002735 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002736 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002737 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002738 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002739 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002740 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002741 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2742 ** a critical I/O error
2743 */
2744 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2745 SQLITE_IOERR_LOCK;
2746 goto afp_end_lock;
2747 }
2748 }else{
aswift5b1a2562008-08-22 00:22:35 +00002749 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002750 }
2751 }
aswift5b1a2562008-08-22 00:22:35 +00002752 if( failed ){
2753 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002754 }
2755 }
2756
2757 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002758 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002759 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002760 }else if( eFileLock==EXCLUSIVE_LOCK ){
2761 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002762 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002763 }
2764
2765afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002766 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002767 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2768 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002769 return rc;
2770}
2771
2772/*
drh308c2a52010-05-14 11:30:18 +00002773** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002774** must be either NO_LOCK or SHARED_LOCK.
2775**
2776** If the locking level of the file descriptor is already at or below
2777** the requested locking level, this routine is a no-op.
2778*/
drh308c2a52010-05-14 11:30:18 +00002779static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002780 int rc = SQLITE_OK;
2781 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002782 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002783 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2784 int skipShared = 0;
2785#ifdef SQLITE_TEST
2786 int h = pFile->h;
2787#endif
drhbfe66312006-10-03 17:40:40 +00002788
2789 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002790 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002791 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002792 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002793
drh308c2a52010-05-14 11:30:18 +00002794 assert( eFileLock<=SHARED_LOCK );
2795 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002796 return SQLITE_OK;
2797 }
drh6c7d5c52008-11-21 20:32:33 +00002798 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002799 pInode = pFile->pInode;
2800 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002801 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002802 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002803 SimulateIOErrorBenign(1);
2804 SimulateIOError( h=(-1) )
2805 SimulateIOErrorBenign(0);
2806
2807#ifndef NDEBUG
2808 /* When reducing a lock such that other processes can start
2809 ** reading the database file again, make sure that the
2810 ** transaction counter was updated if any part of the database
2811 ** file changed. If the transaction counter is not updated,
2812 ** other connections to the same file might not realize that
2813 ** the file has changed and hence might not know to flush their
2814 ** cache. The use of a stale cache can lead to database corruption.
2815 */
2816 assert( pFile->inNormalWrite==0
2817 || pFile->dbUpdate==0
2818 || pFile->transCntrChng==1 );
2819 pFile->inNormalWrite = 0;
2820#endif
aswiftaebf4132008-11-21 00:10:35 +00002821
drh308c2a52010-05-14 11:30:18 +00002822 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002823 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002824 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002825 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002826 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002827 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2828 } else {
2829 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002830 }
2831 }
drh308c2a52010-05-14 11:30:18 +00002832 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002833 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002834 }
drh308c2a52010-05-14 11:30:18 +00002835 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002836 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2837 if( !rc ){
2838 context->reserved = 0;
2839 }
aswiftaebf4132008-11-21 00:10:35 +00002840 }
drh8af6c222010-05-14 12:43:01 +00002841 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2842 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002843 }
aswiftaebf4132008-11-21 00:10:35 +00002844 }
drh308c2a52010-05-14 11:30:18 +00002845 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002846
drh7ed97b92010-01-20 13:07:21 +00002847 /* Decrement the shared lock counter. Release the lock using an
2848 ** OS call only when all threads in this same process have released
2849 ** the lock.
2850 */
drh8af6c222010-05-14 12:43:01 +00002851 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2852 pInode->nShared--;
2853 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002854 SimulateIOErrorBenign(1);
2855 SimulateIOError( h=(-1) )
2856 SimulateIOErrorBenign(0);
2857 if( !skipShared ){
2858 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2859 }
2860 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002861 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002862 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002863 }
2864 }
2865 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002866 pInode->nLock--;
2867 assert( pInode->nLock>=0 );
2868 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002869 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002870 }
2871 }
drhbfe66312006-10-03 17:40:40 +00002872 }
drh7ed97b92010-01-20 13:07:21 +00002873
drh6c7d5c52008-11-21 20:32:33 +00002874 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002875 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002876 return rc;
2877}
2878
2879/*
drh339eb0b2008-03-07 15:34:11 +00002880** Close a file & cleanup AFP specific locking context
2881*/
danielk1977e339d652008-06-28 11:23:00 +00002882static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002883 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002884 if( id ){
2885 unixFile *pFile = (unixFile*)id;
2886 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002887 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002888 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002889 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002890 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002891 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002892 ** the last lock is cleared.
2893 */
dan08da86a2009-08-21 17:18:03 +00002894 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002895 }
danb0ac3e32010-06-16 10:55:42 +00002896 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002897 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002898 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002899 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002900 }
drh7ed97b92010-01-20 13:07:21 +00002901 return rc;
drhbfe66312006-10-03 17:40:40 +00002902}
2903
drhd2cb50b2009-01-09 21:41:17 +00002904#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002905/*
2906** The code above is the AFP lock implementation. The code is specific
2907** to MacOSX and does not work on other unix platforms. No alternative
2908** is available. If you don't compile for a mac, then the "unix-afp"
2909** VFS is not available.
2910**
2911********************* End of the AFP lock implementation **********************
2912******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002913
drh7ed97b92010-01-20 13:07:21 +00002914/******************************************************************************
2915*************************** Begin NFS Locking ********************************/
2916
2917#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2918/*
drh308c2a52010-05-14 11:30:18 +00002919 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002920 ** must be either NO_LOCK or SHARED_LOCK.
2921 **
2922 ** If the locking level of the file descriptor is already at or below
2923 ** the requested locking level, this routine is a no-op.
2924 */
drh308c2a52010-05-14 11:30:18 +00002925static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002926 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002927}
2928
2929#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2930/*
2931** The code above is the NFS lock implementation. The code is specific
2932** to MacOSX and does not work on other unix platforms. No alternative
2933** is available.
2934**
2935********************* End of the NFS lock implementation **********************
2936******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002937
2938/******************************************************************************
2939**************** Non-locking sqlite3_file methods *****************************
2940**
2941** The next division contains implementations for all methods of the
2942** sqlite3_file object other than the locking methods. The locking
2943** methods were defined in divisions above (one locking method per
2944** division). Those methods that are common to all locking modes
2945** are gather together into this division.
2946*/
drhbfe66312006-10-03 17:40:40 +00002947
2948/*
drh734c9862008-11-28 15:37:20 +00002949** Seek to the offset passed as the second argument, then read cnt
2950** bytes into pBuf. Return the number of bytes actually read.
2951**
2952** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2953** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2954** one system to another. Since SQLite does not define USE_PREAD
2955** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2956** See tickets #2741 and #2681.
2957**
2958** To avoid stomping the errno value on a failed read the lastErrno value
2959** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00002960*/
drh734c9862008-11-28 15:37:20 +00002961static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2962 int got;
drh58024642011-11-07 18:16:00 +00002963 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00002964#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00002965 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00002966#endif
drh734c9862008-11-28 15:37:20 +00002967 TIMER_START;
drh58024642011-11-07 18:16:00 +00002968 do{
drh734c9862008-11-28 15:37:20 +00002969#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00002970 got = osPread(id->h, pBuf, cnt, offset);
2971 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002972#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00002973 got = osPread64(id->h, pBuf, cnt, offset);
2974 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00002975#else
drh58024642011-11-07 18:16:00 +00002976 newOffset = lseek(id->h, offset, SEEK_SET);
2977 SimulateIOError( newOffset-- );
2978 if( newOffset!=offset ){
2979 if( newOffset == -1 ){
2980 ((unixFile*)id)->lastErrno = errno;
2981 }else{
2982 ((unixFile*)id)->lastErrno = 0;
2983 }
2984 return -1;
drh734c9862008-11-28 15:37:20 +00002985 }
drh58024642011-11-07 18:16:00 +00002986 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00002987#endif
drh58024642011-11-07 18:16:00 +00002988 if( got==cnt ) break;
2989 if( got<0 ){
2990 if( errno==EINTR ){ got = 1; continue; }
2991 prior = 0;
2992 ((unixFile*)id)->lastErrno = errno;
2993 break;
2994 }else if( got>0 ){
2995 cnt -= got;
2996 offset += got;
2997 prior += got;
2998 pBuf = (void*)(got + (char*)pBuf);
2999 }
3000 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003001 TIMER_END;
drh58024642011-11-07 18:16:00 +00003002 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3003 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3004 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003005}
3006
3007/*
drh734c9862008-11-28 15:37:20 +00003008** Read data from a file into a buffer. Return SQLITE_OK if all
3009** bytes were read successfully and SQLITE_IOERR if anything goes
3010** wrong.
drh339eb0b2008-03-07 15:34:11 +00003011*/
drh734c9862008-11-28 15:37:20 +00003012static int unixRead(
3013 sqlite3_file *id,
3014 void *pBuf,
3015 int amt,
3016 sqlite3_int64 offset
3017){
dan08da86a2009-08-21 17:18:03 +00003018 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003019 int got;
3020 assert( id );
drh08c6d442009-02-09 17:34:07 +00003021
dan08da86a2009-08-21 17:18:03 +00003022 /* If this is a database file (not a journal, master-journal or temp
3023 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003024#if 0
dane946c392009-08-22 11:39:46 +00003025 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003026 || offset>=PENDING_BYTE+512
3027 || offset+amt<=PENDING_BYTE
3028 );
dan7c246102010-04-12 19:00:29 +00003029#endif
drh08c6d442009-02-09 17:34:07 +00003030
dan08da86a2009-08-21 17:18:03 +00003031 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003032 if( got==amt ){
3033 return SQLITE_OK;
3034 }else if( got<0 ){
3035 /* lastErrno set by seekAndRead */
3036 return SQLITE_IOERR_READ;
3037 }else{
dan08da86a2009-08-21 17:18:03 +00003038 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003039 /* Unread parts of the buffer must be zero-filled */
3040 memset(&((char*)pBuf)[got], 0, amt-got);
3041 return SQLITE_IOERR_SHORT_READ;
3042 }
3043}
3044
3045/*
3046** Seek to the offset in id->offset then read cnt bytes into pBuf.
3047** Return the number of bytes actually read. Update the offset.
3048**
3049** To avoid stomping the errno value on a failed write the lastErrno value
3050** is set before returning.
3051*/
3052static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3053 int got;
drh7ed97b92010-01-20 13:07:21 +00003054#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003055 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003056#endif
drh734c9862008-11-28 15:37:20 +00003057 TIMER_START;
3058#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003059 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003060#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003061 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003062#else
drhbd1e50c2011-08-19 14:54:12 +00003063 do{
3064 newOffset = lseek(id->h, offset, SEEK_SET);
3065 SimulateIOError( newOffset-- );
3066 if( newOffset!=offset ){
3067 if( newOffset == -1 ){
3068 ((unixFile*)id)->lastErrno = errno;
3069 }else{
3070 ((unixFile*)id)->lastErrno = 0;
3071 }
3072 return -1;
drh734c9862008-11-28 15:37:20 +00003073 }
drhbd1e50c2011-08-19 14:54:12 +00003074 got = osWrite(id->h, pBuf, cnt);
3075 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003076#endif
3077 TIMER_END;
3078 if( got<0 ){
3079 ((unixFile*)id)->lastErrno = errno;
3080 }
3081
drh308c2a52010-05-14 11:30:18 +00003082 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003083 return got;
3084}
3085
3086
3087/*
3088** Write data from a buffer into a file. Return SQLITE_OK on success
3089** or some other error code on failure.
3090*/
3091static int unixWrite(
3092 sqlite3_file *id,
3093 const void *pBuf,
3094 int amt,
3095 sqlite3_int64 offset
3096){
dan08da86a2009-08-21 17:18:03 +00003097 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003098 int wrote = 0;
3099 assert( id );
3100 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003101
dan08da86a2009-08-21 17:18:03 +00003102 /* If this is a database file (not a journal, master-journal or temp
3103 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003104#if 0
dane946c392009-08-22 11:39:46 +00003105 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003106 || offset>=PENDING_BYTE+512
3107 || offset+amt<=PENDING_BYTE
3108 );
dan7c246102010-04-12 19:00:29 +00003109#endif
drh08c6d442009-02-09 17:34:07 +00003110
drh8f941bc2009-01-14 23:03:40 +00003111#ifndef NDEBUG
3112 /* If we are doing a normal write to a database file (as opposed to
3113 ** doing a hot-journal rollback or a write to some file other than a
3114 ** normal database file) then record the fact that the database
3115 ** has changed. If the transaction counter is modified, record that
3116 ** fact too.
3117 */
dan08da86a2009-08-21 17:18:03 +00003118 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003119 pFile->dbUpdate = 1; /* The database has been modified */
3120 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003121 int rc;
drh8f941bc2009-01-14 23:03:40 +00003122 char oldCntr[4];
3123 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003124 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003125 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003126 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003127 pFile->transCntrChng = 1; /* The transaction counter has changed */
3128 }
3129 }
3130 }
3131#endif
3132
dan08da86a2009-08-21 17:18:03 +00003133 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003134 amt -= wrote;
3135 offset += wrote;
3136 pBuf = &((char*)pBuf)[wrote];
3137 }
3138 SimulateIOError(( wrote=(-1), amt=1 ));
3139 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003140
drh734c9862008-11-28 15:37:20 +00003141 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003142 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003143 /* lastErrno set by seekAndWrite */
3144 return SQLITE_IOERR_WRITE;
3145 }else{
dan08da86a2009-08-21 17:18:03 +00003146 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003147 return SQLITE_FULL;
3148 }
3149 }
dan6e09d692010-07-27 18:34:15 +00003150
drh734c9862008-11-28 15:37:20 +00003151 return SQLITE_OK;
3152}
3153
3154#ifdef SQLITE_TEST
3155/*
3156** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003157** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003158*/
3159int sqlite3_sync_count = 0;
3160int sqlite3_fullsync_count = 0;
3161#endif
3162
3163/*
drh89240432009-03-25 01:06:01 +00003164** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003165** Others do no. To be safe, we will stick with the (slightly slower)
3166** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003167** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003168*/
drh20f8e132011-08-31 21:01:55 +00003169#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003170# define fdatasync fsync
3171#endif
3172
3173/*
3174** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3175** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3176** only available on Mac OS X. But that could change.
3177*/
3178#ifdef F_FULLFSYNC
3179# define HAVE_FULLFSYNC 1
3180#else
3181# define HAVE_FULLFSYNC 0
3182#endif
3183
3184
3185/*
3186** The fsync() system call does not work as advertised on many
3187** unix systems. The following procedure is an attempt to make
3188** it work better.
3189**
3190** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3191** for testing when we want to run through the test suite quickly.
3192** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3193** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3194** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003195**
3196** SQLite sets the dataOnly flag if the size of the file is unchanged.
3197** The idea behind dataOnly is that it should only write the file content
3198** to disk, not the inode. We only set dataOnly if the file size is
3199** unchanged since the file size is part of the inode. However,
3200** Ted Ts'o tells us that fdatasync() will also write the inode if the
3201** file size has changed. The only real difference between fdatasync()
3202** and fsync(), Ted tells us, is that fdatasync() will not flush the
3203** inode if the mtime or owner or other inode attributes have changed.
3204** We only care about the file size, not the other file attributes, so
3205** as far as SQLite is concerned, an fdatasync() is always adequate.
3206** So, we always use fdatasync() if it is available, regardless of
3207** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003208*/
3209static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003210 int rc;
drh734c9862008-11-28 15:37:20 +00003211
3212 /* The following "ifdef/elif/else/" block has the same structure as
3213 ** the one below. It is replicated here solely to avoid cluttering
3214 ** up the real code with the UNUSED_PARAMETER() macros.
3215 */
3216#ifdef SQLITE_NO_SYNC
3217 UNUSED_PARAMETER(fd);
3218 UNUSED_PARAMETER(fullSync);
3219 UNUSED_PARAMETER(dataOnly);
3220#elif HAVE_FULLFSYNC
3221 UNUSED_PARAMETER(dataOnly);
3222#else
3223 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003224 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003225#endif
3226
3227 /* Record the number of times that we do a normal fsync() and
3228 ** FULLSYNC. This is used during testing to verify that this procedure
3229 ** gets called with the correct arguments.
3230 */
3231#ifdef SQLITE_TEST
3232 if( fullSync ) sqlite3_fullsync_count++;
3233 sqlite3_sync_count++;
3234#endif
3235
3236 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3237 ** no-op
3238 */
3239#ifdef SQLITE_NO_SYNC
3240 rc = SQLITE_OK;
3241#elif HAVE_FULLFSYNC
3242 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003243 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003244 }else{
3245 rc = 1;
3246 }
3247 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003248 ** It shouldn't be possible for fullfsync to fail on the local
3249 ** file system (on OSX), so failure indicates that FULLFSYNC
3250 ** isn't supported for this file system. So, attempt an fsync
3251 ** and (for now) ignore the overhead of a superfluous fcntl call.
3252 ** It'd be better to detect fullfsync support once and avoid
3253 ** the fcntl call every time sync is called.
3254 */
drh734c9862008-11-28 15:37:20 +00003255 if( rc ) rc = fsync(fd);
3256
drh7ed97b92010-01-20 13:07:21 +00003257#elif defined(__APPLE__)
3258 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3259 ** so currently we default to the macro that redefines fdatasync to fsync
3260 */
3261 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003262#else
drh0b647ff2009-03-21 14:41:04 +00003263 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003264#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003265 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003266 rc = fsync(fd);
3267 }
drh0b647ff2009-03-21 14:41:04 +00003268#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003269#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3270
3271 if( OS_VXWORKS && rc!= -1 ){
3272 rc = 0;
3273 }
chw97185482008-11-17 08:05:31 +00003274 return rc;
drhbfe66312006-10-03 17:40:40 +00003275}
3276
drh734c9862008-11-28 15:37:20 +00003277/*
drh0059eae2011-08-08 23:48:40 +00003278** Open a file descriptor to the directory containing file zFilename.
3279** If successful, *pFd is set to the opened file descriptor and
3280** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3281** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3282** value.
3283**
drh90315a22011-08-10 01:52:12 +00003284** The directory file descriptor is used for only one thing - to
3285** fsync() a directory to make sure file creation and deletion events
3286** are flushed to disk. Such fsyncs are not needed on newer
3287** journaling filesystems, but are required on older filesystems.
3288**
3289** This routine can be overridden using the xSetSysCall interface.
3290** The ability to override this routine was added in support of the
3291** chromium sandbox. Opening a directory is a security risk (we are
3292** told) so making it overrideable allows the chromium sandbox to
3293** replace this routine with a harmless no-op. To make this routine
3294** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3295** *pFd set to a negative number.
3296**
drh0059eae2011-08-08 23:48:40 +00003297** If SQLITE_OK is returned, the caller is responsible for closing
3298** the file descriptor *pFd using close().
3299*/
3300static int openDirectory(const char *zFilename, int *pFd){
3301 int ii;
3302 int fd = -1;
3303 char zDirname[MAX_PATHNAME+1];
3304
3305 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3306 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3307 if( ii>0 ){
3308 zDirname[ii] = '\0';
3309 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3310 if( fd>=0 ){
3311#ifdef FD_CLOEXEC
3312 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3313#endif
3314 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3315 }
3316 }
3317 *pFd = fd;
3318 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3319}
3320
3321/*
drh734c9862008-11-28 15:37:20 +00003322** Make sure all writes to a particular file are committed to disk.
3323**
3324** If dataOnly==0 then both the file itself and its metadata (file
3325** size, access time, etc) are synced. If dataOnly!=0 then only the
3326** file data is synced.
3327**
3328** Under Unix, also make sure that the directory entry for the file
3329** has been created by fsync-ing the directory that contains the file.
3330** If we do not do this and we encounter a power failure, the directory
3331** entry for the journal might not exist after we reboot. The next
3332** SQLite to access the file will not know that the journal exists (because
3333** the directory entry for the journal was never created) and the transaction
3334** will not roll back - possibly leading to database corruption.
3335*/
3336static int unixSync(sqlite3_file *id, int flags){
3337 int rc;
3338 unixFile *pFile = (unixFile*)id;
3339
3340 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3341 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3342
3343 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3344 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3345 || (flags&0x0F)==SQLITE_SYNC_FULL
3346 );
3347
3348 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3349 ** line is to test that doing so does not cause any problems.
3350 */
3351 SimulateDiskfullError( return SQLITE_FULL );
3352
3353 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003354 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003355 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3356 SimulateIOError( rc=1 );
3357 if( rc ){
3358 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003359 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003360 }
drh0059eae2011-08-08 23:48:40 +00003361
3362 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003363 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3364 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003365 */
3366 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3367 int dirfd;
3368 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003369 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003370 rc = osOpenDirectory(pFile->zPath, &dirfd);
3371 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003372 full_fsync(dirfd, 0, 0);
3373 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003374 }else if( rc==SQLITE_CANTOPEN ){
3375 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003376 }
drh0059eae2011-08-08 23:48:40 +00003377 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003378 }
3379 return rc;
3380}
3381
3382/*
3383** Truncate an open file to a specified size
3384*/
3385static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003386 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003387 int rc;
dan6e09d692010-07-27 18:34:15 +00003388 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003389 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003390
3391 /* If the user has configured a chunk-size for this file, truncate the
3392 ** file so that it consists of an integer number of chunks (i.e. the
3393 ** actual file size after the operation may be larger than the requested
3394 ** size).
3395 */
3396 if( pFile->szChunk ){
3397 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3398 }
3399
drhff812312011-02-23 13:33:46 +00003400 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003401 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003402 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003403 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003404 }else{
drh3313b142009-11-06 04:13:18 +00003405#ifndef NDEBUG
3406 /* If we are doing a normal write to a database file (as opposed to
3407 ** doing a hot-journal rollback or a write to some file other than a
3408 ** normal database file) and we truncate the file to zero length,
3409 ** that effectively updates the change counter. This might happen
3410 ** when restoring a database using the backup API from a zero-length
3411 ** source.
3412 */
dan6e09d692010-07-27 18:34:15 +00003413 if( pFile->inNormalWrite && nByte==0 ){
3414 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003415 }
3416#endif
3417
drh734c9862008-11-28 15:37:20 +00003418 return SQLITE_OK;
3419 }
3420}
3421
3422/*
3423** Determine the current size of a file in bytes
3424*/
3425static int unixFileSize(sqlite3_file *id, i64 *pSize){
3426 int rc;
3427 struct stat buf;
3428 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003429 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003430 SimulateIOError( rc=1 );
3431 if( rc!=0 ){
3432 ((unixFile*)id)->lastErrno = errno;
3433 return SQLITE_IOERR_FSTAT;
3434 }
3435 *pSize = buf.st_size;
3436
drh8af6c222010-05-14 12:43:01 +00003437 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003438 ** writes a single byte into that file in order to work around a bug
3439 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3440 ** layers, we need to report this file size as zero even though it is
3441 ** really 1. Ticket #3260.
3442 */
3443 if( *pSize==1 ) *pSize = 0;
3444
3445
3446 return SQLITE_OK;
3447}
3448
drhd2cb50b2009-01-09 21:41:17 +00003449#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003450/*
3451** Handler for proxy-locking file-control verbs. Defined below in the
3452** proxying locking division.
3453*/
3454static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003455#endif
drh715ff302008-12-03 22:32:44 +00003456
dan502019c2010-07-28 14:26:17 +00003457/*
3458** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003459** file-control operation. Enlarge the database to nBytes in size
3460** (rounded up to the next chunk-size). If the database is already
3461** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003462*/
3463static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003464 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003465 i64 nSize; /* Required file size */
3466 struct stat buf; /* Used to hold return values of fstat() */
3467
drh99ab3b12011-03-02 15:09:07 +00003468 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003469
3470 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3471 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003472
dan502019c2010-07-28 14:26:17 +00003473#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003474 /* The code below is handling the return value of osFallocate()
3475 ** correctly. posix_fallocate() is defined to "returns zero on success,
3476 ** or an error number on failure". See the manpage for details. */
3477 int err;
drhff812312011-02-23 13:33:46 +00003478 do{
dan661d71a2011-03-30 19:08:03 +00003479 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3480 }while( err==EINTR );
3481 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003482#else
3483 /* If the OS does not have posix_fallocate(), fake it. First use
3484 ** ftruncate() to set the file size, then write a single byte to
3485 ** the last byte in each block within the extended region. This
3486 ** is the same technique used by glibc to implement posix_fallocate()
3487 ** on systems that do not have a real fallocate() system call.
3488 */
3489 int nBlk = buf.st_blksize; /* File-system block size */
3490 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003491
drhff812312011-02-23 13:33:46 +00003492 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003493 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003494 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003495 }
3496 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003497 while( iWrite<nSize ){
3498 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3499 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003500 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003501 }
dan502019c2010-07-28 14:26:17 +00003502#endif
3503 }
3504 }
3505
3506 return SQLITE_OK;
3507}
danielk1977ad94b582007-08-20 06:44:22 +00003508
danielk1977e3026632004-06-22 11:29:02 +00003509/*
drhf12b3f62011-12-21 14:42:29 +00003510** If *pArg is inititially negative then this is a query. Set *pArg to
3511** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3512**
3513** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3514*/
3515static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3516 if( *pArg<0 ){
3517 *pArg = (pFile->ctrlFlags & mask)!=0;
3518 }else if( (*pArg)==0 ){
3519 pFile->ctrlFlags &= ~mask;
3520 }else{
3521 pFile->ctrlFlags |= mask;
3522 }
3523}
3524
3525/*
drh9e33c2c2007-08-31 18:34:59 +00003526** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003527*/
drhcc6bb3e2007-08-31 16:11:35 +00003528static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003529 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003530 switch( op ){
3531 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003532 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003533 return SQLITE_OK;
3534 }
drh7708e972008-11-29 00:56:52 +00003535 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003536 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003537 return SQLITE_OK;
3538 }
dan6e09d692010-07-27 18:34:15 +00003539 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003540 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003541 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003542 }
drh9ff27ec2010-05-19 19:26:05 +00003543 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003544 int rc;
3545 SimulateIOErrorBenign(1);
3546 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3547 SimulateIOErrorBenign(0);
3548 return rc;
drhf0b190d2011-07-26 16:03:07 +00003549 }
3550 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003551 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3552 return SQLITE_OK;
3553 }
drhcb15f352011-12-23 01:04:17 +00003554 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3555 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003556 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003557 }
drhde60fc22011-12-14 17:53:36 +00003558 case SQLITE_FCNTL_VFSNAME: {
3559 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3560 return SQLITE_OK;
3561 }
drh8f941bc2009-01-14 23:03:40 +00003562#ifndef NDEBUG
3563 /* The pager calls this method to signal that it has done
3564 ** a rollback and that the database is therefore unchanged and
3565 ** it hence it is OK for the transaction change counter to be
3566 ** unchanged.
3567 */
3568 case SQLITE_FCNTL_DB_UNCHANGED: {
3569 ((unixFile*)id)->dbUpdate = 0;
3570 return SQLITE_OK;
3571 }
3572#endif
drhd2cb50b2009-01-09 21:41:17 +00003573#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003574 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003575 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003576 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003577 }
drhd2cb50b2009-01-09 21:41:17 +00003578#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003579 }
drh0b52b7d2011-01-26 19:46:22 +00003580 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003581}
3582
3583/*
danielk1977a3d4c882007-03-23 10:08:38 +00003584** Return the sector size in bytes of the underlying block device for
3585** the specified file. This is almost always 512 bytes, but may be
3586** larger for some devices.
3587**
3588** SQLite code assumes this function cannot fail. It also assumes that
3589** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003590** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003591** same for both.
3592*/
drh1da88f02011-12-17 16:09:16 +00003593static int unixSectorSize(sqlite3_file *pFile){
drh8942d412012-01-02 18:20:14 +00003594 (void)pFile;
3595 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003596}
3597
danielk197790949c22007-08-17 16:50:38 +00003598/*
drhf12b3f62011-12-21 14:42:29 +00003599** Return the device characteristics for the file.
3600**
drhcb15f352011-12-23 01:04:17 +00003601** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3602** However, that choice is contraversial since technically the underlying
3603** file system does not always provide powersafe overwrites. (In other
3604** words, after a power-loss event, parts of the file that were never
3605** written might end up being altered.) However, non-PSOW behavior is very,
3606** very rare. And asserting PSOW makes a large reduction in the amount
3607** of required I/O for journaling, since a lot of padding is eliminated.
3608** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3609** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003610*/
drhf12b3f62011-12-21 14:42:29 +00003611static int unixDeviceCharacteristics(sqlite3_file *id){
3612 unixFile *p = (unixFile*)id;
drhcb15f352011-12-23 01:04:17 +00003613 if( p->ctrlFlags & UNIXFILE_PSOW ){
3614 return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3615 }else{
3616 return 0;
3617 }
danielk197762079062007-08-15 17:08:46 +00003618}
3619
drhd9e5c4f2010-05-12 18:01:39 +00003620#ifndef SQLITE_OMIT_WAL
3621
3622
3623/*
drhd91c68f2010-05-14 14:52:25 +00003624** Object used to represent an shared memory buffer.
3625**
3626** When multiple threads all reference the same wal-index, each thread
3627** has its own unixShm object, but they all point to a single instance
3628** of this unixShmNode object. In other words, each wal-index is opened
3629** only once per process.
3630**
3631** Each unixShmNode object is connected to a single unixInodeInfo object.
3632** We could coalesce this object into unixInodeInfo, but that would mean
3633** every open file that does not use shared memory (in other words, most
3634** open files) would have to carry around this extra information. So
3635** the unixInodeInfo object contains a pointer to this unixShmNode object
3636** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003637**
3638** unixMutexHeld() must be true when creating or destroying
3639** this object or while reading or writing the following fields:
3640**
3641** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003642**
3643** The following fields are read-only after the object is created:
3644**
3645** fid
3646** zFilename
3647**
drhd91c68f2010-05-14 14:52:25 +00003648** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003649** unixMutexHeld() is true when reading or writing any other field
3650** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003651*/
drhd91c68f2010-05-14 14:52:25 +00003652struct unixShmNode {
3653 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003654 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003655 char *zFilename; /* Name of the mmapped file */
3656 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003657 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003658 u16 nRegion; /* Size of array apRegion */
3659 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003660 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003661 int nRef; /* Number of unixShm objects pointing to this */
3662 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003663#ifdef SQLITE_DEBUG
3664 u8 exclMask; /* Mask of exclusive locks held */
3665 u8 sharedMask; /* Mask of shared locks held */
3666 u8 nextShmId; /* Next available unixShm.id value */
3667#endif
3668};
3669
3670/*
drhd9e5c4f2010-05-12 18:01:39 +00003671** Structure used internally by this VFS to record the state of an
3672** open shared memory connection.
3673**
drhd91c68f2010-05-14 14:52:25 +00003674** The following fields are initialized when this object is created and
3675** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003676**
drhd91c68f2010-05-14 14:52:25 +00003677** unixShm.pFile
3678** unixShm.id
3679**
3680** All other fields are read/write. The unixShm.pFile->mutex must be held
3681** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003682*/
3683struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003684 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3685 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003686 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003687 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003688 u16 sharedMask; /* Mask of shared locks held */
3689 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003690};
3691
3692/*
drhd9e5c4f2010-05-12 18:01:39 +00003693** Constants used for locking
3694*/
drhbd9676c2010-06-23 17:58:38 +00003695#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003696#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003697
drhd9e5c4f2010-05-12 18:01:39 +00003698/*
drh73b64e42010-05-30 19:55:15 +00003699** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003700**
3701** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3702** otherwise.
3703*/
3704static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003705 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3706 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003707 int ofst, /* First byte of the locking range */
3708 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003709){
3710 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003711 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003712
drhd91c68f2010-05-14 14:52:25 +00003713 /* Access to the unixShmNode object is serialized by the caller */
3714 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003715
drh73b64e42010-05-30 19:55:15 +00003716 /* Shared locks never span more than one byte */
3717 assert( n==1 || lockType!=F_RDLCK );
3718
3719 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003720 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003721
drh3cb93392011-03-12 18:10:44 +00003722 if( pShmNode->h>=0 ){
3723 /* Initialize the locking parameters */
3724 memset(&f, 0, sizeof(f));
3725 f.l_type = lockType;
3726 f.l_whence = SEEK_SET;
3727 f.l_start = ofst;
3728 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003729
drh3cb93392011-03-12 18:10:44 +00003730 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3731 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3732 }
drhd9e5c4f2010-05-12 18:01:39 +00003733
3734 /* Update the global lock state and do debug tracing */
3735#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003736 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003737 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003738 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003739 if( rc==SQLITE_OK ){
3740 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003741 OSTRACE(("unlock %d ok", ofst));
3742 pShmNode->exclMask &= ~mask;
3743 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003744 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003745 OSTRACE(("read-lock %d ok", ofst));
3746 pShmNode->exclMask &= ~mask;
3747 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003748 }else{
3749 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003750 OSTRACE(("write-lock %d ok", ofst));
3751 pShmNode->exclMask |= mask;
3752 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003753 }
3754 }else{
3755 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003756 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003757 }else if( lockType==F_RDLCK ){
3758 OSTRACE(("read-lock failed"));
3759 }else{
3760 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003761 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003762 }
3763 }
drh20e1f082010-05-31 16:10:12 +00003764 OSTRACE((" - afterwards %03x,%03x\n",
3765 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003766 }
drhd9e5c4f2010-05-12 18:01:39 +00003767#endif
3768
3769 return rc;
3770}
3771
drhd9e5c4f2010-05-12 18:01:39 +00003772
3773/*
drhd91c68f2010-05-14 14:52:25 +00003774** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003775**
3776** This is not a VFS shared-memory method; it is a utility function called
3777** by VFS shared-memory methods.
3778*/
drhd91c68f2010-05-14 14:52:25 +00003779static void unixShmPurge(unixFile *pFd){
3780 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003781 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003782 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003783 int i;
drhd91c68f2010-05-14 14:52:25 +00003784 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003785 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003786 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003787 if( p->h>=0 ){
3788 munmap(p->apRegion[i], p->szRegion);
3789 }else{
3790 sqlite3_free(p->apRegion[i]);
3791 }
dan13a3cb82010-06-11 19:04:21 +00003792 }
dan18801912010-06-14 14:07:50 +00003793 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003794 if( p->h>=0 ){
3795 robust_close(pFd, p->h, __LINE__);
3796 p->h = -1;
3797 }
drhd91c68f2010-05-14 14:52:25 +00003798 p->pInode->pShmNode = 0;
3799 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003800 }
3801}
3802
3803/*
danda9fe0c2010-07-13 18:44:03 +00003804** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003805** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003806**
drh7234c6d2010-06-19 15:10:09 +00003807** The file used to implement shared-memory is in the same directory
3808** as the open database file and has the same name as the open database
3809** file with the "-shm" suffix added. For example, if the database file
3810** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003811** for shared memory will be called "/home/user1/config.db-shm".
3812**
3813** Another approach to is to use files in /dev/shm or /dev/tmp or an
3814** some other tmpfs mount. But if a file in a different directory
3815** from the database file is used, then differing access permissions
3816** or a chroot() might cause two different processes on the same
3817** database to end up using different files for shared memory -
3818** meaning that their memory would not really be shared - resulting
3819** in database corruption. Nevertheless, this tmpfs file usage
3820** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3821** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3822** option results in an incompatible build of SQLite; builds of SQLite
3823** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3824** same database file at the same time, database corruption will likely
3825** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3826** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003827**
3828** When opening a new shared-memory file, if no other instances of that
3829** file are currently open, in this process or in other processes, then
3830** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003831**
3832** If the original database file (pDbFd) is using the "unix-excl" VFS
3833** that means that an exclusive lock is held on the database file and
3834** that no other processes are able to read or write the database. In
3835** that case, we do not really need shared memory. No shared memory
3836** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003837*/
danda9fe0c2010-07-13 18:44:03 +00003838static int unixOpenSharedMemory(unixFile *pDbFd){
3839 struct unixShm *p = 0; /* The connection to be opened */
3840 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3841 int rc; /* Result code */
3842 unixInodeInfo *pInode; /* The inode of fd */
3843 char *zShmFilename; /* Name of the file used for SHM */
3844 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003845
danda9fe0c2010-07-13 18:44:03 +00003846 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003847 p = sqlite3_malloc( sizeof(*p) );
3848 if( p==0 ) return SQLITE_NOMEM;
3849 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00003850 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003851
danda9fe0c2010-07-13 18:44:03 +00003852 /* Check to see if a unixShmNode object already exists. Reuse an existing
3853 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00003854 */
3855 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00003856 pInode = pDbFd->pInode;
3857 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00003858 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00003859 struct stat sStat; /* fstat() info for database file */
3860
3861 /* Call fstat() to figure out the permissions on the database file. If
3862 ** a new *-shm file is created, an attempt will be made to create it
3863 ** with the same permissions. The actual permissions the file is created
3864 ** with are subject to the current umask setting.
3865 */
drh3cb93392011-03-12 18:10:44 +00003866 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00003867 rc = SQLITE_IOERR_FSTAT;
3868 goto shm_open_err;
3869 }
3870
drha4ced192010-07-15 18:32:40 +00003871#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00003872 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00003873#else
drh52bcde02012-01-03 14:50:45 +00003874 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00003875#endif
drh7234c6d2010-06-19 15:10:09 +00003876 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00003877 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00003878 rc = SQLITE_NOMEM;
3879 goto shm_open_err;
3880 }
drh9cb5a0d2012-01-05 21:19:54 +00003881 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00003882 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00003883#ifdef SQLITE_SHM_DIRECTORY
3884 sqlite3_snprintf(nShmFilename, zShmFilename,
3885 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3886 (u32)sStat.st_ino, (u32)sStat.st_dev);
3887#else
drh7234c6d2010-06-19 15:10:09 +00003888 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00003889 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00003890#endif
drhd91c68f2010-05-14 14:52:25 +00003891 pShmNode->h = -1;
3892 pDbFd->pInode->pShmNode = pShmNode;
3893 pShmNode->pInode = pDbFd->pInode;
3894 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3895 if( pShmNode->mutex==0 ){
3896 rc = SQLITE_NOMEM;
3897 goto shm_open_err;
3898 }
drhd9e5c4f2010-05-12 18:01:39 +00003899
drh3cb93392011-03-12 18:10:44 +00003900 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00003901 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00003902 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00003903 openFlags = O_RDONLY;
3904 pShmNode->isReadonly = 1;
3905 }
3906 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00003907 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00003908 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
3909 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003910 }
drhac7c3ac2012-02-11 19:23:48 +00003911
3912 /* If this process is running as root, make sure that the SHM file
3913 ** is owned by the same user that owns the original database. Otherwise,
3914 ** the original owner will not be able to connect. If this process is
drh3ee34842012-02-11 21:21:17 +00003915 ** not root, the following fchown() will fail, but we don't care. The
3916 ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
3917 ** warnings.
drhac7c3ac2012-02-11 19:23:48 +00003918 */
drh23c4b972012-02-11 23:55:15 +00003919 if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
drh3ee34842012-02-11 21:21:17 +00003920 pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
3921 }
drh3cb93392011-03-12 18:10:44 +00003922
3923 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00003924 ** If not, truncate the file to zero length.
3925 */
3926 rc = SQLITE_OK;
3927 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3928 if( robust_ftruncate(pShmNode->h, 0) ){
3929 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00003930 }
3931 }
drh66dfec8b2011-06-01 20:01:49 +00003932 if( rc==SQLITE_OK ){
3933 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3934 }
3935 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00003936 }
drhd9e5c4f2010-05-12 18:01:39 +00003937 }
3938
drhd91c68f2010-05-14 14:52:25 +00003939 /* Make the new connection a child of the unixShmNode */
3940 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003941#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00003942 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00003943#endif
drhd91c68f2010-05-14 14:52:25 +00003944 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00003945 pDbFd->pShm = p;
3946 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00003947
3948 /* The reference count on pShmNode has already been incremented under
3949 ** the cover of the unixEnterMutex() mutex and the pointer from the
3950 ** new (struct unixShm) object to the pShmNode has been set. All that is
3951 ** left to do is to link the new object into the linked list starting
3952 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3953 ** mutex.
3954 */
3955 sqlite3_mutex_enter(pShmNode->mutex);
3956 p->pNext = pShmNode->pFirst;
3957 pShmNode->pFirst = p;
3958 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00003959 return SQLITE_OK;
3960
3961 /* Jump here on any error */
3962shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00003963 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00003964 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003965 unixLeaveMutex();
3966 return rc;
3967}
3968
3969/*
danda9fe0c2010-07-13 18:44:03 +00003970** This function is called to obtain a pointer to region iRegion of the
3971** shared-memory associated with the database file fd. Shared-memory regions
3972** are numbered starting from zero. Each shared-memory region is szRegion
3973** bytes in size.
3974**
3975** If an error occurs, an error code is returned and *pp is set to NULL.
3976**
3977** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3978** region has not been allocated (by any client, including one running in a
3979** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3980** bExtend is non-zero and the requested shared-memory region has not yet
3981** been allocated, it is allocated by this function.
3982**
3983** If the shared-memory region has already been allocated or is allocated by
3984** this call as described above, then it is mapped into this processes
3985** address space (if it is not already), *pp is set to point to the mapped
3986** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00003987*/
danda9fe0c2010-07-13 18:44:03 +00003988static int unixShmMap(
3989 sqlite3_file *fd, /* Handle open on database file */
3990 int iRegion, /* Region to retrieve */
3991 int szRegion, /* Size of regions */
3992 int bExtend, /* True to extend file if necessary */
3993 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00003994){
danda9fe0c2010-07-13 18:44:03 +00003995 unixFile *pDbFd = (unixFile*)fd;
3996 unixShm *p;
3997 unixShmNode *pShmNode;
3998 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00003999
danda9fe0c2010-07-13 18:44:03 +00004000 /* If the shared-memory file has not yet been opened, open it now. */
4001 if( pDbFd->pShm==0 ){
4002 rc = unixOpenSharedMemory(pDbFd);
4003 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004004 }
drhd9e5c4f2010-05-12 18:01:39 +00004005
danda9fe0c2010-07-13 18:44:03 +00004006 p = pDbFd->pShm;
4007 pShmNode = p->pShmNode;
4008 sqlite3_mutex_enter(pShmNode->mutex);
4009 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004010 assert( pShmNode->pInode==pDbFd->pInode );
4011 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4012 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004013
4014 if( pShmNode->nRegion<=iRegion ){
4015 char **apNew; /* New apRegion[] array */
4016 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4017 struct stat sStat; /* Used by fstat() */
4018
4019 pShmNode->szRegion = szRegion;
4020
drh3cb93392011-03-12 18:10:44 +00004021 if( pShmNode->h>=0 ){
4022 /* The requested region is not mapped into this processes address space.
4023 ** Check to see if it has been allocated (i.e. if the wal-index file is
4024 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004025 */
drh3cb93392011-03-12 18:10:44 +00004026 if( osFstat(pShmNode->h, &sStat) ){
4027 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004028 goto shmpage_out;
4029 }
drh3cb93392011-03-12 18:10:44 +00004030
4031 if( sStat.st_size<nByte ){
4032 /* The requested memory region does not exist. If bExtend is set to
4033 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4034 **
4035 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4036 ** the requested memory region.
4037 */
4038 if( !bExtend ) goto shmpage_out;
4039 if( robust_ftruncate(pShmNode->h, nByte) ){
4040 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4041 pShmNode->zFilename);
4042 goto shmpage_out;
4043 }
4044 }
danda9fe0c2010-07-13 18:44:03 +00004045 }
4046
4047 /* Map the requested memory region into this processes address space. */
4048 apNew = (char **)sqlite3_realloc(
4049 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4050 );
4051 if( !apNew ){
4052 rc = SQLITE_IOERR_NOMEM;
4053 goto shmpage_out;
4054 }
4055 pShmNode->apRegion = apNew;
4056 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004057 void *pMem;
4058 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004059 pMem = mmap(0, szRegion,
4060 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh3cb93392011-03-12 18:10:44 +00004061 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
4062 );
4063 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004064 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004065 goto shmpage_out;
4066 }
4067 }else{
4068 pMem = sqlite3_malloc(szRegion);
4069 if( pMem==0 ){
4070 rc = SQLITE_NOMEM;
4071 goto shmpage_out;
4072 }
4073 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004074 }
4075 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4076 pShmNode->nRegion++;
4077 }
4078 }
4079
4080shmpage_out:
4081 if( pShmNode->nRegion>iRegion ){
4082 *pp = pShmNode->apRegion[iRegion];
4083 }else{
4084 *pp = 0;
4085 }
drh66dfec8b2011-06-01 20:01:49 +00004086 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004087 sqlite3_mutex_leave(pShmNode->mutex);
4088 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004089}
4090
4091/*
drhd9e5c4f2010-05-12 18:01:39 +00004092** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004093**
4094** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4095** different here than in posix. In xShmLock(), one can go from unlocked
4096** to shared and back or from unlocked to exclusive and back. But one may
4097** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004098*/
4099static int unixShmLock(
4100 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004101 int ofst, /* First lock to acquire or release */
4102 int n, /* Number of locks to acquire or release */
4103 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004104){
drh73b64e42010-05-30 19:55:15 +00004105 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4106 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4107 unixShm *pX; /* For looping over all siblings */
4108 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4109 int rc = SQLITE_OK; /* Result code */
4110 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004111
drhd91c68f2010-05-14 14:52:25 +00004112 assert( pShmNode==pDbFd->pInode->pShmNode );
4113 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004114 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004115 assert( n>=1 );
4116 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4117 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4118 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4119 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4120 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004121 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4122 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004123
drhc99597c2010-05-31 01:41:15 +00004124 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004125 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004126 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004127 if( flags & SQLITE_SHM_UNLOCK ){
4128 u16 allMask = 0; /* Mask of locks held by siblings */
4129
4130 /* See if any siblings hold this same lock */
4131 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4132 if( pX==p ) continue;
4133 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4134 allMask |= pX->sharedMask;
4135 }
4136
4137 /* Unlock the system-level locks */
4138 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004139 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004140 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004141 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004142 }
drh73b64e42010-05-30 19:55:15 +00004143
4144 /* Undo the local locks */
4145 if( rc==SQLITE_OK ){
4146 p->exclMask &= ~mask;
4147 p->sharedMask &= ~mask;
4148 }
4149 }else if( flags & SQLITE_SHM_SHARED ){
4150 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4151
4152 /* Find out which shared locks are already held by sibling connections.
4153 ** If any sibling already holds an exclusive lock, go ahead and return
4154 ** SQLITE_BUSY.
4155 */
4156 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004157 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004158 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004159 break;
4160 }
4161 allShared |= pX->sharedMask;
4162 }
4163
4164 /* Get shared locks at the system level, if necessary */
4165 if( rc==SQLITE_OK ){
4166 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004167 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004168 }else{
drh73b64e42010-05-30 19:55:15 +00004169 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004170 }
drhd9e5c4f2010-05-12 18:01:39 +00004171 }
drh73b64e42010-05-30 19:55:15 +00004172
4173 /* Get the local shared locks */
4174 if( rc==SQLITE_OK ){
4175 p->sharedMask |= mask;
4176 }
4177 }else{
4178 /* Make sure no sibling connections hold locks that will block this
4179 ** lock. If any do, return SQLITE_BUSY right away.
4180 */
4181 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004182 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4183 rc = SQLITE_BUSY;
4184 break;
4185 }
4186 }
4187
4188 /* Get the exclusive locks at the system level. Then if successful
4189 ** also mark the local connection as being locked.
4190 */
4191 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004192 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004193 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004194 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004195 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004196 }
drhd9e5c4f2010-05-12 18:01:39 +00004197 }
4198 }
drhd91c68f2010-05-14 14:52:25 +00004199 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004200 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4201 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004202 return rc;
4203}
4204
drh286a2882010-05-20 23:51:06 +00004205/*
4206** Implement a memory barrier or memory fence on shared memory.
4207**
4208** All loads and stores begun before the barrier must complete before
4209** any load or store begun after the barrier.
4210*/
4211static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004212 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004213){
drhff828942010-06-26 21:34:06 +00004214 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004215 unixEnterMutex();
4216 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004217}
4218
dan18801912010-06-14 14:07:50 +00004219/*
danda9fe0c2010-07-13 18:44:03 +00004220** Close a connection to shared-memory. Delete the underlying
4221** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004222**
4223** If there is no shared memory associated with the connection then this
4224** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004225*/
danda9fe0c2010-07-13 18:44:03 +00004226static int unixShmUnmap(
4227 sqlite3_file *fd, /* The underlying database file */
4228 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004229){
danda9fe0c2010-07-13 18:44:03 +00004230 unixShm *p; /* The connection to be closed */
4231 unixShmNode *pShmNode; /* The underlying shared-memory file */
4232 unixShm **pp; /* For looping over sibling connections */
4233 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004234
danda9fe0c2010-07-13 18:44:03 +00004235 pDbFd = (unixFile*)fd;
4236 p = pDbFd->pShm;
4237 if( p==0 ) return SQLITE_OK;
4238 pShmNode = p->pShmNode;
4239
4240 assert( pShmNode==pDbFd->pInode->pShmNode );
4241 assert( pShmNode->pInode==pDbFd->pInode );
4242
4243 /* Remove connection p from the set of connections associated
4244 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004245 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004246 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4247 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004248
danda9fe0c2010-07-13 18:44:03 +00004249 /* Free the connection p */
4250 sqlite3_free(p);
4251 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004252 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004253
4254 /* If pShmNode->nRef has reached 0, then close the underlying
4255 ** shared-memory file, too */
4256 unixEnterMutex();
4257 assert( pShmNode->nRef>0 );
4258 pShmNode->nRef--;
4259 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004260 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004261 unixShmPurge(pDbFd);
4262 }
4263 unixLeaveMutex();
4264
4265 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004266}
drh286a2882010-05-20 23:51:06 +00004267
danda9fe0c2010-07-13 18:44:03 +00004268
drhd9e5c4f2010-05-12 18:01:39 +00004269#else
drh6b017cc2010-06-14 18:01:46 +00004270# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004271# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004272# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004273# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004274#endif /* #ifndef SQLITE_OMIT_WAL */
4275
drh734c9862008-11-28 15:37:20 +00004276/*
4277** Here ends the implementation of all sqlite3_file methods.
4278**
4279********************** End sqlite3_file Methods *******************************
4280******************************************************************************/
4281
4282/*
drh6b9d6dd2008-12-03 19:34:47 +00004283** This division contains definitions of sqlite3_io_methods objects that
4284** implement various file locking strategies. It also contains definitions
4285** of "finder" functions. A finder-function is used to locate the appropriate
4286** sqlite3_io_methods object for a particular database file. The pAppData
4287** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4288** the correct finder-function for that VFS.
4289**
4290** Most finder functions return a pointer to a fixed sqlite3_io_methods
4291** object. The only interesting finder-function is autolockIoFinder, which
4292** looks at the filesystem type and tries to guess the best locking
4293** strategy from that.
4294**
drh1875f7a2008-12-08 18:19:17 +00004295** For finder-funtion F, two objects are created:
4296**
4297** (1) The real finder-function named "FImpt()".
4298**
dane946c392009-08-22 11:39:46 +00004299** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004300**
4301**
4302** A pointer to the F pointer is used as the pAppData value for VFS
4303** objects. We have to do this instead of letting pAppData point
4304** directly at the finder-function since C90 rules prevent a void*
4305** from be cast into a function pointer.
4306**
drh6b9d6dd2008-12-03 19:34:47 +00004307**
drh7708e972008-11-29 00:56:52 +00004308** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004309**
drh7708e972008-11-29 00:56:52 +00004310** * A constant sqlite3_io_methods object call METHOD that has locking
4311** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4312**
4313** * An I/O method finder function called FINDER that returns a pointer
4314** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004315*/
drhd9e5c4f2010-05-12 18:01:39 +00004316#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004317static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004318 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004319 CLOSE, /* xClose */ \
4320 unixRead, /* xRead */ \
4321 unixWrite, /* xWrite */ \
4322 unixTruncate, /* xTruncate */ \
4323 unixSync, /* xSync */ \
4324 unixFileSize, /* xFileSize */ \
4325 LOCK, /* xLock */ \
4326 UNLOCK, /* xUnlock */ \
4327 CKLOCK, /* xCheckReservedLock */ \
4328 unixFileControl, /* xFileControl */ \
4329 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004330 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004331 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004332 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004333 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004334 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004335}; \
drh0c2694b2009-09-03 16:23:44 +00004336static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4337 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004338 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004339} \
drh0c2694b2009-09-03 16:23:44 +00004340static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004341 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004342
4343/*
4344** Here are all of the sqlite3_io_methods objects for each of the
4345** locking strategies. Functions that return pointers to these methods
4346** are also created.
4347*/
4348IOMETHODS(
4349 posixIoFinder, /* Finder function name */
4350 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004351 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004352 unixClose, /* xClose method */
4353 unixLock, /* xLock method */
4354 unixUnlock, /* xUnlock method */
4355 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004356)
drh7708e972008-11-29 00:56:52 +00004357IOMETHODS(
4358 nolockIoFinder, /* Finder function name */
4359 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004360 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004361 nolockClose, /* xClose method */
4362 nolockLock, /* xLock method */
4363 nolockUnlock, /* xUnlock method */
4364 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004365)
drh7708e972008-11-29 00:56:52 +00004366IOMETHODS(
4367 dotlockIoFinder, /* Finder function name */
4368 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004369 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004370 dotlockClose, /* xClose method */
4371 dotlockLock, /* xLock method */
4372 dotlockUnlock, /* xUnlock method */
4373 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004374)
drh7708e972008-11-29 00:56:52 +00004375
chw78a13182009-04-07 05:35:03 +00004376#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004377IOMETHODS(
4378 flockIoFinder, /* Finder function name */
4379 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004380 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004381 flockClose, /* xClose method */
4382 flockLock, /* xLock method */
4383 flockUnlock, /* xUnlock method */
4384 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004385)
drh7708e972008-11-29 00:56:52 +00004386#endif
4387
drh6c7d5c52008-11-21 20:32:33 +00004388#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004389IOMETHODS(
4390 semIoFinder, /* Finder function name */
4391 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004392 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004393 semClose, /* xClose method */
4394 semLock, /* xLock method */
4395 semUnlock, /* xUnlock method */
4396 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004397)
aswiftaebf4132008-11-21 00:10:35 +00004398#endif
drh7708e972008-11-29 00:56:52 +00004399
drhd2cb50b2009-01-09 21:41:17 +00004400#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004401IOMETHODS(
4402 afpIoFinder, /* Finder function name */
4403 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004404 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004405 afpClose, /* xClose method */
4406 afpLock, /* xLock method */
4407 afpUnlock, /* xUnlock method */
4408 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004409)
drh715ff302008-12-03 22:32:44 +00004410#endif
4411
4412/*
4413** The proxy locking method is a "super-method" in the sense that it
4414** opens secondary file descriptors for the conch and lock files and
4415** it uses proxy, dot-file, AFP, and flock() locking methods on those
4416** secondary files. For this reason, the division that implements
4417** proxy locking is located much further down in the file. But we need
4418** to go ahead and define the sqlite3_io_methods and finder function
4419** for proxy locking here. So we forward declare the I/O methods.
4420*/
drhd2cb50b2009-01-09 21:41:17 +00004421#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004422static int proxyClose(sqlite3_file*);
4423static int proxyLock(sqlite3_file*, int);
4424static int proxyUnlock(sqlite3_file*, int);
4425static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004426IOMETHODS(
4427 proxyIoFinder, /* Finder function name */
4428 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004429 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004430 proxyClose, /* xClose method */
4431 proxyLock, /* xLock method */
4432 proxyUnlock, /* xUnlock method */
4433 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004434)
aswiftaebf4132008-11-21 00:10:35 +00004435#endif
drh7708e972008-11-29 00:56:52 +00004436
drh7ed97b92010-01-20 13:07:21 +00004437/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4438#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4439IOMETHODS(
4440 nfsIoFinder, /* Finder function name */
4441 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004442 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004443 unixClose, /* xClose method */
4444 unixLock, /* xLock method */
4445 nfsUnlock, /* xUnlock method */
4446 unixCheckReservedLock /* xCheckReservedLock method */
4447)
4448#endif
drh7708e972008-11-29 00:56:52 +00004449
drhd2cb50b2009-01-09 21:41:17 +00004450#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004451/*
drh6b9d6dd2008-12-03 19:34:47 +00004452** This "finder" function attempts to determine the best locking strategy
4453** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004454** object that implements that strategy.
4455**
4456** This is for MacOSX only.
4457*/
drh1875f7a2008-12-08 18:19:17 +00004458static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004459 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004460 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004461){
4462 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004463 const char *zFilesystem; /* Filesystem type name */
4464 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004465 } aMap[] = {
4466 { "hfs", &posixIoMethods },
4467 { "ufs", &posixIoMethods },
4468 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004469 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004470 { "webdav", &nolockIoMethods },
4471 { 0, 0 }
4472 };
4473 int i;
4474 struct statfs fsInfo;
4475 struct flock lockInfo;
4476
4477 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004478 /* If filePath==NULL that means we are dealing with a transient file
4479 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004480 return &nolockIoMethods;
4481 }
4482 if( statfs(filePath, &fsInfo) != -1 ){
4483 if( fsInfo.f_flags & MNT_RDONLY ){
4484 return &nolockIoMethods;
4485 }
4486 for(i=0; aMap[i].zFilesystem; i++){
4487 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4488 return aMap[i].pMethods;
4489 }
4490 }
4491 }
4492
4493 /* Default case. Handles, amongst others, "nfs".
4494 ** Test byte-range lock using fcntl(). If the call succeeds,
4495 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004496 */
drh7708e972008-11-29 00:56:52 +00004497 lockInfo.l_len = 1;
4498 lockInfo.l_start = 0;
4499 lockInfo.l_whence = SEEK_SET;
4500 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004501 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004502 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4503 return &nfsIoMethods;
4504 } else {
4505 return &posixIoMethods;
4506 }
drh7708e972008-11-29 00:56:52 +00004507 }else{
4508 return &dotlockIoMethods;
4509 }
4510}
drh0c2694b2009-09-03 16:23:44 +00004511static const sqlite3_io_methods
4512 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004513
drhd2cb50b2009-01-09 21:41:17 +00004514#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004515
chw78a13182009-04-07 05:35:03 +00004516#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4517/*
4518** This "finder" function attempts to determine the best locking strategy
4519** for the database file "filePath". It then returns the sqlite3_io_methods
4520** object that implements that strategy.
4521**
4522** This is for VXWorks only.
4523*/
4524static const sqlite3_io_methods *autolockIoFinderImpl(
4525 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004526 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004527){
4528 struct flock lockInfo;
4529
4530 if( !filePath ){
4531 /* If filePath==NULL that means we are dealing with a transient file
4532 ** that does not need to be locked. */
4533 return &nolockIoMethods;
4534 }
4535
4536 /* Test if fcntl() is supported and use POSIX style locks.
4537 ** Otherwise fall back to the named semaphore method.
4538 */
4539 lockInfo.l_len = 1;
4540 lockInfo.l_start = 0;
4541 lockInfo.l_whence = SEEK_SET;
4542 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004543 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004544 return &posixIoMethods;
4545 }else{
4546 return &semIoMethods;
4547 }
4548}
drh0c2694b2009-09-03 16:23:44 +00004549static const sqlite3_io_methods
4550 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004551
4552#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4553
drh7708e972008-11-29 00:56:52 +00004554/*
4555** An abstract type for a pointer to a IO method finder function:
4556*/
drh0c2694b2009-09-03 16:23:44 +00004557typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004558
aswiftaebf4132008-11-21 00:10:35 +00004559
drh734c9862008-11-28 15:37:20 +00004560/****************************************************************************
4561**************************** sqlite3_vfs methods ****************************
4562**
4563** This division contains the implementation of methods on the
4564** sqlite3_vfs object.
4565*/
4566
danielk1977a3d4c882007-03-23 10:08:38 +00004567/*
danielk1977e339d652008-06-28 11:23:00 +00004568** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004569*/
4570static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004571 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004572 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004573 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004574 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004575 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004576){
drh7708e972008-11-29 00:56:52 +00004577 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004578 unixFile *pNew = (unixFile *)pId;
4579 int rc = SQLITE_OK;
4580
drh8af6c222010-05-14 12:43:01 +00004581 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004582
dan00157392010-10-05 11:33:15 +00004583 /* Usually the path zFilename should not be a relative pathname. The
4584 ** exception is when opening the proxy "conch" file in builds that
4585 ** include the special Apple locking styles.
4586 */
dan00157392010-10-05 11:33:15 +00004587#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004588 assert( zFilename==0 || zFilename[0]=='/'
4589 || pVfs->pAppData==(void*)&autolockIoFinder );
4590#else
4591 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004592#endif
dan00157392010-10-05 11:33:15 +00004593
drhb07028f2011-10-14 21:49:18 +00004594 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004595 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004596
drh308c2a52010-05-14 11:30:18 +00004597 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004598 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004599 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004600 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004601 pNew->ctrlFlags = (u8)ctrlFlags;
4602 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4603 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004604 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004605 }
drha7e61d82011-03-12 17:02:57 +00004606 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004607 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004608 }
drh339eb0b2008-03-07 15:34:11 +00004609
drh6c7d5c52008-11-21 20:32:33 +00004610#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004611 pNew->pId = vxworksFindFileId(zFilename);
4612 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004613 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004614 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004615 }
4616#endif
4617
drhc02a43a2012-01-10 23:18:38 +00004618 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004619 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004620 }else{
drh0c2694b2009-09-03 16:23:44 +00004621 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004622#if SQLITE_ENABLE_LOCKING_STYLE
4623 /* Cache zFilename in the locking context (AFP and dotlock override) for
4624 ** proxyLock activation is possible (remote proxy is based on db name)
4625 ** zFilename remains valid until file is closed, to support */
4626 pNew->lockingContext = (void*)zFilename;
4627#endif
drhda0e7682008-07-30 15:27:54 +00004628 }
danielk1977e339d652008-06-28 11:23:00 +00004629
drh7ed97b92010-01-20 13:07:21 +00004630 if( pLockingStyle == &posixIoMethods
4631#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4632 || pLockingStyle == &nfsIoMethods
4633#endif
4634 ){
drh7708e972008-11-29 00:56:52 +00004635 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004636 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004637 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004638 /* If an error occured in findInodeInfo(), close the file descriptor
4639 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004640 ** in two scenarios:
4641 **
4642 ** (a) A call to fstat() failed.
4643 ** (b) A malloc failed.
4644 **
4645 ** Scenario (b) may only occur if the process is holding no other
4646 ** file descriptors open on the same file. If there were other file
4647 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004648 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004649 ** handle h - as it is guaranteed that no posix locks will be released
4650 ** by doing so.
4651 **
4652 ** If scenario (a) caused the error then things are not so safe. The
4653 ** implicit assumption here is that if fstat() fails, things are in
4654 ** such bad shape that dropping a lock or two doesn't matter much.
4655 */
drh0e9365c2011-03-02 02:08:13 +00004656 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004657 h = -1;
4658 }
drh7708e972008-11-29 00:56:52 +00004659 unixLeaveMutex();
4660 }
danielk1977e339d652008-06-28 11:23:00 +00004661
drhd2cb50b2009-01-09 21:41:17 +00004662#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004663 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004664 /* AFP locking uses the file path so it needs to be included in
4665 ** the afpLockingContext.
4666 */
4667 afpLockingContext *pCtx;
4668 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4669 if( pCtx==0 ){
4670 rc = SQLITE_NOMEM;
4671 }else{
4672 /* NB: zFilename exists and remains valid until the file is closed
4673 ** according to requirement F11141. So we do not need to make a
4674 ** copy of the filename. */
4675 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004676 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004677 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004678 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004679 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004680 if( rc!=SQLITE_OK ){
4681 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004682 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004683 h = -1;
4684 }
drh7708e972008-11-29 00:56:52 +00004685 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004686 }
drh7708e972008-11-29 00:56:52 +00004687 }
4688#endif
danielk1977e339d652008-06-28 11:23:00 +00004689
drh7708e972008-11-29 00:56:52 +00004690 else if( pLockingStyle == &dotlockIoMethods ){
4691 /* Dotfile locking uses the file path so it needs to be included in
4692 ** the dotlockLockingContext
4693 */
4694 char *zLockFile;
4695 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004696 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004697 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004698 zLockFile = (char *)sqlite3_malloc(nFilename);
4699 if( zLockFile==0 ){
4700 rc = SQLITE_NOMEM;
4701 }else{
4702 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004703 }
drh7708e972008-11-29 00:56:52 +00004704 pNew->lockingContext = zLockFile;
4705 }
danielk1977e339d652008-06-28 11:23:00 +00004706
drh6c7d5c52008-11-21 20:32:33 +00004707#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004708 else if( pLockingStyle == &semIoMethods ){
4709 /* Named semaphore locking uses the file path so it needs to be
4710 ** included in the semLockingContext
4711 */
4712 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004713 rc = findInodeInfo(pNew, &pNew->pInode);
4714 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4715 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004716 int n;
drh2238dcc2009-08-27 17:56:20 +00004717 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004718 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004719 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004720 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004721 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4722 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004723 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004724 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004725 }
chw97185482008-11-17 08:05:31 +00004726 }
drh7708e972008-11-29 00:56:52 +00004727 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004728 }
drh7708e972008-11-29 00:56:52 +00004729#endif
aswift5b1a2562008-08-22 00:22:35 +00004730
4731 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004732#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004733 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004734 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004735 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004736 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004737 isDelete = 0;
4738 }
drhc02a43a2012-01-10 23:18:38 +00004739 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004740#endif
danielk1977e339d652008-06-28 11:23:00 +00004741 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004742 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004743 }else{
drh7708e972008-11-29 00:56:52 +00004744 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004745 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004746 }
danielk1977e339d652008-06-28 11:23:00 +00004747 return rc;
drh054889e2005-11-30 03:20:31 +00004748}
drh9c06c952005-11-26 00:25:00 +00004749
danielk1977ad94b582007-08-20 06:44:22 +00004750/*
drh8b3cf822010-06-01 21:02:51 +00004751** Return the name of a directory in which to put temporary files.
4752** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004753*/
drh7234c6d2010-06-19 15:10:09 +00004754static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004755 static const char *azDirs[] = {
4756 0,
aswiftaebf4132008-11-21 00:10:35 +00004757 0,
danielk197717b90b52008-06-06 11:11:25 +00004758 "/var/tmp",
4759 "/usr/tmp",
4760 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004761 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004762 };
drh8b3cf822010-06-01 21:02:51 +00004763 unsigned int i;
4764 struct stat buf;
4765 const char *zDir = 0;
4766
4767 azDirs[0] = sqlite3_temp_directory;
4768 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004769 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004770 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004771 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004772 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004773 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004774 break;
4775 }
4776 return zDir;
4777}
4778
4779/*
4780** Create a temporary file name in zBuf. zBuf must be allocated
4781** by the calling process and must be big enough to hold at least
4782** pVfs->mxPathname bytes.
4783*/
4784static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004785 static const unsigned char zChars[] =
4786 "abcdefghijklmnopqrstuvwxyz"
4787 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4788 "0123456789";
drh41022642008-11-21 00:24:42 +00004789 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004790 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004791
4792 /* It's odd to simulate an io-error here, but really this is just
4793 ** using the io-error infrastructure to test that SQLite handles this
4794 ** function failing.
4795 */
4796 SimulateIOError( return SQLITE_IOERR );
4797
drh7234c6d2010-06-19 15:10:09 +00004798 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004799 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004800
4801 /* Check that the output buffer is large enough for the temporary file
4802 ** name. If it is not, return SQLITE_ERROR.
4803 */
drhc02a43a2012-01-10 23:18:38 +00004804 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004805 return SQLITE_ERROR;
4806 }
4807
4808 do{
drhc02a43a2012-01-10 23:18:38 +00004809 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004810 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004811 sqlite3_randomness(15, &zBuf[j]);
4812 for(i=0; i<15; i++, j++){
4813 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4814 }
4815 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004816 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004817 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004818 return SQLITE_OK;
4819}
4820
drhd2cb50b2009-01-09 21:41:17 +00004821#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004822/*
4823** Routine to transform a unixFile into a proxy-locking unixFile.
4824** Implementation in the proxy-lock division, but used by unixOpen()
4825** if SQLITE_PREFER_PROXY_LOCKING is defined.
4826*/
4827static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004828#endif
drhc66d5b62008-12-03 22:48:32 +00004829
dan08da86a2009-08-21 17:18:03 +00004830/*
4831** Search for an unused file descriptor that was opened on the database
4832** file (not a journal or master-journal file) identified by pathname
4833** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4834** argument to this function.
4835**
4836** Such a file descriptor may exist if a database connection was closed
4837** but the associated file descriptor could not be closed because some
4838** other file descriptor open on the same file is holding a file-lock.
4839** Refer to comments in the unixClose() function and the lengthy comment
4840** describing "Posix Advisory Locking" at the start of this file for
4841** further details. Also, ticket #4018.
4842**
4843** If a suitable file descriptor is found, then it is returned. If no
4844** such file descriptor is located, -1 is returned.
4845*/
dane946c392009-08-22 11:39:46 +00004846static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4847 UnixUnusedFd *pUnused = 0;
4848
4849 /* Do not search for an unused file descriptor on vxworks. Not because
4850 ** vxworks would not benefit from the change (it might, we're not sure),
4851 ** but because no way to test it is currently available. It is better
4852 ** not to risk breaking vxworks support for the sake of such an obscure
4853 ** feature. */
4854#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00004855 struct stat sStat; /* Results of stat() call */
4856
4857 /* A stat() call may fail for various reasons. If this happens, it is
4858 ** almost certain that an open() call on the same path will also fail.
4859 ** For this reason, if an error occurs in the stat() call here, it is
4860 ** ignored and -1 is returned. The caller will try to open a new file
4861 ** descriptor on the same path, fail, and return an error to SQLite.
4862 **
4863 ** Even if a subsequent open() call does succeed, the consequences of
4864 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00004865 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00004866 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00004867
4868 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004869 pInode = inodeList;
4870 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4871 || pInode->fileId.ino!=sStat.st_ino) ){
4872 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00004873 }
drh8af6c222010-05-14 12:43:01 +00004874 if( pInode ){
dane946c392009-08-22 11:39:46 +00004875 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00004876 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00004877 pUnused = *pp;
4878 if( pUnused ){
4879 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00004880 }
4881 }
4882 unixLeaveMutex();
4883 }
dane946c392009-08-22 11:39:46 +00004884#endif /* if !OS_VXWORKS */
4885 return pUnused;
dan08da86a2009-08-21 17:18:03 +00004886}
danielk197717b90b52008-06-06 11:11:25 +00004887
4888/*
danddb0ac42010-07-14 14:48:58 +00004889** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00004890** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00004891** and a value suitable for passing as the third argument to open(2) is
4892** written to *pMode. If an IO error occurs, an SQLite error code is
4893** returned and the value of *pMode is not modified.
4894**
4895** If the file being opened is a temporary file, it is always created with
4896** the octal permissions 0600 (read/writable by owner only). If the file
drh8ab58662010-07-15 18:38:39 +00004897** is a database or master journal file, it is created with the permissions
4898** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
danddb0ac42010-07-14 14:48:58 +00004899**
drh8ab58662010-07-15 18:38:39 +00004900** Finally, if the file being opened is a WAL or regular journal file, then
4901** this function queries the file-system for the permissions on the
4902** corresponding database file and sets *pMode to this value. Whenever
4903** possible, WAL and journal files are created using the same permissions
4904** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00004905**
4906** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
4907** original filename is unavailable. But 8_3_NAMES is only used for
4908** FAT filesystems and permissions do not matter there, so just use
4909** the default permissions.
danddb0ac42010-07-14 14:48:58 +00004910*/
4911static int findCreateFileMode(
4912 const char *zPath, /* Path of file (possibly) being created */
4913 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00004914 mode_t *pMode, /* OUT: Permissions to open file with */
4915 uid_t *pUid, /* OUT: uid to set on the file */
4916 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00004917){
4918 int rc = SQLITE_OK; /* Return Code */
drh81cc5162011-05-17 20:36:21 +00004919 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
drhac7c3ac2012-02-11 19:23:48 +00004920 *pUid = 0;
4921 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00004922 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00004923 char zDb[MAX_PATHNAME+1]; /* Database file path */
4924 int nDb; /* Number of valid bytes in zDb */
4925 struct stat sStat; /* Output of stat() on database file */
4926
dana0c989d2010-11-05 18:07:37 +00004927 /* zPath is a path to a WAL or journal file. The following block derives
4928 ** the path to the associated database file from zPath. This block handles
4929 ** the following naming conventions:
4930 **
4931 ** "<path to db>-journal"
4932 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00004933 ** "<path to db>-journalNN"
4934 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00004935 **
drhd337c5b2011-10-20 18:23:35 +00004936 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00004937 ** used by the test_multiplex.c module.
4938 */
4939 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00004940#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00004941 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00004942 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00004943#else
4944 while( zPath[nDb]!='-' ){
4945 assert( nDb>0 );
4946 assert( zPath[nDb]!='\n' );
4947 nDb--;
4948 }
4949#endif
danddb0ac42010-07-14 14:48:58 +00004950 memcpy(zDb, zPath, nDb);
4951 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00004952
drh58384f12011-07-28 00:14:45 +00004953 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004954 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00004955 *pUid = sStat.st_uid;
4956 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00004957 }else{
4958 rc = SQLITE_IOERR_FSTAT;
4959 }
4960 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4961 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00004962 }
4963 return rc;
4964}
4965
4966/*
danielk1977ad94b582007-08-20 06:44:22 +00004967** Open the file zPath.
4968**
danielk1977b4b47412007-08-17 15:53:36 +00004969** Previously, the SQLite OS layer used three functions in place of this
4970** one:
4971**
4972** sqlite3OsOpenReadWrite();
4973** sqlite3OsOpenReadOnly();
4974** sqlite3OsOpenExclusive();
4975**
4976** These calls correspond to the following combinations of flags:
4977**
4978** ReadWrite() -> (READWRITE | CREATE)
4979** ReadOnly() -> (READONLY)
4980** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
4981**
4982** The old OpenExclusive() accepted a boolean argument - "delFlag". If
4983** true, the file was configured to be automatically deleted when the
4984** file handle closed. To achieve the same effect using this new
4985** interface, add the DELETEONCLOSE flag to those specified above for
4986** OpenExclusive().
4987*/
4988static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00004989 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
4990 const char *zPath, /* Pathname of file to be opened */
4991 sqlite3_file *pFile, /* The file descriptor to be filled in */
4992 int flags, /* Input flags to control the opening */
4993 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00004994){
dan08da86a2009-08-21 17:18:03 +00004995 unixFile *p = (unixFile *)pFile;
4996 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00004997 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00004998 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00004999 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005000 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005001 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005002
5003 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5004 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5005 int isCreate = (flags & SQLITE_OPEN_CREATE);
5006 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5007 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005008#if SQLITE_ENABLE_LOCKING_STYLE
5009 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5010#endif
drh3d4435b2011-08-26 20:55:50 +00005011#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5012 struct statfs fsInfo;
5013#endif
danielk1977b4b47412007-08-17 15:53:36 +00005014
danielk1977fee2d252007-08-18 10:59:19 +00005015 /* If creating a master or main-file journal, this function will open
5016 ** a file-descriptor on the directory too. The first time unixSync()
5017 ** is called the directory file descriptor will be fsync()ed and close()d.
5018 */
drh0059eae2011-08-08 23:48:40 +00005019 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005020 eType==SQLITE_OPEN_MASTER_JOURNAL
5021 || eType==SQLITE_OPEN_MAIN_JOURNAL
5022 || eType==SQLITE_OPEN_WAL
5023 ));
danielk1977fee2d252007-08-18 10:59:19 +00005024
danielk197717b90b52008-06-06 11:11:25 +00005025 /* If argument zPath is a NULL pointer, this function is required to open
5026 ** a temporary file. Use this buffer to store the file name in.
5027 */
drhc02a43a2012-01-10 23:18:38 +00005028 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005029 const char *zName = zPath;
5030
danielk1977fee2d252007-08-18 10:59:19 +00005031 /* Check the following statements are true:
5032 **
5033 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5034 ** (b) if CREATE is set, then READWRITE must also be set, and
5035 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005036 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005037 */
danielk1977b4b47412007-08-17 15:53:36 +00005038 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005039 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005040 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005041 assert(isDelete==0 || isCreate);
5042
danddb0ac42010-07-14 14:48:58 +00005043 /* The main DB, main journal, WAL file and master journal are never
5044 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005045 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5046 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5047 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005048 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005049
danielk1977fee2d252007-08-18 10:59:19 +00005050 /* Assert that the upper layer has set one of the "file-type" flags. */
5051 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5052 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5053 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005054 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005055 );
5056
dan08da86a2009-08-21 17:18:03 +00005057 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005058
dan08da86a2009-08-21 17:18:03 +00005059 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005060 UnixUnusedFd *pUnused;
5061 pUnused = findReusableFd(zName, flags);
5062 if( pUnused ){
5063 fd = pUnused->fd;
5064 }else{
dan6aa657f2009-08-24 18:57:58 +00005065 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005066 if( !pUnused ){
5067 return SQLITE_NOMEM;
5068 }
5069 }
5070 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005071
5072 /* Database filenames are double-zero terminated if they are not
5073 ** URIs with parameters. Hence, they can always be passed into
5074 ** sqlite3_uri_parameter(). */
5075 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5076
dan08da86a2009-08-21 17:18:03 +00005077 }else if( !zName ){
5078 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005079 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005080 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005081 if( rc!=SQLITE_OK ){
5082 return rc;
5083 }
5084 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005085
5086 /* Generated temporary filenames are always double-zero terminated
5087 ** for use by sqlite3_uri_parameter(). */
5088 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005089 }
5090
dan08da86a2009-08-21 17:18:03 +00005091 /* Determine the value of the flags parameter passed to POSIX function
5092 ** open(). These must be calculated even if open() is not called, as
5093 ** they may be stored as part of the file handle and used by the
5094 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005095 if( isReadonly ) openFlags |= O_RDONLY;
5096 if( isReadWrite ) openFlags |= O_RDWR;
5097 if( isCreate ) openFlags |= O_CREAT;
5098 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5099 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005100
danielk1977b4b47412007-08-17 15:53:36 +00005101 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005102 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005103 uid_t uid; /* Userid for the file */
5104 gid_t gid; /* Groupid for the file */
5105 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005106 if( rc!=SQLITE_OK ){
5107 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005108 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005109 return rc;
5110 }
drhad4f1e52011-03-04 15:43:57 +00005111 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005112 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005113 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5114 /* Failed to open the file for read/write access. Try read-only. */
5115 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005116 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005117 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005118 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005119 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005120 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005121 }
5122 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005123 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005124 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005125 }
drhac7c3ac2012-02-11 19:23:48 +00005126
5127 /* If this process is running as root and if creating a new rollback
5128 ** journal or WAL file, set the ownership of the journal or WAL to be
5129 ** the same as the original database. If we are not running as root,
drh3ee34842012-02-11 21:21:17 +00005130 ** then the fchown() call will fail, but that's ok. The "if(){}" and
5131 ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
5132 ** warnings from gcc.
drhac7c3ac2012-02-11 19:23:48 +00005133 */
5134 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh23c4b972012-02-11 23:55:15 +00005135 if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
drhac7c3ac2012-02-11 19:23:48 +00005136 }
danielk1977b4b47412007-08-17 15:53:36 +00005137 }
dan08da86a2009-08-21 17:18:03 +00005138 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005139 if( pOutFlags ){
5140 *pOutFlags = flags;
5141 }
5142
dane946c392009-08-22 11:39:46 +00005143 if( p->pUnused ){
5144 p->pUnused->fd = fd;
5145 p->pUnused->flags = flags;
5146 }
5147
danielk1977b4b47412007-08-17 15:53:36 +00005148 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005149#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005150 zPath = zName;
5151#else
drh036ac7f2011-08-08 23:18:05 +00005152 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005153#endif
danielk1977b4b47412007-08-17 15:53:36 +00005154 }
drh41022642008-11-21 00:24:42 +00005155#if SQLITE_ENABLE_LOCKING_STYLE
5156 else{
dan08da86a2009-08-21 17:18:03 +00005157 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005158 }
5159#endif
5160
danielk1977e339d652008-06-28 11:23:00 +00005161#ifdef FD_CLOEXEC
drh99ab3b12011-03-02 15:09:07 +00005162 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
danielk1977e339d652008-06-28 11:23:00 +00005163#endif
5164
drhda0e7682008-07-30 15:27:54 +00005165 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005166
drh7ed97b92010-01-20 13:07:21 +00005167
5168#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005169 if( fstatfs(fd, &fsInfo) == -1 ){
5170 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005171 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005172 return SQLITE_IOERR_ACCESS;
5173 }
5174 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5175 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5176 }
5177#endif
drhc02a43a2012-01-10 23:18:38 +00005178
5179 /* Set up appropriate ctrlFlags */
5180 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5181 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5182 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5183 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5184 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5185
drh7ed97b92010-01-20 13:07:21 +00005186#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005187#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005188 isAutoProxy = 1;
5189#endif
5190 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005191 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5192 int useProxy = 0;
5193
dan08da86a2009-08-21 17:18:03 +00005194 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5195 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005196 if( envforce!=NULL ){
5197 useProxy = atoi(envforce)>0;
5198 }else{
aswiftaebf4132008-11-21 00:10:35 +00005199 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005200 /* In theory, the close(fd) call is sub-optimal. If the file opened
5201 ** with fd is a database file, and there are other connections open
5202 ** on that file that are currently holding advisory locks on it,
5203 ** then the call to close() will cancel those locks. In practice,
5204 ** we're assuming that statfs() doesn't fail very often. At least
5205 ** not while other file descriptors opened by the same process on
5206 ** the same file are working. */
5207 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005208 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005209 rc = SQLITE_IOERR_ACCESS;
5210 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005211 }
5212 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5213 }
5214 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005215 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005216 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005217 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005218 if( rc!=SQLITE_OK ){
5219 /* Use unixClose to clean up the resources added in fillInUnixFile
5220 ** and clear all the structure's references. Specifically,
5221 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5222 */
5223 unixClose(pFile);
5224 return rc;
5225 }
aswiftaebf4132008-11-21 00:10:35 +00005226 }
dane946c392009-08-22 11:39:46 +00005227 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005228 }
5229 }
5230#endif
5231
drhc02a43a2012-01-10 23:18:38 +00005232 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5233
dane946c392009-08-22 11:39:46 +00005234open_finished:
5235 if( rc!=SQLITE_OK ){
5236 sqlite3_free(p->pUnused);
5237 }
5238 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005239}
5240
dane946c392009-08-22 11:39:46 +00005241
danielk1977b4b47412007-08-17 15:53:36 +00005242/*
danielk1977fee2d252007-08-18 10:59:19 +00005243** Delete the file at zPath. If the dirSync argument is true, fsync()
5244** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005245*/
drh6b9d6dd2008-12-03 19:34:47 +00005246static int unixDelete(
5247 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5248 const char *zPath, /* Name of file to be deleted */
5249 int dirSync /* If true, fsync() directory after deleting file */
5250){
danielk1977fee2d252007-08-18 10:59:19 +00005251 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005252 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005253 SimulateIOError(return SQLITE_IOERR_DELETE);
drh036ac7f2011-08-08 23:18:05 +00005254 if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
dane18d4952011-02-21 11:46:24 +00005255 return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
drh5d4feff2010-07-14 01:45:22 +00005256 }
danielk1977d39fa702008-10-16 13:27:40 +00005257#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005258 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005259 int fd;
drh90315a22011-08-10 01:52:12 +00005260 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005261 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005262#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005263 if( fsync(fd)==-1 )
5264#else
5265 if( fsync(fd) )
5266#endif
5267 {
dane18d4952011-02-21 11:46:24 +00005268 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005269 }
drh0e9365c2011-03-02 02:08:13 +00005270 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005271 }else if( rc==SQLITE_CANTOPEN ){
5272 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005273 }
5274 }
danielk1977d138dd82008-10-15 16:02:48 +00005275#endif
danielk1977fee2d252007-08-18 10:59:19 +00005276 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005277}
5278
danielk197790949c22007-08-17 16:50:38 +00005279/*
5280** Test the existance of or access permissions of file zPath. The
5281** test performed depends on the value of flags:
5282**
5283** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5284** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5285** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5286**
5287** Otherwise return 0.
5288*/
danielk1977861f7452008-06-05 11:39:11 +00005289static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005290 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5291 const char *zPath, /* Path of the file to examine */
5292 int flags, /* What do we want to learn about the zPath file? */
5293 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005294){
rse25c0d1a2007-09-20 08:38:14 +00005295 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005296 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005297 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005298 switch( flags ){
5299 case SQLITE_ACCESS_EXISTS:
5300 amode = F_OK;
5301 break;
5302 case SQLITE_ACCESS_READWRITE:
5303 amode = W_OK|R_OK;
5304 break;
drh50d3f902007-08-27 21:10:36 +00005305 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005306 amode = R_OK;
5307 break;
5308
5309 default:
5310 assert(!"Invalid flags argument");
5311 }
drh99ab3b12011-03-02 15:09:07 +00005312 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005313 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5314 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005315 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005316 *pResOut = 0;
5317 }
5318 }
danielk1977861f7452008-06-05 11:39:11 +00005319 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005320}
5321
danielk1977b4b47412007-08-17 15:53:36 +00005322
5323/*
5324** Turn a relative pathname into a full pathname. The relative path
5325** is stored as a nul-terminated string in the buffer pointed to by
5326** zPath.
5327**
5328** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5329** (in this case, MAX_PATHNAME bytes). The full-path is written to
5330** this buffer before returning.
5331*/
danielk1977adfb9b02007-09-17 07:02:56 +00005332static int unixFullPathname(
5333 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5334 const char *zPath, /* Possibly relative input path */
5335 int nOut, /* Size of output buffer in bytes */
5336 char *zOut /* Output buffer */
5337){
danielk1977843e65f2007-09-01 16:16:15 +00005338
5339 /* It's odd to simulate an io-error here, but really this is just
5340 ** using the io-error infrastructure to test that SQLite handles this
5341 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005342 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005343 */
5344 SimulateIOError( return SQLITE_ERROR );
5345
drh153c62c2007-08-24 03:51:33 +00005346 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005347 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005348
drh3c7f2dc2007-12-06 13:26:20 +00005349 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005350 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005351 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005352 }else{
5353 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005354 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005355 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005356 }
drhea678832008-12-10 19:26:22 +00005357 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005358 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005359 }
5360 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005361}
5362
drh0ccebe72005-06-07 22:22:50 +00005363
drh761df872006-12-21 01:29:22 +00005364#ifndef SQLITE_OMIT_LOAD_EXTENSION
5365/*
5366** Interfaces for opening a shared library, finding entry points
5367** within the shared library, and closing the shared library.
5368*/
5369#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005370static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5371 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005372 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5373}
danielk197795c8a542007-09-01 06:51:27 +00005374
5375/*
5376** SQLite calls this function immediately after a call to unixDlSym() or
5377** unixDlOpen() fails (returns a null pointer). If a more detailed error
5378** message is available, it is written to zBufOut. If no error message
5379** is available, zBufOut is left unmodified and SQLite uses a default
5380** error message.
5381*/
danielk1977397d65f2008-11-19 11:35:39 +00005382static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005383 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005384 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005385 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005386 zErr = dlerror();
5387 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005388 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005389 }
drh6c7d5c52008-11-21 20:32:33 +00005390 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005391}
drh1875f7a2008-12-08 18:19:17 +00005392static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5393 /*
5394 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5395 ** cast into a pointer to a function. And yet the library dlsym() routine
5396 ** returns a void* which is really a pointer to a function. So how do we
5397 ** use dlsym() with -pedantic-errors?
5398 **
5399 ** Variable x below is defined to be a pointer to a function taking
5400 ** parameters void* and const char* and returning a pointer to a function.
5401 ** We initialize x by assigning it a pointer to the dlsym() function.
5402 ** (That assignment requires a cast.) Then we call the function that
5403 ** x points to.
5404 **
5405 ** This work-around is unlikely to work correctly on any system where
5406 ** you really cannot cast a function pointer into void*. But then, on the
5407 ** other hand, dlsym() will not work on such a system either, so we have
5408 ** not really lost anything.
5409 */
5410 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005411 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005412 x = (void(*(*)(void*,const char*))(void))dlsym;
5413 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005414}
danielk1977397d65f2008-11-19 11:35:39 +00005415static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5416 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005417 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005418}
danielk1977b4b47412007-08-17 15:53:36 +00005419#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5420 #define unixDlOpen 0
5421 #define unixDlError 0
5422 #define unixDlSym 0
5423 #define unixDlClose 0
5424#endif
5425
5426/*
danielk197790949c22007-08-17 16:50:38 +00005427** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005428*/
danielk1977397d65f2008-11-19 11:35:39 +00005429static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5430 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005431 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005432
drhbbd42a62004-05-22 17:41:58 +00005433 /* We have to initialize zBuf to prevent valgrind from reporting
5434 ** errors. The reports issued by valgrind are incorrect - we would
5435 ** prefer that the randomness be increased by making use of the
5436 ** uninitialized space in zBuf - but valgrind errors tend to worry
5437 ** some users. Rather than argue, it seems easier just to initialize
5438 ** the whole array and silence valgrind, even if that means less randomness
5439 ** in the random seed.
5440 **
5441 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005442 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005443 ** tests repeatable.
5444 */
danielk1977b4b47412007-08-17 15:53:36 +00005445 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005446#if !defined(SQLITE_TEST)
5447 {
drhc18b4042012-02-10 03:10:27 +00005448 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005449 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005450 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005451 time_t t;
5452 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005453 memcpy(zBuf, &t, sizeof(t));
5454 pid = getpid();
5455 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005456 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005457 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005458 }else{
drhc18b4042012-02-10 03:10:27 +00005459 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005460 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005461 }
drhbbd42a62004-05-22 17:41:58 +00005462 }
5463#endif
drh72cbd072008-10-14 17:58:38 +00005464 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005465}
5466
danielk1977b4b47412007-08-17 15:53:36 +00005467
drhbbd42a62004-05-22 17:41:58 +00005468/*
5469** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005470** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005471** The return value is the number of microseconds of sleep actually
5472** requested from the underlying operating system, a number which
5473** might be greater than or equal to the argument, but not less
5474** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005475*/
danielk1977397d65f2008-11-19 11:35:39 +00005476static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005477#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005478 struct timespec sp;
5479
5480 sp.tv_sec = microseconds / 1000000;
5481 sp.tv_nsec = (microseconds % 1000000) * 1000;
5482 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005483 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005484 return microseconds;
5485#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005486 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005487 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005488 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005489#else
danielk1977b4b47412007-08-17 15:53:36 +00005490 int seconds = (microseconds+999999)/1000000;
5491 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005492 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005493 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005494#endif
drh88f474a2006-01-02 20:00:12 +00005495}
5496
5497/*
drh6b9d6dd2008-12-03 19:34:47 +00005498** The following variable, if set to a non-zero value, is interpreted as
5499** the number of seconds since 1970 and is used to set the result of
5500** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005501*/
5502#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005503int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005504#endif
5505
5506/*
drhb7e8ea22010-05-03 14:32:30 +00005507** Find the current time (in Universal Coordinated Time). Write into *piNow
5508** the current time and date as a Julian Day number times 86_400_000. In
5509** other words, write into *piNow the number of milliseconds since the Julian
5510** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5511** proleptic Gregorian calendar.
5512**
drh31702252011-10-12 23:13:43 +00005513** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5514** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005515*/
5516static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5517 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005518 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005519#if defined(NO_GETTOD)
5520 time_t t;
5521 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005522 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005523#elif OS_VXWORKS
5524 struct timespec sNow;
5525 clock_gettime(CLOCK_REALTIME, &sNow);
5526 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5527#else
5528 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005529 if( gettimeofday(&sNow, 0)==0 ){
5530 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5531 }else{
5532 rc = SQLITE_ERROR;
5533 }
drhb7e8ea22010-05-03 14:32:30 +00005534#endif
5535
5536#ifdef SQLITE_TEST
5537 if( sqlite3_current_time ){
5538 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5539 }
5540#endif
5541 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005542 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005543}
5544
5545/*
drhbbd42a62004-05-22 17:41:58 +00005546** Find the current time (in Universal Coordinated Time). Write the
5547** current time and date as a Julian Day number into *prNow and
5548** return 0. Return 1 if the time and date cannot be found.
5549*/
danielk1977397d65f2008-11-19 11:35:39 +00005550static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005551 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005552 int rc;
drhff828942010-06-26 21:34:06 +00005553 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005554 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005555 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005556 return rc;
drhbbd42a62004-05-22 17:41:58 +00005557}
danielk1977b4b47412007-08-17 15:53:36 +00005558
drh6b9d6dd2008-12-03 19:34:47 +00005559/*
5560** We added the xGetLastError() method with the intention of providing
5561** better low-level error messages when operating-system problems come up
5562** during SQLite operation. But so far, none of that has been implemented
5563** in the core. So this routine is never called. For now, it is merely
5564** a place-holder.
5565*/
danielk1977397d65f2008-11-19 11:35:39 +00005566static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5567 UNUSED_PARAMETER(NotUsed);
5568 UNUSED_PARAMETER(NotUsed2);
5569 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005570 return 0;
5571}
5572
drhf2424c52010-04-26 00:04:55 +00005573
5574/*
drh734c9862008-11-28 15:37:20 +00005575************************ End of sqlite3_vfs methods ***************************
5576******************************************************************************/
5577
drh715ff302008-12-03 22:32:44 +00005578/******************************************************************************
5579************************** Begin Proxy Locking ********************************
5580**
5581** Proxy locking is a "uber-locking-method" in this sense: It uses the
5582** other locking methods on secondary lock files. Proxy locking is a
5583** meta-layer over top of the primitive locking implemented above. For
5584** this reason, the division that implements of proxy locking is deferred
5585** until late in the file (here) after all of the other I/O methods have
5586** been defined - so that the primitive locking methods are available
5587** as services to help with the implementation of proxy locking.
5588**
5589****
5590**
5591** The default locking schemes in SQLite use byte-range locks on the
5592** database file to coordinate safe, concurrent access by multiple readers
5593** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5594** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5595** as POSIX read & write locks over fixed set of locations (via fsctl),
5596** on AFP and SMB only exclusive byte-range locks are available via fsctl
5597** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5598** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5599** address in the shared range is taken for a SHARED lock, the entire
5600** shared range is taken for an EXCLUSIVE lock):
5601**
5602** PENDING_BYTE 0x40000000
5603** RESERVED_BYTE 0x40000001
5604** SHARED_RANGE 0x40000002 -> 0x40000200
5605**
5606** This works well on the local file system, but shows a nearly 100x
5607** slowdown in read performance on AFP because the AFP client disables
5608** the read cache when byte-range locks are present. Enabling the read
5609** cache exposes a cache coherency problem that is present on all OS X
5610** supported network file systems. NFS and AFP both observe the
5611** close-to-open semantics for ensuring cache coherency
5612** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5613** address the requirements for concurrent database access by multiple
5614** readers and writers
5615** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5616**
5617** To address the performance and cache coherency issues, proxy file locking
5618** changes the way database access is controlled by limiting access to a
5619** single host at a time and moving file locks off of the database file
5620** and onto a proxy file on the local file system.
5621**
5622**
5623** Using proxy locks
5624** -----------------
5625**
5626** C APIs
5627**
5628** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5629** <proxy_path> | ":auto:");
5630** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5631**
5632**
5633** SQL pragmas
5634**
5635** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5636** PRAGMA [database.]lock_proxy_file
5637**
5638** Specifying ":auto:" means that if there is a conch file with a matching
5639** host ID in it, the proxy path in the conch file will be used, otherwise
5640** a proxy path based on the user's temp dir
5641** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5642** actual proxy file name is generated from the name and path of the
5643** database file. For example:
5644**
5645** For database path "/Users/me/foo.db"
5646** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5647**
5648** Once a lock proxy is configured for a database connection, it can not
5649** be removed, however it may be switched to a different proxy path via
5650** the above APIs (assuming the conch file is not being held by another
5651** connection or process).
5652**
5653**
5654** How proxy locking works
5655** -----------------------
5656**
5657** Proxy file locking relies primarily on two new supporting files:
5658**
5659** * conch file to limit access to the database file to a single host
5660** at a time
5661**
5662** * proxy file to act as a proxy for the advisory locks normally
5663** taken on the database
5664**
5665** The conch file - to use a proxy file, sqlite must first "hold the conch"
5666** by taking an sqlite-style shared lock on the conch file, reading the
5667** contents and comparing the host's unique host ID (see below) and lock
5668** proxy path against the values stored in the conch. The conch file is
5669** stored in the same directory as the database file and the file name
5670** is patterned after the database file name as ".<databasename>-conch".
5671** If the conch file does not exist, or it's contents do not match the
5672** host ID and/or proxy path, then the lock is escalated to an exclusive
5673** lock and the conch file contents is updated with the host ID and proxy
5674** path and the lock is downgraded to a shared lock again. If the conch
5675** is held by another process (with a shared lock), the exclusive lock
5676** will fail and SQLITE_BUSY is returned.
5677**
5678** The proxy file - a single-byte file used for all advisory file locks
5679** normally taken on the database file. This allows for safe sharing
5680** of the database file for multiple readers and writers on the same
5681** host (the conch ensures that they all use the same local lock file).
5682**
drh715ff302008-12-03 22:32:44 +00005683** Requesting the lock proxy does not immediately take the conch, it is
5684** only taken when the first request to lock database file is made.
5685** This matches the semantics of the traditional locking behavior, where
5686** opening a connection to a database file does not take a lock on it.
5687** The shared lock and an open file descriptor are maintained until
5688** the connection to the database is closed.
5689**
5690** The proxy file and the lock file are never deleted so they only need
5691** to be created the first time they are used.
5692**
5693** Configuration options
5694** ---------------------
5695**
5696** SQLITE_PREFER_PROXY_LOCKING
5697**
5698** Database files accessed on non-local file systems are
5699** automatically configured for proxy locking, lock files are
5700** named automatically using the same logic as
5701** PRAGMA lock_proxy_file=":auto:"
5702**
5703** SQLITE_PROXY_DEBUG
5704**
5705** Enables the logging of error messages during host id file
5706** retrieval and creation
5707**
drh715ff302008-12-03 22:32:44 +00005708** LOCKPROXYDIR
5709**
5710** Overrides the default directory used for lock proxy files that
5711** are named automatically via the ":auto:" setting
5712**
5713** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5714**
5715** Permissions to use when creating a directory for storing the
5716** lock proxy files, only used when LOCKPROXYDIR is not set.
5717**
5718**
5719** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5720** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5721** force proxy locking to be used for every database file opened, and 0
5722** will force automatic proxy locking to be disabled for all database
5723** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5724** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5725*/
5726
5727/*
5728** Proxy locking is only available on MacOSX
5729*/
drhd2cb50b2009-01-09 21:41:17 +00005730#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005731
drh715ff302008-12-03 22:32:44 +00005732/*
5733** The proxyLockingContext has the path and file structures for the remote
5734** and local proxy files in it
5735*/
5736typedef struct proxyLockingContext proxyLockingContext;
5737struct proxyLockingContext {
5738 unixFile *conchFile; /* Open conch file */
5739 char *conchFilePath; /* Name of the conch file */
5740 unixFile *lockProxy; /* Open proxy lock file */
5741 char *lockProxyPath; /* Name of the proxy lock file */
5742 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005743 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005744 void *oldLockingContext; /* Original lockingcontext to restore on close */
5745 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5746};
5747
drh7ed97b92010-01-20 13:07:21 +00005748/*
5749** The proxy lock file path for the database at dbPath is written into lPath,
5750** which must point to valid, writable memory large enough for a maxLen length
5751** file path.
drh715ff302008-12-03 22:32:44 +00005752*/
drh715ff302008-12-03 22:32:44 +00005753static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5754 int len;
5755 int dbLen;
5756 int i;
5757
5758#ifdef LOCKPROXYDIR
5759 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5760#else
5761# ifdef _CS_DARWIN_USER_TEMP_DIR
5762 {
drh7ed97b92010-01-20 13:07:21 +00005763 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005764 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5765 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005766 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005767 }
drh7ed97b92010-01-20 13:07:21 +00005768 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005769 }
5770# else
5771 len = strlcpy(lPath, "/tmp/", maxLen);
5772# endif
5773#endif
5774
5775 if( lPath[len-1]!='/' ){
5776 len = strlcat(lPath, "/", maxLen);
5777 }
5778
5779 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005780 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005781 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005782 char c = dbPath[i];
5783 lPath[i+len] = (c=='/')?'_':c;
5784 }
5785 lPath[i+len]='\0';
5786 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005787 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005788 return SQLITE_OK;
5789}
5790
drh7ed97b92010-01-20 13:07:21 +00005791/*
5792 ** Creates the lock file and any missing directories in lockPath
5793 */
5794static int proxyCreateLockPath(const char *lockPath){
5795 int i, len;
5796 char buf[MAXPATHLEN];
5797 int start = 0;
5798
5799 assert(lockPath!=NULL);
5800 /* try to create all the intermediate directories */
5801 len = (int)strlen(lockPath);
5802 buf[0] = lockPath[0];
5803 for( i=1; i<len; i++ ){
5804 if( lockPath[i] == '/' && (i - start > 0) ){
5805 /* only mkdir if leaf dir != "." or "/" or ".." */
5806 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5807 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5808 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005809 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005810 int err=errno;
5811 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005812 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005813 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005814 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005815 return err;
5816 }
5817 }
5818 }
5819 start=i+1;
5820 }
5821 buf[i] = lockPath[i];
5822 }
drh308c2a52010-05-14 11:30:18 +00005823 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005824 return 0;
5825}
5826
drh715ff302008-12-03 22:32:44 +00005827/*
5828** Create a new VFS file descriptor (stored in memory obtained from
5829** sqlite3_malloc) and open the file named "path" in the file descriptor.
5830**
5831** The caller is responsible not only for closing the file descriptor
5832** but also for freeing the memory associated with the file descriptor.
5833*/
drh7ed97b92010-01-20 13:07:21 +00005834static int proxyCreateUnixFile(
5835 const char *path, /* path for the new unixFile */
5836 unixFile **ppFile, /* unixFile created and returned by ref */
5837 int islockfile /* if non zero missing dirs will be created */
5838) {
5839 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005840 unixFile *pNew;
5841 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005842 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005843 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005844 int terrno = 0;
5845 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005846
drh7ed97b92010-01-20 13:07:21 +00005847 /* 1. first try to open/create the file
5848 ** 2. if that fails, and this is a lock file (not-conch), try creating
5849 ** the parent directories and then try again.
5850 ** 3. if that fails, try to open the file read-only
5851 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5852 */
5853 pUnused = findReusableFd(path, openFlags);
5854 if( pUnused ){
5855 fd = pUnused->fd;
5856 }else{
5857 pUnused = sqlite3_malloc(sizeof(*pUnused));
5858 if( !pUnused ){
5859 return SQLITE_NOMEM;
5860 }
5861 }
5862 if( fd<0 ){
drhad4f1e52011-03-04 15:43:57 +00005863 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005864 terrno = errno;
5865 if( fd<0 && errno==ENOENT && islockfile ){
5866 if( proxyCreateLockPath(path) == SQLITE_OK ){
drhad4f1e52011-03-04 15:43:57 +00005867 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005868 }
5869 }
5870 }
5871 if( fd<0 ){
5872 openFlags = O_RDONLY;
drhad4f1e52011-03-04 15:43:57 +00005873 fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005874 terrno = errno;
5875 }
5876 if( fd<0 ){
5877 if( islockfile ){
5878 return SQLITE_BUSY;
5879 }
5880 switch (terrno) {
5881 case EACCES:
5882 return SQLITE_PERM;
5883 case EIO:
5884 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5885 default:
drh9978c972010-02-23 17:36:32 +00005886 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00005887 }
5888 }
5889
5890 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5891 if( pNew==NULL ){
5892 rc = SQLITE_NOMEM;
5893 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00005894 }
5895 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00005896 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00005897 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00005898 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00005899 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00005900 pUnused->fd = fd;
5901 pUnused->flags = openFlags;
5902 pNew->pUnused = pUnused;
5903
drhc02a43a2012-01-10 23:18:38 +00005904 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00005905 if( rc==SQLITE_OK ){
5906 *ppFile = pNew;
5907 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00005908 }
drh7ed97b92010-01-20 13:07:21 +00005909end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00005910 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005911 sqlite3_free(pNew);
5912 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00005913 return rc;
5914}
5915
drh7ed97b92010-01-20 13:07:21 +00005916#ifdef SQLITE_TEST
5917/* simulate multiple hosts by creating unique hostid file paths */
5918int sqlite3_hostid_num = 0;
5919#endif
5920
5921#define PROXY_HOSTIDLEN 16 /* conch file host id length */
5922
drh0ab216a2010-07-02 17:10:40 +00005923/* Not always defined in the headers as it ought to be */
5924extern int gethostuuid(uuid_t id, const struct timespec *wait);
5925
drh7ed97b92010-01-20 13:07:21 +00005926/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5927** bytes of writable memory.
5928*/
5929static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00005930 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5931 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00005932#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5933 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00005934 {
5935 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
5936 if( gethostuuid(pHostID, &timeout) ){
5937 int err = errno;
5938 if( pError ){
5939 *pError = err;
5940 }
5941 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00005942 }
drh7ed97b92010-01-20 13:07:21 +00005943 }
drh3d4435b2011-08-26 20:55:50 +00005944#else
5945 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00005946#endif
drh7ed97b92010-01-20 13:07:21 +00005947#ifdef SQLITE_TEST
5948 /* simulate multiple hosts by creating unique hostid file paths */
5949 if( sqlite3_hostid_num != 0){
5950 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5951 }
5952#endif
5953
5954 return SQLITE_OK;
5955}
5956
5957/* The conch file contains the header, host id and lock file path
5958 */
5959#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5960#define PROXY_HEADERLEN 1 /* conch file header length */
5961#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5962#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5963
5964/*
5965** Takes an open conch file, copies the contents to a new path and then moves
5966** it back. The newly created file's file descriptor is assigned to the
5967** conch file structure and finally the original conch file descriptor is
5968** closed. Returns zero if successful.
5969*/
5970static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5971 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5972 unixFile *conchFile = pCtx->conchFile;
5973 char tPath[MAXPATHLEN];
5974 char buf[PROXY_MAXCONCHLEN];
5975 char *cPath = pCtx->conchFilePath;
5976 size_t readLen = 0;
5977 size_t pathLen = 0;
5978 char errmsg[64] = "";
5979 int fd = -1;
5980 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00005981 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00005982
5983 /* create a new path by replace the trailing '-conch' with '-break' */
5984 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5985 if( pathLen>MAXPATHLEN || pathLen<6 ||
5986 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00005987 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00005988 goto end_breaklock;
5989 }
5990 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00005991 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00005992 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00005993 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00005994 goto end_breaklock;
5995 }
5996 /* write it out to the temporary break file */
drhad4f1e52011-03-04 15:43:57 +00005997 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
5998 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh7ed97b92010-01-20 13:07:21 +00005999 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006000 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006001 goto end_breaklock;
6002 }
drhe562be52011-03-02 18:01:10 +00006003 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006004 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006005 goto end_breaklock;
6006 }
6007 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006008 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006009 goto end_breaklock;
6010 }
6011 rc = 0;
6012 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006013 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006014 conchFile->h = fd;
6015 conchFile->openFlags = O_RDWR | O_CREAT;
6016
6017end_breaklock:
6018 if( rc ){
6019 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006020 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006021 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006022 }
6023 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6024 }
6025 return rc;
6026}
6027
6028/* Take the requested lock on the conch file and break a stale lock if the
6029** host id matches.
6030*/
6031static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6032 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6033 unixFile *conchFile = pCtx->conchFile;
6034 int rc = SQLITE_OK;
6035 int nTries = 0;
6036 struct timespec conchModTime;
6037
drh3d4435b2011-08-26 20:55:50 +00006038 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006039 do {
6040 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6041 nTries ++;
6042 if( rc==SQLITE_BUSY ){
6043 /* If the lock failed (busy):
6044 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6045 * 2nd try: fail if the mod time changed or host id is different, wait
6046 * 10 sec and try again
6047 * 3rd try: break the lock unless the mod time has changed.
6048 */
6049 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006050 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006051 pFile->lastErrno = errno;
6052 return SQLITE_IOERR_LOCK;
6053 }
6054
6055 if( nTries==1 ){
6056 conchModTime = buf.st_mtimespec;
6057 usleep(500000); /* wait 0.5 sec and try the lock again*/
6058 continue;
6059 }
6060
6061 assert( nTries>1 );
6062 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6063 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6064 return SQLITE_BUSY;
6065 }
6066
6067 if( nTries==2 ){
6068 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006069 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006070 if( len<0 ){
6071 pFile->lastErrno = errno;
6072 return SQLITE_IOERR_LOCK;
6073 }
6074 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6075 /* don't break the lock if the host id doesn't match */
6076 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6077 return SQLITE_BUSY;
6078 }
6079 }else{
6080 /* don't break the lock on short read or a version mismatch */
6081 return SQLITE_BUSY;
6082 }
6083 usleep(10000000); /* wait 10 sec and try the lock again */
6084 continue;
6085 }
6086
6087 assert( nTries==3 );
6088 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6089 rc = SQLITE_OK;
6090 if( lockType==EXCLUSIVE_LOCK ){
6091 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6092 }
6093 if( !rc ){
6094 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6095 }
6096 }
6097 }
6098 } while( rc==SQLITE_BUSY && nTries<3 );
6099
6100 return rc;
6101}
6102
6103/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006104** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6105** lockPath means that the lockPath in the conch file will be used if the
6106** host IDs match, or a new lock path will be generated automatically
6107** and written to the conch file.
6108*/
6109static int proxyTakeConch(unixFile *pFile){
6110 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6111
drh7ed97b92010-01-20 13:07:21 +00006112 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006113 return SQLITE_OK;
6114 }else{
6115 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006116 uuid_t myHostID;
6117 int pError = 0;
6118 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006119 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006120 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006121 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006122 int createConch = 0;
6123 int hostIdMatch = 0;
6124 int readLen = 0;
6125 int tryOldLockPath = 0;
6126 int forceNewLockPath = 0;
6127
drh308c2a52010-05-14 11:30:18 +00006128 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6129 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006130
drh7ed97b92010-01-20 13:07:21 +00006131 rc = proxyGetHostID(myHostID, &pError);
6132 if( (rc&0xff)==SQLITE_IOERR ){
6133 pFile->lastErrno = pError;
6134 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006135 }
drh7ed97b92010-01-20 13:07:21 +00006136 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006137 if( rc!=SQLITE_OK ){
6138 goto end_takeconch;
6139 }
drh7ed97b92010-01-20 13:07:21 +00006140 /* read the existing conch file */
6141 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6142 if( readLen<0 ){
6143 /* I/O error: lastErrno set by seekAndRead */
6144 pFile->lastErrno = conchFile->lastErrno;
6145 rc = SQLITE_IOERR_READ;
6146 goto end_takeconch;
6147 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6148 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6149 /* a short read or version format mismatch means we need to create a new
6150 ** conch file.
6151 */
6152 createConch = 1;
6153 }
6154 /* if the host id matches and the lock path already exists in the conch
6155 ** we'll try to use the path there, if we can't open that path, we'll
6156 ** retry with a new auto-generated path
6157 */
6158 do { /* in case we need to try again for an :auto: named lock file */
6159
6160 if( !createConch && !forceNewLockPath ){
6161 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6162 PROXY_HOSTIDLEN);
6163 /* if the conch has data compare the contents */
6164 if( !pCtx->lockProxyPath ){
6165 /* for auto-named local lock file, just check the host ID and we'll
6166 ** use the local lock file path that's already in there
6167 */
6168 if( hostIdMatch ){
6169 size_t pathLen = (readLen - PROXY_PATHINDEX);
6170
6171 if( pathLen>=MAXPATHLEN ){
6172 pathLen=MAXPATHLEN-1;
6173 }
6174 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6175 lockPath[pathLen] = 0;
6176 tempLockPath = lockPath;
6177 tryOldLockPath = 1;
6178 /* create a copy of the lock path if the conch is taken */
6179 goto end_takeconch;
6180 }
6181 }else if( hostIdMatch
6182 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6183 readLen-PROXY_PATHINDEX)
6184 ){
6185 /* conch host and lock path match */
6186 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006187 }
drh7ed97b92010-01-20 13:07:21 +00006188 }
6189
6190 /* if the conch isn't writable and doesn't match, we can't take it */
6191 if( (conchFile->openFlags&O_RDWR) == 0 ){
6192 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006193 goto end_takeconch;
6194 }
drh7ed97b92010-01-20 13:07:21 +00006195
6196 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006197 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006198 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6199 tempLockPath = lockPath;
6200 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006201 }
drh7ed97b92010-01-20 13:07:21 +00006202
6203 /* update conch with host and path (this will fail if other process
6204 ** has a shared lock already), if the host id matches, use the big
6205 ** stick.
drh715ff302008-12-03 22:32:44 +00006206 */
drh7ed97b92010-01-20 13:07:21 +00006207 futimes(conchFile->h, NULL);
6208 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006209 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006210 /* We are trying for an exclusive lock but another thread in this
6211 ** same process is still holding a shared lock. */
6212 rc = SQLITE_BUSY;
6213 } else {
6214 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006215 }
drh715ff302008-12-03 22:32:44 +00006216 }else{
drh7ed97b92010-01-20 13:07:21 +00006217 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006218 }
drh7ed97b92010-01-20 13:07:21 +00006219 if( rc==SQLITE_OK ){
6220 char writeBuffer[PROXY_MAXCONCHLEN];
6221 int writeSize = 0;
6222
6223 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6224 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6225 if( pCtx->lockProxyPath!=NULL ){
6226 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6227 }else{
6228 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6229 }
6230 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006231 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006232 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6233 fsync(conchFile->h);
6234 /* If we created a new conch file (not just updated the contents of a
6235 ** valid conch file), try to match the permissions of the database
6236 */
6237 if( rc==SQLITE_OK && createConch ){
6238 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006239 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006240 if( err==0 ){
6241 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6242 S_IROTH|S_IWOTH);
6243 /* try to match the database file R/W permissions, ignore failure */
6244#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006245 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006246#else
drhff812312011-02-23 13:33:46 +00006247 do{
drhe562be52011-03-02 18:01:10 +00006248 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006249 }while( rc==(-1) && errno==EINTR );
6250 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006251 int code = errno;
6252 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6253 cmode, code, strerror(code));
6254 } else {
6255 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6256 }
6257 }else{
6258 int code = errno;
6259 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6260 err, code, strerror(code));
6261#endif
6262 }
drh715ff302008-12-03 22:32:44 +00006263 }
6264 }
drh7ed97b92010-01-20 13:07:21 +00006265 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6266
6267 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006268 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006269 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006270 int fd;
drh7ed97b92010-01-20 13:07:21 +00006271 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006272 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006273 }
6274 pFile->h = -1;
drh3d4435b2011-08-26 20:55:50 +00006275 fd = robust_open(pCtx->dbPath, pFile->openFlags,
drh7ed97b92010-01-20 13:07:21 +00006276 SQLITE_DEFAULT_FILE_PERMISSIONS);
drh308c2a52010-05-14 11:30:18 +00006277 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006278 if( fd>=0 ){
6279 pFile->h = fd;
6280 }else{
drh9978c972010-02-23 17:36:32 +00006281 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006282 during locking */
6283 }
6284 }
6285 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6286 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6287 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6288 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6289 /* we couldn't create the proxy lock file with the old lock file path
6290 ** so try again via auto-naming
6291 */
6292 forceNewLockPath = 1;
6293 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006294 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006295 }
6296 }
6297 if( rc==SQLITE_OK ){
6298 /* Need to make a copy of path if we extracted the value
6299 ** from the conch file or the path was allocated on the stack
6300 */
6301 if( tempLockPath ){
6302 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6303 if( !pCtx->lockProxyPath ){
6304 rc = SQLITE_NOMEM;
6305 }
6306 }
6307 }
6308 if( rc==SQLITE_OK ){
6309 pCtx->conchHeld = 1;
6310
6311 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6312 afpLockingContext *afpCtx;
6313 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6314 afpCtx->dbPath = pCtx->lockProxyPath;
6315 }
6316 } else {
6317 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6318 }
drh308c2a52010-05-14 11:30:18 +00006319 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6320 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006321 return rc;
drh308c2a52010-05-14 11:30:18 +00006322 } while (1); /* in case we need to retry the :auto: lock file -
6323 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006324 }
6325}
6326
6327/*
6328** If pFile holds a lock on a conch file, then release that lock.
6329*/
6330static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006331 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006332 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6333 unixFile *conchFile; /* Name of the conch file */
6334
6335 pCtx = (proxyLockingContext *)pFile->lockingContext;
6336 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006337 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006338 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006339 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006340 if( pCtx->conchHeld>0 ){
6341 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6342 }
drh715ff302008-12-03 22:32:44 +00006343 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006344 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6345 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006346 return rc;
6347}
6348
6349/*
6350** Given the name of a database file, compute the name of its conch file.
6351** Store the conch filename in memory obtained from sqlite3_malloc().
6352** Make *pConchPath point to the new name. Return SQLITE_OK on success
6353** or SQLITE_NOMEM if unable to obtain memory.
6354**
6355** The caller is responsible for ensuring that the allocated memory
6356** space is eventually freed.
6357**
6358** *pConchPath is set to NULL if a memory allocation error occurs.
6359*/
6360static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6361 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006362 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006363 char *conchPath; /* buffer in which to construct conch name */
6364
6365 /* Allocate space for the conch filename and initialize the name to
6366 ** the name of the original database file. */
6367 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6368 if( conchPath==0 ){
6369 return SQLITE_NOMEM;
6370 }
6371 memcpy(conchPath, dbPath, len+1);
6372
6373 /* now insert a "." before the last / character */
6374 for( i=(len-1); i>=0; i-- ){
6375 if( conchPath[i]=='/' ){
6376 i++;
6377 break;
6378 }
6379 }
6380 conchPath[i]='.';
6381 while ( i<len ){
6382 conchPath[i+1]=dbPath[i];
6383 i++;
6384 }
6385
6386 /* append the "-conch" suffix to the file */
6387 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006388 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006389
6390 return SQLITE_OK;
6391}
6392
6393
6394/* Takes a fully configured proxy locking-style unix file and switches
6395** the local lock file path
6396*/
6397static int switchLockProxyPath(unixFile *pFile, const char *path) {
6398 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6399 char *oldPath = pCtx->lockProxyPath;
6400 int rc = SQLITE_OK;
6401
drh308c2a52010-05-14 11:30:18 +00006402 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006403 return SQLITE_BUSY;
6404 }
6405
6406 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6407 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6408 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6409 return SQLITE_OK;
6410 }else{
6411 unixFile *lockProxy = pCtx->lockProxy;
6412 pCtx->lockProxy=NULL;
6413 pCtx->conchHeld = 0;
6414 if( lockProxy!=NULL ){
6415 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6416 if( rc ) return rc;
6417 sqlite3_free(lockProxy);
6418 }
6419 sqlite3_free(oldPath);
6420 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6421 }
6422
6423 return rc;
6424}
6425
6426/*
6427** pFile is a file that has been opened by a prior xOpen call. dbPath
6428** is a string buffer at least MAXPATHLEN+1 characters in size.
6429**
6430** This routine find the filename associated with pFile and writes it
6431** int dbPath.
6432*/
6433static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006434#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006435 if( pFile->pMethod == &afpIoMethods ){
6436 /* afp style keeps a reference to the db path in the filePath field
6437 ** of the struct */
drhea678832008-12-10 19:26:22 +00006438 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006439 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6440 } else
drh715ff302008-12-03 22:32:44 +00006441#endif
6442 if( pFile->pMethod == &dotlockIoMethods ){
6443 /* dot lock style uses the locking context to store the dot lock
6444 ** file path */
6445 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6446 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6447 }else{
6448 /* all other styles use the locking context to store the db file path */
6449 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006450 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006451 }
6452 return SQLITE_OK;
6453}
6454
6455/*
6456** Takes an already filled in unix file and alters it so all file locking
6457** will be performed on the local proxy lock file. The following fields
6458** are preserved in the locking context so that they can be restored and
6459** the unix structure properly cleaned up at close time:
6460** ->lockingContext
6461** ->pMethod
6462*/
6463static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6464 proxyLockingContext *pCtx;
6465 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6466 char *lockPath=NULL;
6467 int rc = SQLITE_OK;
6468
drh308c2a52010-05-14 11:30:18 +00006469 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006470 return SQLITE_BUSY;
6471 }
6472 proxyGetDbPathForUnixFile(pFile, dbPath);
6473 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6474 lockPath=NULL;
6475 }else{
6476 lockPath=(char *)path;
6477 }
6478
drh308c2a52010-05-14 11:30:18 +00006479 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6480 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006481
6482 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6483 if( pCtx==0 ){
6484 return SQLITE_NOMEM;
6485 }
6486 memset(pCtx, 0, sizeof(*pCtx));
6487
6488 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6489 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006490 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6491 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6492 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6493 ** (c) the file system is read-only, then enable no-locking access.
6494 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6495 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6496 */
6497 struct statfs fsInfo;
6498 struct stat conchInfo;
6499 int goLockless = 0;
6500
drh99ab3b12011-03-02 15:09:07 +00006501 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006502 int err = errno;
6503 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6504 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6505 }
6506 }
6507 if( goLockless ){
6508 pCtx->conchHeld = -1; /* read only FS/ lockless */
6509 rc = SQLITE_OK;
6510 }
6511 }
drh715ff302008-12-03 22:32:44 +00006512 }
6513 if( rc==SQLITE_OK && lockPath ){
6514 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6515 }
6516
6517 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006518 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6519 if( pCtx->dbPath==NULL ){
6520 rc = SQLITE_NOMEM;
6521 }
6522 }
6523 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006524 /* all memory is allocated, proxys are created and assigned,
6525 ** switch the locking context and pMethod then return.
6526 */
drh715ff302008-12-03 22:32:44 +00006527 pCtx->oldLockingContext = pFile->lockingContext;
6528 pFile->lockingContext = pCtx;
6529 pCtx->pOldMethod = pFile->pMethod;
6530 pFile->pMethod = &proxyIoMethods;
6531 }else{
6532 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006533 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006534 sqlite3_free(pCtx->conchFile);
6535 }
drhd56b1212010-08-11 06:14:15 +00006536 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006537 sqlite3_free(pCtx->conchFilePath);
6538 sqlite3_free(pCtx);
6539 }
drh308c2a52010-05-14 11:30:18 +00006540 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6541 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006542 return rc;
6543}
6544
6545
6546/*
6547** This routine handles sqlite3_file_control() calls that are specific
6548** to proxy locking.
6549*/
6550static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6551 switch( op ){
6552 case SQLITE_GET_LOCKPROXYFILE: {
6553 unixFile *pFile = (unixFile*)id;
6554 if( pFile->pMethod == &proxyIoMethods ){
6555 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6556 proxyTakeConch(pFile);
6557 if( pCtx->lockProxyPath ){
6558 *(const char **)pArg = pCtx->lockProxyPath;
6559 }else{
6560 *(const char **)pArg = ":auto: (not held)";
6561 }
6562 } else {
6563 *(const char **)pArg = NULL;
6564 }
6565 return SQLITE_OK;
6566 }
6567 case SQLITE_SET_LOCKPROXYFILE: {
6568 unixFile *pFile = (unixFile*)id;
6569 int rc = SQLITE_OK;
6570 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6571 if( pArg==NULL || (const char *)pArg==0 ){
6572 if( isProxyStyle ){
6573 /* turn off proxy locking - not supported */
6574 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6575 }else{
6576 /* turn off proxy locking - already off - NOOP */
6577 rc = SQLITE_OK;
6578 }
6579 }else{
6580 const char *proxyPath = (const char *)pArg;
6581 if( isProxyStyle ){
6582 proxyLockingContext *pCtx =
6583 (proxyLockingContext*)pFile->lockingContext;
6584 if( !strcmp(pArg, ":auto:")
6585 || (pCtx->lockProxyPath &&
6586 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6587 ){
6588 rc = SQLITE_OK;
6589 }else{
6590 rc = switchLockProxyPath(pFile, proxyPath);
6591 }
6592 }else{
6593 /* turn on proxy file locking */
6594 rc = proxyTransformUnixFile(pFile, proxyPath);
6595 }
6596 }
6597 return rc;
6598 }
6599 default: {
6600 assert( 0 ); /* The call assures that only valid opcodes are sent */
6601 }
6602 }
6603 /*NOTREACHED*/
6604 return SQLITE_ERROR;
6605}
6606
6607/*
6608** Within this division (the proxying locking implementation) the procedures
6609** above this point are all utilities. The lock-related methods of the
6610** proxy-locking sqlite3_io_method object follow.
6611*/
6612
6613
6614/*
6615** This routine checks if there is a RESERVED lock held on the specified
6616** file by this or any other process. If such a lock is held, set *pResOut
6617** to a non-zero value otherwise *pResOut is set to zero. The return value
6618** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6619*/
6620static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6621 unixFile *pFile = (unixFile*)id;
6622 int rc = proxyTakeConch(pFile);
6623 if( rc==SQLITE_OK ){
6624 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006625 if( pCtx->conchHeld>0 ){
6626 unixFile *proxy = pCtx->lockProxy;
6627 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6628 }else{ /* conchHeld < 0 is lockless */
6629 pResOut=0;
6630 }
drh715ff302008-12-03 22:32:44 +00006631 }
6632 return rc;
6633}
6634
6635/*
drh308c2a52010-05-14 11:30:18 +00006636** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006637** of the following:
6638**
6639** (1) SHARED_LOCK
6640** (2) RESERVED_LOCK
6641** (3) PENDING_LOCK
6642** (4) EXCLUSIVE_LOCK
6643**
6644** Sometimes when requesting one lock state, additional lock states
6645** are inserted in between. The locking might fail on one of the later
6646** transitions leaving the lock state different from what it started but
6647** still short of its goal. The following chart shows the allowed
6648** transitions and the inserted intermediate states:
6649**
6650** UNLOCKED -> SHARED
6651** SHARED -> RESERVED
6652** SHARED -> (PENDING) -> EXCLUSIVE
6653** RESERVED -> (PENDING) -> EXCLUSIVE
6654** PENDING -> EXCLUSIVE
6655**
6656** This routine will only increase a lock. Use the sqlite3OsUnlock()
6657** routine to lower a locking level.
6658*/
drh308c2a52010-05-14 11:30:18 +00006659static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006660 unixFile *pFile = (unixFile*)id;
6661 int rc = proxyTakeConch(pFile);
6662 if( rc==SQLITE_OK ){
6663 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006664 if( pCtx->conchHeld>0 ){
6665 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006666 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6667 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006668 }else{
6669 /* conchHeld < 0 is lockless */
6670 }
drh715ff302008-12-03 22:32:44 +00006671 }
6672 return rc;
6673}
6674
6675
6676/*
drh308c2a52010-05-14 11:30:18 +00006677** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006678** must be either NO_LOCK or SHARED_LOCK.
6679**
6680** If the locking level of the file descriptor is already at or below
6681** the requested locking level, this routine is a no-op.
6682*/
drh308c2a52010-05-14 11:30:18 +00006683static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006684 unixFile *pFile = (unixFile*)id;
6685 int rc = proxyTakeConch(pFile);
6686 if( rc==SQLITE_OK ){
6687 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006688 if( pCtx->conchHeld>0 ){
6689 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006690 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6691 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006692 }else{
6693 /* conchHeld < 0 is lockless */
6694 }
drh715ff302008-12-03 22:32:44 +00006695 }
6696 return rc;
6697}
6698
6699/*
6700** Close a file that uses proxy locks.
6701*/
6702static int proxyClose(sqlite3_file *id) {
6703 if( id ){
6704 unixFile *pFile = (unixFile*)id;
6705 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6706 unixFile *lockProxy = pCtx->lockProxy;
6707 unixFile *conchFile = pCtx->conchFile;
6708 int rc = SQLITE_OK;
6709
6710 if( lockProxy ){
6711 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6712 if( rc ) return rc;
6713 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6714 if( rc ) return rc;
6715 sqlite3_free(lockProxy);
6716 pCtx->lockProxy = 0;
6717 }
6718 if( conchFile ){
6719 if( pCtx->conchHeld ){
6720 rc = proxyReleaseConch(pFile);
6721 if( rc ) return rc;
6722 }
6723 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6724 if( rc ) return rc;
6725 sqlite3_free(conchFile);
6726 }
drhd56b1212010-08-11 06:14:15 +00006727 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006728 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006729 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006730 /* restore the original locking context and pMethod then close it */
6731 pFile->lockingContext = pCtx->oldLockingContext;
6732 pFile->pMethod = pCtx->pOldMethod;
6733 sqlite3_free(pCtx);
6734 return pFile->pMethod->xClose(id);
6735 }
6736 return SQLITE_OK;
6737}
6738
6739
6740
drhd2cb50b2009-01-09 21:41:17 +00006741#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006742/*
6743** The proxy locking style is intended for use with AFP filesystems.
6744** And since AFP is only supported on MacOSX, the proxy locking is also
6745** restricted to MacOSX.
6746**
6747**
6748******************* End of the proxy lock implementation **********************
6749******************************************************************************/
6750
drh734c9862008-11-28 15:37:20 +00006751/*
danielk1977e339d652008-06-28 11:23:00 +00006752** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006753**
6754** This routine registers all VFS implementations for unix-like operating
6755** systems. This routine, and the sqlite3_os_end() routine that follows,
6756** should be the only routines in this file that are visible from other
6757** files.
drh6b9d6dd2008-12-03 19:34:47 +00006758**
6759** This routine is called once during SQLite initialization and by a
6760** single thread. The memory allocation and mutex subsystems have not
6761** necessarily been initialized when this routine is called, and so they
6762** should not be used.
drh153c62c2007-08-24 03:51:33 +00006763*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006764int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006765 /*
6766 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006767 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6768 ** to the "finder" function. (pAppData is a pointer to a pointer because
6769 ** silly C90 rules prohibit a void* from being cast to a function pointer
6770 ** and so we have to go through the intermediate pointer to avoid problems
6771 ** when compiling with -pedantic-errors on GCC.)
6772 **
6773 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006774 ** finder-function. The finder-function returns a pointer to the
6775 ** sqlite_io_methods object that implements the desired locking
6776 ** behaviors. See the division above that contains the IOMETHODS
6777 ** macro for addition information on finder-functions.
6778 **
6779 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6780 ** object. But the "autolockIoFinder" available on MacOSX does a little
6781 ** more than that; it looks at the filesystem type that hosts the
6782 ** database file and tries to choose an locking method appropriate for
6783 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006784 */
drh7708e972008-11-29 00:56:52 +00006785 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006786 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006787 sizeof(unixFile), /* szOsFile */ \
6788 MAX_PATHNAME, /* mxPathname */ \
6789 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006790 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006791 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006792 unixOpen, /* xOpen */ \
6793 unixDelete, /* xDelete */ \
6794 unixAccess, /* xAccess */ \
6795 unixFullPathname, /* xFullPathname */ \
6796 unixDlOpen, /* xDlOpen */ \
6797 unixDlError, /* xDlError */ \
6798 unixDlSym, /* xDlSym */ \
6799 unixDlClose, /* xDlClose */ \
6800 unixRandomness, /* xRandomness */ \
6801 unixSleep, /* xSleep */ \
6802 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006803 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006804 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006805 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006806 unixGetSystemCall, /* xGetSystemCall */ \
6807 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006808 }
6809
drh6b9d6dd2008-12-03 19:34:47 +00006810 /*
6811 ** All default VFSes for unix are contained in the following array.
6812 **
6813 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6814 ** by the SQLite core when the VFS is registered. So the following
6815 ** array cannot be const.
6816 */
danielk1977e339d652008-06-28 11:23:00 +00006817 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006818#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006819 UNIXVFS("unix", autolockIoFinder ),
6820#else
6821 UNIXVFS("unix", posixIoFinder ),
6822#endif
6823 UNIXVFS("unix-none", nolockIoFinder ),
6824 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006825 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006826#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006827 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006828#endif
6829#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006830 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006831#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006832 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006833#endif
chw78a13182009-04-07 05:35:03 +00006834#endif
drhd2cb50b2009-01-09 21:41:17 +00006835#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006836 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006837 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006838 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006839#endif
drh153c62c2007-08-24 03:51:33 +00006840 };
drh6b9d6dd2008-12-03 19:34:47 +00006841 unsigned int i; /* Loop counter */
6842
drh2aa5a002011-04-13 13:42:25 +00006843 /* Double-check that the aSyscall[] array has been constructed
6844 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh23c4b972012-02-11 23:55:15 +00006845 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00006846
drh6b9d6dd2008-12-03 19:34:47 +00006847 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006848 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006849 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006850 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006851 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006852}
danielk1977e339d652008-06-28 11:23:00 +00006853
6854/*
drh6b9d6dd2008-12-03 19:34:47 +00006855** Shutdown the operating system interface.
6856**
6857** Some operating systems might need to do some cleanup in this routine,
6858** to release dynamically allocated objects. But not on unix.
6859** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00006860*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006861int sqlite3_os_end(void){
6862 return SQLITE_OK;
6863}
drhdce8bdb2007-08-16 13:01:44 +00006864
danielk197729bafea2008-06-26 10:41:19 +00006865#endif /* SQLITE_OS_UNIX */