blob: 153cf5f435a1d19413a468bddeec82b6ae73f2b2 [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
drh6033e152012-11-13 11:08:49 +000049/* Use posix_fallocate() if it is available
50*/
51#if !defined(HAVE_POSIX_FALLOCATE) \
52 && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
53# define HAVE_POSIX_FALLOCATE 1
54#endif
55
danielk1977e339d652008-06-28 11:23:00 +000056/*
drh6b9d6dd2008-12-03 19:34:47 +000057** There are various methods for file locking used for concurrency
58** control:
danielk1977e339d652008-06-28 11:23:00 +000059**
drh734c9862008-11-28 15:37:20 +000060** 1. POSIX locking (the default),
61** 2. No locking,
62** 3. Dot-file locking,
63** 4. flock() locking,
64** 5. AFP locking (OSX only),
65** 6. Named POSIX semaphores (VXWorks only),
66** 7. proxy locking. (OSX only)
67**
68** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
69** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
70** selection of the appropriate locking style based on the filesystem
71** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000072*/
drh40bbb0a2008-09-23 10:23:26 +000073#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000074# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000075# define SQLITE_ENABLE_LOCKING_STYLE 1
76# else
77# define SQLITE_ENABLE_LOCKING_STYLE 0
78# endif
79#endif
drhbfe66312006-10-03 17:40:40 +000080
drh9cbe6352005-11-29 03:13:21 +000081/*
drh6c7d5c52008-11-21 20:32:33 +000082** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000083** vxworks, or 0 otherwise.
84*/
drh6c7d5c52008-11-21 20:32:33 +000085#ifndef OS_VXWORKS
86# if defined(__RTP__) || defined(_WRS_KERNEL)
87# define OS_VXWORKS 1
88# else
89# define OS_VXWORKS 0
90# endif
danielk1977397d65f2008-11-19 11:35:39 +000091#endif
92
93/*
drh9cbe6352005-11-29 03:13:21 +000094** These #defines should enable >2GB file support on Posix if the
95** underlying operating system supports it. If the OS lacks
drhf1a221e2006-01-15 17:27:17 +000096** large file support, these should be no-ops.
drh9cbe6352005-11-29 03:13:21 +000097**
98** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
99** on the compiler command line. This is necessary if you are compiling
100** on a recent machine (ex: RedHat 7.2) but you want your code to work
101** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
102** without this option, LFS is enable. But LFS does not exist in the kernel
103** in RedHat 6.0, so the code won't work. Hence, for maximum binary
104** portability you should omit LFS.
drh9b35ea62008-11-29 02:20:26 +0000105**
106** The previous paragraph was written in 2005. (This paragraph is written
107** on 2008-11-28.) These days, all Linux kernels support large files, so
108** you should probably leave LFS enabled. But some embedded platforms might
109** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
drh9cbe6352005-11-29 03:13:21 +0000110*/
111#ifndef SQLITE_DISABLE_LFS
112# define _LARGE_FILE 1
113# ifndef _FILE_OFFSET_BITS
114# define _FILE_OFFSET_BITS 64
115# endif
116# define _LARGEFILE_SOURCE 1
117#endif
drhbbd42a62004-05-22 17:41:58 +0000118
drh9cbe6352005-11-29 03:13:21 +0000119/*
120** standard include files.
121*/
122#include <sys/types.h>
123#include <sys/stat.h>
124#include <fcntl.h>
125#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +0000126#include <time.h>
drh19e2d372005-08-29 23:00:03 +0000127#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +0000128#include <errno.h>
drhb469f462010-12-22 21:48:50 +0000129#ifndef SQLITE_OMIT_WAL
drhf2424c52010-04-26 00:04:55 +0000130#include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000131#endif
drh1da88f02011-12-17 16:09:16 +0000132
danielk1977e339d652008-06-28 11:23:00 +0000133
drh40bbb0a2008-09-23 10:23:26 +0000134#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000135# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000136# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000137# include <semaphore.h>
138# include <limits.h>
139# else
drh9b35ea62008-11-29 02:20:26 +0000140# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000141# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000142# endif
drhbfe66312006-10-03 17:40:40 +0000143#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000144
drhf8b4d8c2010-03-05 13:53:22 +0000145#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000146# include <sys/mount.h>
147#endif
148
drhdbe4b882011-06-20 18:00:17 +0000149#ifdef HAVE_UTIME
150# include <utime.h>
151#endif
152
drh9cbe6352005-11-29 03:13:21 +0000153/*
drh7ed97b92010-01-20 13:07:21 +0000154** Allowed values of unixFile.fsFlags
155*/
156#define SQLITE_FSFLAGS_IS_MSDOS 0x1
157
158/*
drhf1a221e2006-01-15 17:27:17 +0000159** If we are to be thread-safe, include the pthreads header and define
160** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000161*/
drhd677b3d2007-08-20 22:48:41 +0000162#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000163# include <pthread.h>
164# define SQLITE_UNIX_THREADS 1
165#endif
166
167/*
168** Default permissions when creating a new file
169*/
170#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
171# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
172#endif
173
danielk1977b4b47412007-08-17 15:53:36 +0000174/*
drh5adc60b2012-04-14 13:25:11 +0000175** Default permissions when creating auto proxy dir
176*/
aswiftaebf4132008-11-21 00:10:35 +0000177#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
178# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
179#endif
180
181/*
danielk1977b4b47412007-08-17 15:53:36 +0000182** Maximum supported path-length.
183*/
184#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000185
drh734c9862008-11-28 15:37:20 +0000186/*
drh734c9862008-11-28 15:37:20 +0000187** Only set the lastErrno if the error code is a real error and not
188** a normal expected return code of SQLITE_BUSY or SQLITE_OK
189*/
190#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
191
drhd91c68f2010-05-14 14:52:25 +0000192/* Forward references */
193typedef struct unixShm unixShm; /* Connection shared memory */
194typedef struct unixShmNode unixShmNode; /* Shared memory instance */
195typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
196typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000197
198/*
dane946c392009-08-22 11:39:46 +0000199** Sometimes, after a file handle is closed by SQLite, the file descriptor
200** cannot be closed immediately. In these cases, instances of the following
201** structure are used to store the file descriptor while waiting for an
202** opportunity to either close or reuse it.
203*/
dane946c392009-08-22 11:39:46 +0000204struct UnixUnusedFd {
205 int fd; /* File descriptor to close */
206 int flags; /* Flags this file descriptor was opened with */
207 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
208};
209
210/*
drh9b35ea62008-11-29 02:20:26 +0000211** The unixFile structure is subclass of sqlite3_file specific to the unix
212** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000213*/
drh054889e2005-11-30 03:20:31 +0000214typedef struct unixFile unixFile;
215struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000216 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000217 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000218 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000219 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000220 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000221 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000222 int lastErrno; /* The unix errno from last I/O error */
223 void *lockingContext; /* Locking style specific state */
224 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000225 const char *zPath; /* Name of the file */
226 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000227 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
drh537dddf2012-10-26 13:46:24 +0000228#ifdef __QNXNTO__
229 int sectorSize; /* Device sector size */
230 int deviceCharacteristics; /* Precomputed device characteristics */
231#endif
drh08c6d442009-02-09 17:34:07 +0000232#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000233 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000234#endif
drh7ed97b92010-01-20 13:07:21 +0000235#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000236 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000237#endif
238#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000239 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000240#endif
drhd3d8c042012-05-29 17:02:40 +0000241#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000242 /* The next group of variables are used to track whether or not the
243 ** transaction counter in bytes 24-27 of database files are updated
244 ** whenever any part of the database changes. An assertion fault will
245 ** occur if a file is updated without also updating the transaction
246 ** counter. This test is made to avoid new problems similar to the
247 ** one described by ticket #3584.
248 */
249 unsigned char transCntrChng; /* True if the transaction counter changed */
250 unsigned char dbUpdate; /* True if any part of database file changed */
251 unsigned char inNormalWrite; /* True if in a normal write operation */
252#endif
danielk1977967a4a12007-08-20 14:23:44 +0000253#ifdef SQLITE_TEST
254 /* In test mode, increase the size of this structure a bit so that
255 ** it is larger than the struct CrashFile defined in test6.c.
256 */
257 char aPadding[32];
258#endif
drh9cbe6352005-11-29 03:13:21 +0000259};
260
drh0ccebe72005-06-07 22:22:50 +0000261/*
drha7e61d82011-03-12 17:02:57 +0000262** Allowed values for the unixFile.ctrlFlags bitmask:
263*/
drhf0b190d2011-07-26 16:03:07 +0000264#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
265#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
266#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000267#ifndef SQLITE_DISABLE_DIRSYNC
268# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
269#else
270# define UNIXFILE_DIRSYNC 0x00
271#endif
drhcb15f352011-12-23 01:04:17 +0000272#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000273#define UNIXFILE_DELETE 0x20 /* Delete on close */
274#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
275#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000276
277/*
drh198bf392006-01-06 21:52:49 +0000278** Include code that is common to all os_*.c files
279*/
280#include "os_common.h"
281
282/*
drh0ccebe72005-06-07 22:22:50 +0000283** Define various macros that are missing from some systems.
284*/
drhbbd42a62004-05-22 17:41:58 +0000285#ifndef O_LARGEFILE
286# define O_LARGEFILE 0
287#endif
288#ifdef SQLITE_DISABLE_LFS
289# undef O_LARGEFILE
290# define O_LARGEFILE 0
291#endif
292#ifndef O_NOFOLLOW
293# define O_NOFOLLOW 0
294#endif
295#ifndef O_BINARY
296# define O_BINARY 0
297#endif
298
299/*
drh2b4b5962005-06-15 17:47:55 +0000300** The threadid macro resolves to the thread-id or to 0. Used for
301** testing and debugging only.
302*/
drhd677b3d2007-08-20 22:48:41 +0000303#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000304#define threadid pthread_self()
305#else
306#define threadid 0
307#endif
308
drh99ab3b12011-03-02 15:09:07 +0000309/*
drh9a3baf12011-04-25 18:01:27 +0000310** Different Unix systems declare open() in different ways. Same use
311** open(const char*,int,mode_t). Others use open(const char*,int,...).
312** The difference is important when using a pointer to the function.
313**
314** The safest way to deal with the problem is to always use this wrapper
315** which always has the same well-defined interface.
316*/
317static int posixOpen(const char *zFile, int flags, int mode){
318 return open(zFile, flags, mode);
319}
320
drhed466822012-05-31 13:10:49 +0000321/*
322** On some systems, calls to fchown() will trigger a message in a security
323** log if they come from non-root processes. So avoid calling fchown() if
324** we are not running as root.
325*/
326static int posixFchown(int fd, uid_t uid, gid_t gid){
327 return geteuid() ? 0 : fchown(fd,uid,gid);
328}
329
drh90315a22011-08-10 01:52:12 +0000330/* Forward reference */
331static int openDirectory(const char*, int*);
332
drh9a3baf12011-04-25 18:01:27 +0000333/*
drh99ab3b12011-03-02 15:09:07 +0000334** Many system calls are accessed through pointer-to-functions so that
335** they may be overridden at runtime to facilitate fault injection during
336** testing and sandboxing. The following array holds the names and pointers
337** to all overrideable system calls.
338*/
339static struct unix_syscall {
drh58ad5802011-03-23 22:02:23 +0000340 const char *zName; /* Name of the sytem call */
341 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
342 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000343} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000344 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
345#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000346
drh58ad5802011-03-23 22:02:23 +0000347 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osClose ((int(*)(int))aSyscall[1].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
352
drh58ad5802011-03-23 22:02:23 +0000353 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
355
drh58ad5802011-03-23 22:02:23 +0000356 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000357#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
358
359/*
360** The DJGPP compiler environment looks mostly like Unix, but it
361** lacks the fcntl() system call. So redefine fcntl() to be something
362** that always succeeds. This means that locking does not occur under
363** DJGPP. But it is DOS - what did you expect?
364*/
365#ifdef __DJGPP__
366 { "fstat", 0, 0 },
367#define osFstat(a,b,c) 0
368#else
drh58ad5802011-03-23 22:02:23 +0000369 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
371#endif
372
drh58ad5802011-03-23 22:02:23 +0000373 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000378
drh58ad5802011-03-23 22:02:23 +0000379 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000380#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
381
drhd4a80312011-04-15 14:33:20 +0000382#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000383 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000384#else
drh58ad5802011-03-23 22:02:23 +0000385 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000386#endif
387#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
388
389#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000390 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000393#endif
394#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
395
drh58ad5802011-03-23 22:02:23 +0000396 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000397#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
398
drhd4a80312011-04-15 14:33:20 +0000399#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000400 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000401#else
drh58ad5802011-03-23 22:02:23 +0000402 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000403#endif
404#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
405 aSyscall[12].pCurrent)
406
407#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000409#else
drh58ad5802011-03-23 22:02:23 +0000410 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000411#endif
412#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
413 aSyscall[13].pCurrent)
414
drh58ad5802011-03-23 22:02:23 +0000415 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000416#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000417
418#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000419 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000420#else
drh58ad5802011-03-23 22:02:23 +0000421 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000422#endif
dan0fd7d862011-03-29 10:04:23 +0000423#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000424
drh036ac7f2011-08-08 23:18:05 +0000425 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
426#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
427
drh90315a22011-08-10 01:52:12 +0000428 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
429#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
430
drh9ef6bc42011-11-04 02:24:02 +0000431 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
432#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
433
434 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
435#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
436
drhed466822012-05-31 13:10:49 +0000437 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000438#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000439
drhe562be52011-03-02 18:01:10 +0000440}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000441
442/*
443** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000444** "unix" VFSes. Return SQLITE_OK opon successfully updating the
445** system call pointer, or SQLITE_NOTFOUND if there is no configurable
446** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000447*/
448static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000449 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
450 const char *zName, /* Name of system call to override */
451 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000452){
drh58ad5802011-03-23 22:02:23 +0000453 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000454 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000455
456 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000457 if( zName==0 ){
458 /* If no zName is given, restore all system calls to their default
459 ** settings and return NULL
460 */
dan51438a72011-04-02 17:00:47 +0000461 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000462 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
463 if( aSyscall[i].pDefault ){
464 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000465 }
466 }
467 }else{
468 /* If zName is specified, operate on only the one system call
469 ** specified.
470 */
471 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
472 if( strcmp(zName, aSyscall[i].zName)==0 ){
473 if( aSyscall[i].pDefault==0 ){
474 aSyscall[i].pDefault = aSyscall[i].pCurrent;
475 }
drh1df30962011-03-02 19:06:42 +0000476 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000477 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
478 aSyscall[i].pCurrent = pNewFunc;
479 break;
480 }
481 }
482 }
483 return rc;
484}
485
drh1df30962011-03-02 19:06:42 +0000486/*
487** Return the value of a system call. Return NULL if zName is not a
488** recognized system call name. NULL is also returned if the system call
489** is currently undefined.
490*/
drh58ad5802011-03-23 22:02:23 +0000491static sqlite3_syscall_ptr unixGetSystemCall(
492 sqlite3_vfs *pNotUsed,
493 const char *zName
494){
495 unsigned int i;
496
497 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000498 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
499 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
500 }
501 return 0;
502}
503
504/*
505** Return the name of the first system call after zName. If zName==NULL
506** then return the name of the first system call. Return NULL if zName
507** is the last system call or if zName is not the name of a valid
508** system call.
509*/
510static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000511 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000512
513 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000514 if( zName ){
515 for(i=0; i<ArraySize(aSyscall)-1; i++){
516 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000517 }
518 }
dan0fd7d862011-03-29 10:04:23 +0000519 for(i++; i<ArraySize(aSyscall); i++){
520 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000521 }
522 return 0;
523}
524
drhad4f1e52011-03-04 15:43:57 +0000525/*
drh8c815d12012-02-13 20:16:37 +0000526** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000527** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000528**
529** If the file creation mode "m" is 0 then set it to the default for
530** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
531** 0644) as modified by the system umask. If m is not 0, then
532** make the file creation mode be exactly m ignoring the umask.
533**
534** The m parameter will be non-zero only when creating -wal, -journal,
535** and -shm files. We want those files to have *exactly* the same
536** permissions as their original database, unadulterated by the umask.
537** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
538** transaction crashes and leaves behind hot journals, then any
539** process that is able to write to the database will also be able to
540** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000541*/
drh8c815d12012-02-13 20:16:37 +0000542static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000543 int fd;
drhe1186ab2013-01-04 20:45:13 +0000544 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5adc60b2012-04-14 13:25:11 +0000545 do{
546#if defined(O_CLOEXEC)
547 fd = osOpen(z,f|O_CLOEXEC,m2);
548#else
549 fd = osOpen(z,f,m2);
550#endif
551 }while( fd<0 && errno==EINTR );
drhe1186ab2013-01-04 20:45:13 +0000552 if( fd>=0 ){
553 if( m!=0 ){
554 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000555 if( osFstat(fd, &statbuf)==0
556 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000557 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000558 ){
drhe1186ab2013-01-04 20:45:13 +0000559 osFchmod(fd, m);
560 }
561 }
drh5adc60b2012-04-14 13:25:11 +0000562#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000563 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000564#endif
drhe1186ab2013-01-04 20:45:13 +0000565 }
drh5adc60b2012-04-14 13:25:11 +0000566 return fd;
drhad4f1e52011-03-04 15:43:57 +0000567}
danielk197713adf8a2004-06-03 16:08:41 +0000568
drh107886a2008-11-21 22:21:50 +0000569/*
dan9359c7b2009-08-21 08:29:10 +0000570** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000571** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000572** vxworksFileId objects used by this file, all of which may be
573** shared by multiple threads.
574**
575** Function unixMutexHeld() is used to assert() that the global mutex
576** is held when required. This function is only used as part of assert()
577** statements. e.g.
578**
579** unixEnterMutex()
580** assert( unixMutexHeld() );
581** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000582*/
583static void unixEnterMutex(void){
584 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
585}
586static void unixLeaveMutex(void){
587 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
588}
dan9359c7b2009-08-21 08:29:10 +0000589#ifdef SQLITE_DEBUG
590static int unixMutexHeld(void) {
591 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
592}
593#endif
drh107886a2008-11-21 22:21:50 +0000594
drh734c9862008-11-28 15:37:20 +0000595
drh30ddce62011-10-15 00:16:30 +0000596#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000597/*
598** Helper function for printing out trace information from debugging
599** binaries. This returns the string represetation of the supplied
600** integer lock-type.
601*/
drh308c2a52010-05-14 11:30:18 +0000602static const char *azFileLock(int eFileLock){
603 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000604 case NO_LOCK: return "NONE";
605 case SHARED_LOCK: return "SHARED";
606 case RESERVED_LOCK: return "RESERVED";
607 case PENDING_LOCK: return "PENDING";
608 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000609 }
610 return "ERROR";
611}
612#endif
613
614#ifdef SQLITE_LOCK_TRACE
615/*
616** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000617**
drh734c9862008-11-28 15:37:20 +0000618** This routine is used for troubleshooting locks on multithreaded
619** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
620** command-line option on the compiler. This code is normally
621** turned off.
622*/
623static int lockTrace(int fd, int op, struct flock *p){
624 char *zOpName, *zType;
625 int s;
626 int savedErrno;
627 if( op==F_GETLK ){
628 zOpName = "GETLK";
629 }else if( op==F_SETLK ){
630 zOpName = "SETLK";
631 }else{
drh99ab3b12011-03-02 15:09:07 +0000632 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000633 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
634 return s;
635 }
636 if( p->l_type==F_RDLCK ){
637 zType = "RDLCK";
638 }else if( p->l_type==F_WRLCK ){
639 zType = "WRLCK";
640 }else if( p->l_type==F_UNLCK ){
641 zType = "UNLCK";
642 }else{
643 assert( 0 );
644 }
645 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000646 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000647 savedErrno = errno;
648 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
649 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
650 (int)p->l_pid, s);
651 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
652 struct flock l2;
653 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000654 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000655 if( l2.l_type==F_RDLCK ){
656 zType = "RDLCK";
657 }else if( l2.l_type==F_WRLCK ){
658 zType = "WRLCK";
659 }else if( l2.l_type==F_UNLCK ){
660 zType = "UNLCK";
661 }else{
662 assert( 0 );
663 }
664 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
665 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
666 }
667 errno = savedErrno;
668 return s;
669}
drh99ab3b12011-03-02 15:09:07 +0000670#undef osFcntl
671#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000672#endif /* SQLITE_LOCK_TRACE */
673
drhff812312011-02-23 13:33:46 +0000674/*
675** Retry ftruncate() calls that fail due to EINTR
676*/
drhff812312011-02-23 13:33:46 +0000677static int robust_ftruncate(int h, sqlite3_int64 sz){
678 int rc;
drh99ab3b12011-03-02 15:09:07 +0000679 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000680 return rc;
681}
drh734c9862008-11-28 15:37:20 +0000682
683/*
684** This routine translates a standard POSIX errno code into something
685** useful to the clients of the sqlite3 functions. Specifically, it is
686** intended to translate a variety of "try again" errors into SQLITE_BUSY
687** and a variety of "please close the file descriptor NOW" errors into
688** SQLITE_IOERR
689**
690** Errors during initialization of locks, or file system support for locks,
691** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
692*/
693static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
694 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000695#if 0
696 /* At one point this code was not commented out. In theory, this branch
697 ** should never be hit, as this function should only be called after
698 ** a locking-related function (i.e. fcntl()) has returned non-zero with
699 ** the value of errno as the first argument. Since a system call has failed,
700 ** errno should be non-zero.
701 **
702 ** Despite this, if errno really is zero, we still don't want to return
703 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
704 ** propagated back to the caller. Commenting this branch out means errno==0
705 ** will be handled by the "default:" case below.
706 */
drh734c9862008-11-28 15:37:20 +0000707 case 0:
708 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000709#endif
710
drh734c9862008-11-28 15:37:20 +0000711 case EAGAIN:
712 case ETIMEDOUT:
713 case EBUSY:
714 case EINTR:
715 case ENOLCK:
716 /* random NFS retry error, unless during file system support
717 * introspection, in which it actually means what it says */
718 return SQLITE_BUSY;
719
720 case EACCES:
721 /* EACCES is like EAGAIN during locking operations, but not any other time*/
722 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000723 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
724 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
725 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000726 return SQLITE_BUSY;
727 }
728 /* else fall through */
729 case EPERM:
730 return SQLITE_PERM;
731
danea83bc62011-04-01 11:56:32 +0000732 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
733 ** this module never makes such a call. And the code in SQLite itself
734 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
735 ** this case is also commented out. If the system does set errno to EDEADLK,
736 ** the default SQLITE_IOERR_XXX code will be returned. */
737#if 0
drh734c9862008-11-28 15:37:20 +0000738 case EDEADLK:
739 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000740#endif
drh734c9862008-11-28 15:37:20 +0000741
742#if EOPNOTSUPP!=ENOTSUP
743 case EOPNOTSUPP:
744 /* something went terribly awry, unless during file system support
745 * introspection, in which it actually means what it says */
746#endif
747#ifdef ENOTSUP
748 case ENOTSUP:
749 /* invalid fd, unless during file system support introspection, in which
750 * it actually means what it says */
751#endif
752 case EIO:
753 case EBADF:
754 case EINVAL:
755 case ENOTCONN:
756 case ENODEV:
757 case ENXIO:
758 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000759#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000760 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000761#endif
drh734c9862008-11-28 15:37:20 +0000762 case ENOSYS:
763 /* these should force the client to close the file and reconnect */
764
765 default:
766 return sqliteIOErr;
767 }
768}
769
770
771
772/******************************************************************************
773****************** Begin Unique File ID Utility Used By VxWorks ***************
774**
775** On most versions of unix, we can get a unique ID for a file by concatenating
776** the device number and the inode number. But this does not work on VxWorks.
777** On VxWorks, a unique file id must be based on the canonical filename.
778**
779** A pointer to an instance of the following structure can be used as a
780** unique file ID in VxWorks. Each instance of this structure contains
781** a copy of the canonical filename. There is also a reference count.
782** The structure is reclaimed when the number of pointers to it drops to
783** zero.
784**
785** There are never very many files open at one time and lookups are not
786** a performance-critical path, so it is sufficient to put these
787** structures on a linked list.
788*/
789struct vxworksFileId {
790 struct vxworksFileId *pNext; /* Next in a list of them all */
791 int nRef; /* Number of references to this one */
792 int nName; /* Length of the zCanonicalName[] string */
793 char *zCanonicalName; /* Canonical filename */
794};
795
796#if OS_VXWORKS
797/*
drh9b35ea62008-11-29 02:20:26 +0000798** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000799** variable:
800*/
801static struct vxworksFileId *vxworksFileList = 0;
802
803/*
804** Simplify a filename into its canonical form
805** by making the following changes:
806**
807** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000808** * convert /./ into just /
809** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000810**
811** Changes are made in-place. Return the new name length.
812**
813** The original filename is in z[0..n-1]. Return the number of
814** characters in the simplified name.
815*/
816static int vxworksSimplifyName(char *z, int n){
817 int i, j;
818 while( n>1 && z[n-1]=='/' ){ n--; }
819 for(i=j=0; i<n; i++){
820 if( z[i]=='/' ){
821 if( z[i+1]=='/' ) continue;
822 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
823 i += 1;
824 continue;
825 }
826 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
827 while( j>0 && z[j-1]!='/' ){ j--; }
828 if( j>0 ){ j--; }
829 i += 2;
830 continue;
831 }
832 }
833 z[j++] = z[i];
834 }
835 z[j] = 0;
836 return j;
837}
838
839/*
840** Find a unique file ID for the given absolute pathname. Return
841** a pointer to the vxworksFileId object. This pointer is the unique
842** file ID.
843**
844** The nRef field of the vxworksFileId object is incremented before
845** the object is returned. A new vxworksFileId object is created
846** and added to the global list if necessary.
847**
848** If a memory allocation error occurs, return NULL.
849*/
850static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
851 struct vxworksFileId *pNew; /* search key and new file ID */
852 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
853 int n; /* Length of zAbsoluteName string */
854
855 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000856 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000857 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
858 if( pNew==0 ) return 0;
859 pNew->zCanonicalName = (char*)&pNew[1];
860 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
861 n = vxworksSimplifyName(pNew->zCanonicalName, n);
862
863 /* Search for an existing entry that matching the canonical name.
864 ** If found, increment the reference count and return a pointer to
865 ** the existing file ID.
866 */
867 unixEnterMutex();
868 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
869 if( pCandidate->nName==n
870 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
871 ){
872 sqlite3_free(pNew);
873 pCandidate->nRef++;
874 unixLeaveMutex();
875 return pCandidate;
876 }
877 }
878
879 /* No match was found. We will make a new file ID */
880 pNew->nRef = 1;
881 pNew->nName = n;
882 pNew->pNext = vxworksFileList;
883 vxworksFileList = pNew;
884 unixLeaveMutex();
885 return pNew;
886}
887
888/*
889** Decrement the reference count on a vxworksFileId object. Free
890** the object when the reference count reaches zero.
891*/
892static void vxworksReleaseFileId(struct vxworksFileId *pId){
893 unixEnterMutex();
894 assert( pId->nRef>0 );
895 pId->nRef--;
896 if( pId->nRef==0 ){
897 struct vxworksFileId **pp;
898 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
899 assert( *pp==pId );
900 *pp = pId->pNext;
901 sqlite3_free(pId);
902 }
903 unixLeaveMutex();
904}
905#endif /* OS_VXWORKS */
906/*************** End of Unique File ID Utility Used By VxWorks ****************
907******************************************************************************/
908
909
910/******************************************************************************
911*************************** Posix Advisory Locking ****************************
912**
drh9b35ea62008-11-29 02:20:26 +0000913** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000914** section 6.5.2.2 lines 483 through 490 specify that when a process
915** sets or clears a lock, that operation overrides any prior locks set
916** by the same process. It does not explicitly say so, but this implies
917** that it overrides locks set by the same process using a different
918** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000919**
920** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000921** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
922**
923** Suppose ./file1 and ./file2 are really the same file (because
924** one is a hard or symbolic link to the other) then if you set
925** an exclusive lock on fd1, then try to get an exclusive lock
926** on fd2, it works. I would have expected the second lock to
927** fail since there was already a lock on the file due to fd1.
928** But not so. Since both locks came from the same process, the
929** second overrides the first, even though they were on different
930** file descriptors opened on different file names.
931**
drh734c9862008-11-28 15:37:20 +0000932** This means that we cannot use POSIX locks to synchronize file access
933** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000934** to synchronize access for threads in separate processes, but not
935** threads within the same process.
936**
937** To work around the problem, SQLite has to manage file locks internally
938** on its own. Whenever a new database is opened, we have to find the
939** specific inode of the database file (the inode is determined by the
940** st_dev and st_ino fields of the stat structure that fstat() fills in)
941** and check for locks already existing on that inode. When locks are
942** created or removed, we have to look at our own internal record of the
943** locks to see if another thread has previously set a lock on that same
944** inode.
945**
drh9b35ea62008-11-29 02:20:26 +0000946** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
947** For VxWorks, we have to use the alternative unique ID system based on
948** canonical filename and implemented in the previous division.)
949**
danielk1977ad94b582007-08-20 06:44:22 +0000950** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000951** descriptor. It is now a structure that holds the integer file
952** descriptor and a pointer to a structure that describes the internal
953** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000954** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000955** point to the same locking structure. The locking structure keeps
956** a reference count (so we will know when to delete it) and a "cnt"
957** field that tells us its internal lock status. cnt==0 means the
958** file is unlocked. cnt==-1 means the file has an exclusive lock.
959** cnt>0 means there are cnt shared locks on the file.
960**
961** Any attempt to lock or unlock a file first checks the locking
962** structure. The fcntl() system call is only invoked to set a
963** POSIX lock if the internal lock structure transitions between
964** a locked and an unlocked state.
965**
drh734c9862008-11-28 15:37:20 +0000966** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000967**
968** If you close a file descriptor that points to a file that has locks,
969** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000970** released. To work around this problem, each unixInodeInfo object
971** maintains a count of the number of pending locks on tha inode.
972** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000973** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000974** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000975** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000976** be closed and that list is walked (and cleared) when the last lock
977** clears.
978**
drh9b35ea62008-11-29 02:20:26 +0000979** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000980**
drh9b35ea62008-11-29 02:20:26 +0000981** Many older versions of linux use the LinuxThreads library which is
982** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000983** A cannot be modified or overridden by a different thread B.
984** Only thread A can modify the lock. Locking behavior is correct
985** if the appliation uses the newer Native Posix Thread Library (NPTL)
986** on linux - with NPTL a lock created by thread A can override locks
987** in thread B. But there is no way to know at compile-time which
988** threading library is being used. So there is no way to know at
989** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000990** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000991** current process.
drh5fdae772004-06-29 03:29:00 +0000992**
drh8af6c222010-05-14 12:43:01 +0000993** SQLite used to support LinuxThreads. But support for LinuxThreads
994** was dropped beginning with version 3.7.0. SQLite will still work with
995** LinuxThreads provided that (1) there is no more than one connection
996** per database file in the same process and (2) database connections
997** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +0000998*/
999
1000/*
1001** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001002** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001003*/
1004struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001005 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001006#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001007 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001008#else
drh107886a2008-11-21 22:21:50 +00001009 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001010#endif
1011};
1012
1013/*
drhbbd42a62004-05-22 17:41:58 +00001014** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001015** inode. Or, on LinuxThreads, there is one of these structures for
1016** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001017**
danielk1977ad94b582007-08-20 06:44:22 +00001018** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001019** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001020** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001021*/
drh8af6c222010-05-14 12:43:01 +00001022struct unixInodeInfo {
1023 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001024 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001025 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1026 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001027 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001028 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1029 int nLock; /* Number of outstanding file locks */
1030 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1031 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1032 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001033#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001034 unsigned long long sharedByte; /* for AFP simulated shared lock */
1035#endif
drh6c7d5c52008-11-21 20:32:33 +00001036#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001037 sem_t *pSem; /* Named POSIX semaphore */
1038 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001039#endif
drhbbd42a62004-05-22 17:41:58 +00001040};
1041
drhda0e7682008-07-30 15:27:54 +00001042/*
drh8af6c222010-05-14 12:43:01 +00001043** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001044*/
drhd91c68f2010-05-14 14:52:25 +00001045static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001046
drh5fdae772004-06-29 03:29:00 +00001047/*
dane18d4952011-02-21 11:46:24 +00001048**
1049** This function - unixLogError_x(), is only ever called via the macro
1050** unixLogError().
1051**
1052** It is invoked after an error occurs in an OS function and errno has been
1053** set. It logs a message using sqlite3_log() containing the current value of
1054** errno and, if possible, the human-readable equivalent from strerror() or
1055** strerror_r().
1056**
1057** The first argument passed to the macro should be the error code that
1058** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1059** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001060** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001061** if any.
1062*/
drh0e9365c2011-03-02 02:08:13 +00001063#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1064static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001065 int errcode, /* SQLite error code */
1066 const char *zFunc, /* Name of OS function that failed */
1067 const char *zPath, /* File path associated with error */
1068 int iLine /* Source line number where error occurred */
1069){
1070 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001071 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001072
1073 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1074 ** the strerror() function to obtain the human-readable error message
1075 ** equivalent to errno. Otherwise, use strerror_r().
1076 */
1077#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1078 char aErr[80];
1079 memset(aErr, 0, sizeof(aErr));
1080 zErr = aErr;
1081
1082 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001083 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001084 ** returns a pointer to a buffer containing the error message. That pointer
1085 ** may point to aErr[], or it may point to some static storage somewhere.
1086 ** Otherwise, assume that the system provides the POSIX version of
1087 ** strerror_r(), which always writes an error message into aErr[].
1088 **
1089 ** If the code incorrectly assumes that it is the POSIX version that is
1090 ** available, the error message will often be an empty string. Not a
1091 ** huge problem. Incorrectly concluding that the GNU version is available
1092 ** could lead to a segfault though.
1093 */
1094#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1095 zErr =
1096# endif
drh0e9365c2011-03-02 02:08:13 +00001097 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001098
1099#elif SQLITE_THREADSAFE
1100 /* This is a threadsafe build, but strerror_r() is not available. */
1101 zErr = "";
1102#else
1103 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001104 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001105#endif
1106
1107 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001108 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001109 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001110 "os_unix.c:%d: (%d) %s(%s) - %s",
1111 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001112 );
1113
1114 return errcode;
1115}
1116
drh0e9365c2011-03-02 02:08:13 +00001117/*
1118** Close a file descriptor.
1119**
1120** We assume that close() almost always works, since it is only in a
1121** very sick application or on a very sick platform that it might fail.
1122** If it does fail, simply leak the file descriptor, but do log the
1123** error.
1124**
1125** Note that it is not safe to retry close() after EINTR since the
1126** file descriptor might have already been reused by another thread.
1127** So we don't even try to recover from an EINTR. Just log the error
1128** and move on.
1129*/
1130static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001131 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001132 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1133 pFile ? pFile->zPath : 0, lineno);
1134 }
1135}
dane18d4952011-02-21 11:46:24 +00001136
1137/*
danb0ac3e32010-06-16 10:55:42 +00001138** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001139*/
drh0e9365c2011-03-02 02:08:13 +00001140static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001141 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001142 UnixUnusedFd *p;
1143 UnixUnusedFd *pNext;
1144 for(p=pInode->pUnused; p; p=pNext){
1145 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001146 robust_close(pFile, p->fd, __LINE__);
1147 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001148 }
drh0e9365c2011-03-02 02:08:13 +00001149 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001150}
1151
1152/*
drh8af6c222010-05-14 12:43:01 +00001153** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001154**
1155** The mutex entered using the unixEnterMutex() function must be held
1156** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001157*/
danb0ac3e32010-06-16 10:55:42 +00001158static void releaseInodeInfo(unixFile *pFile){
1159 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001160 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001161 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001162 pInode->nRef--;
1163 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001164 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001165 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001166 if( pInode->pPrev ){
1167 assert( pInode->pPrev->pNext==pInode );
1168 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001169 }else{
drh8af6c222010-05-14 12:43:01 +00001170 assert( inodeList==pInode );
1171 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001172 }
drh8af6c222010-05-14 12:43:01 +00001173 if( pInode->pNext ){
1174 assert( pInode->pNext->pPrev==pInode );
1175 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001176 }
drh8af6c222010-05-14 12:43:01 +00001177 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001178 }
drhbbd42a62004-05-22 17:41:58 +00001179 }
1180}
1181
1182/*
drh8af6c222010-05-14 12:43:01 +00001183** Given a file descriptor, locate the unixInodeInfo object that
1184** describes that file descriptor. Create a new one if necessary. The
1185** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001186**
dan9359c7b2009-08-21 08:29:10 +00001187** The mutex entered using the unixEnterMutex() function must be held
1188** when this function is called.
1189**
drh6c7d5c52008-11-21 20:32:33 +00001190** Return an appropriate error code.
1191*/
drh8af6c222010-05-14 12:43:01 +00001192static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001193 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001194 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001195){
1196 int rc; /* System call return code */
1197 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001198 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1199 struct stat statbuf; /* Low-level file information */
1200 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001201
dan9359c7b2009-08-21 08:29:10 +00001202 assert( unixMutexHeld() );
1203
drh6c7d5c52008-11-21 20:32:33 +00001204 /* Get low-level information about the file that we can used to
1205 ** create a unique name for the file.
1206 */
1207 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001208 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001209 if( rc!=0 ){
1210 pFile->lastErrno = errno;
1211#ifdef EOVERFLOW
1212 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1213#endif
1214 return SQLITE_IOERR;
1215 }
1216
drheb0d74f2009-02-03 15:27:02 +00001217#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001218 /* On OS X on an msdos filesystem, the inode number is reported
1219 ** incorrectly for zero-size files. See ticket #3260. To work
1220 ** around this problem (we consider it a bug in OS X, not SQLite)
1221 ** we always increase the file size to 1 by writing a single byte
1222 ** prior to accessing the inode number. The one byte written is
1223 ** an ASCII 'S' character which also happens to be the first byte
1224 ** in the header of every SQLite database. In this way, if there
1225 ** is a race condition such that another thread has already populated
1226 ** the first page of the database, no damage is done.
1227 */
drh7ed97b92010-01-20 13:07:21 +00001228 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001229 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001230 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001231 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001232 return SQLITE_IOERR;
1233 }
drh99ab3b12011-03-02 15:09:07 +00001234 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001235 if( rc!=0 ){
1236 pFile->lastErrno = errno;
1237 return SQLITE_IOERR;
1238 }
1239 }
drheb0d74f2009-02-03 15:27:02 +00001240#endif
drh6c7d5c52008-11-21 20:32:33 +00001241
drh8af6c222010-05-14 12:43:01 +00001242 memset(&fileId, 0, sizeof(fileId));
1243 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001244#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001245 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001246#else
drh8af6c222010-05-14 12:43:01 +00001247 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001248#endif
drh8af6c222010-05-14 12:43:01 +00001249 pInode = inodeList;
1250 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1251 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001252 }
drh8af6c222010-05-14 12:43:01 +00001253 if( pInode==0 ){
1254 pInode = sqlite3_malloc( sizeof(*pInode) );
1255 if( pInode==0 ){
1256 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001257 }
drh8af6c222010-05-14 12:43:01 +00001258 memset(pInode, 0, sizeof(*pInode));
1259 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1260 pInode->nRef = 1;
1261 pInode->pNext = inodeList;
1262 pInode->pPrev = 0;
1263 if( inodeList ) inodeList->pPrev = pInode;
1264 inodeList = pInode;
1265 }else{
1266 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001267 }
drh8af6c222010-05-14 12:43:01 +00001268 *ppInode = pInode;
1269 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001270}
drh6c7d5c52008-11-21 20:32:33 +00001271
aswift5b1a2562008-08-22 00:22:35 +00001272
1273/*
danielk197713adf8a2004-06-03 16:08:41 +00001274** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001275** file by this or any other process. If such a lock is held, set *pResOut
1276** to a non-zero value otherwise *pResOut is set to zero. The return value
1277** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001278*/
danielk1977861f7452008-06-05 11:39:11 +00001279static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001280 int rc = SQLITE_OK;
1281 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001282 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001283
danielk1977861f7452008-06-05 11:39:11 +00001284 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1285
drh054889e2005-11-30 03:20:31 +00001286 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001287 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001288
1289 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001290 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001291 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001292 }
1293
drh2ac3ee92004-06-07 16:27:46 +00001294 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001295 */
danielk197709480a92009-02-09 05:32:32 +00001296#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001297 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001298 struct flock lock;
1299 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001300 lock.l_start = RESERVED_BYTE;
1301 lock.l_len = 1;
1302 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001303 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1304 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1305 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001306 } else if( lock.l_type!=F_UNLCK ){
1307 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001308 }
1309 }
danielk197709480a92009-02-09 05:32:32 +00001310#endif
danielk197713adf8a2004-06-03 16:08:41 +00001311
drh6c7d5c52008-11-21 20:32:33 +00001312 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001313 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001314
aswift5b1a2562008-08-22 00:22:35 +00001315 *pResOut = reserved;
1316 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001317}
1318
1319/*
drha7e61d82011-03-12 17:02:57 +00001320** Attempt to set a system-lock on the file pFile. The lock is
1321** described by pLock.
1322**
drh77197112011-03-15 19:08:48 +00001323** If the pFile was opened read/write from unix-excl, then the only lock
1324** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001325** the first time any lock is attempted. All subsequent system locking
1326** operations become no-ops. Locking operations still happen internally,
1327** in order to coordinate access between separate database connections
1328** within this process, but all of that is handled in memory and the
1329** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001330**
1331** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1332** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1333** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001334**
1335** Zero is returned if the call completes successfully, or -1 if a call
1336** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001337*/
1338static int unixFileLock(unixFile *pFile, struct flock *pLock){
1339 int rc;
drh3cb93392011-03-12 18:10:44 +00001340 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001341 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001342 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001343 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1344 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1345 ){
drh3cb93392011-03-12 18:10:44 +00001346 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001347 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001348 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001349 lock.l_whence = SEEK_SET;
1350 lock.l_start = SHARED_FIRST;
1351 lock.l_len = SHARED_SIZE;
1352 lock.l_type = F_WRLCK;
1353 rc = osFcntl(pFile->h, F_SETLK, &lock);
1354 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001355 pInode->bProcessLock = 1;
1356 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001357 }else{
1358 rc = 0;
1359 }
1360 }else{
1361 rc = osFcntl(pFile->h, F_SETLK, pLock);
1362 }
1363 return rc;
1364}
1365
1366/*
drh308c2a52010-05-14 11:30:18 +00001367** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001368** of the following:
1369**
drh2ac3ee92004-06-07 16:27:46 +00001370** (1) SHARED_LOCK
1371** (2) RESERVED_LOCK
1372** (3) PENDING_LOCK
1373** (4) EXCLUSIVE_LOCK
1374**
drhb3e04342004-06-08 00:47:47 +00001375** Sometimes when requesting one lock state, additional lock states
1376** are inserted in between. The locking might fail on one of the later
1377** transitions leaving the lock state different from what it started but
1378** still short of its goal. The following chart shows the allowed
1379** transitions and the inserted intermediate states:
1380**
1381** UNLOCKED -> SHARED
1382** SHARED -> RESERVED
1383** SHARED -> (PENDING) -> EXCLUSIVE
1384** RESERVED -> (PENDING) -> EXCLUSIVE
1385** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001386**
drha6abd042004-06-09 17:37:22 +00001387** This routine will only increase a lock. Use the sqlite3OsUnlock()
1388** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001389*/
drh308c2a52010-05-14 11:30:18 +00001390static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001391 /* The following describes the implementation of the various locks and
1392 ** lock transitions in terms of the POSIX advisory shared and exclusive
1393 ** lock primitives (called read-locks and write-locks below, to avoid
1394 ** confusion with SQLite lock names). The algorithms are complicated
1395 ** slightly in order to be compatible with windows systems simultaneously
1396 ** accessing the same database file, in case that is ever required.
1397 **
1398 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1399 ** byte', each single bytes at well known offsets, and the 'shared byte
1400 ** range', a range of 510 bytes at a well known offset.
1401 **
1402 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1403 ** byte'. If this is successful, a random byte from the 'shared byte
1404 ** range' is read-locked and the lock on the 'pending byte' released.
1405 **
danielk197790ba3bd2004-06-25 08:32:25 +00001406 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1407 ** A RESERVED lock is implemented by grabbing a write-lock on the
1408 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001409 **
1410 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001411 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1412 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1413 ** obtained, but existing SHARED locks are allowed to persist. A process
1414 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1415 ** This property is used by the algorithm for rolling back a journal file
1416 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001417 **
danielk197790ba3bd2004-06-25 08:32:25 +00001418 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1419 ** implemented by obtaining a write-lock on the entire 'shared byte
1420 ** range'. Since all other locks require a read-lock on one of the bytes
1421 ** within this range, this ensures that no other locks are held on the
1422 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001423 **
1424 ** The reason a single byte cannot be used instead of the 'shared byte
1425 ** range' is that some versions of windows do not support read-locks. By
1426 ** locking a random byte from a range, concurrent SHARED locks may exist
1427 ** even if the locking primitive used is always a write-lock.
1428 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001429 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001430 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001431 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001432 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001433 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001434
drh054889e2005-11-30 03:20:31 +00001435 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001436 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1437 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001438 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001439
1440 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001441 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001442 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001443 */
drh308c2a52010-05-14 11:30:18 +00001444 if( pFile->eFileLock>=eFileLock ){
1445 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1446 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001447 return SQLITE_OK;
1448 }
1449
drh0c2694b2009-09-03 16:23:44 +00001450 /* Make sure the locking sequence is correct.
1451 ** (1) We never move from unlocked to anything higher than shared lock.
1452 ** (2) SQLite never explicitly requests a pendig lock.
1453 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001454 */
drh308c2a52010-05-14 11:30:18 +00001455 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1456 assert( eFileLock!=PENDING_LOCK );
1457 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001458
drh8af6c222010-05-14 12:43:01 +00001459 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001460 */
drh6c7d5c52008-11-21 20:32:33 +00001461 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001462 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001463
danielk1977ad94b582007-08-20 06:44:22 +00001464 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001465 ** handle that precludes the requested lock, return BUSY.
1466 */
drh8af6c222010-05-14 12:43:01 +00001467 if( (pFile->eFileLock!=pInode->eFileLock &&
1468 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001469 ){
1470 rc = SQLITE_BUSY;
1471 goto end_lock;
1472 }
1473
1474 /* If a SHARED lock is requested, and some thread using this PID already
1475 ** has a SHARED or RESERVED lock, then increment reference counts and
1476 ** return SQLITE_OK.
1477 */
drh308c2a52010-05-14 11:30:18 +00001478 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001479 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001480 assert( eFileLock==SHARED_LOCK );
1481 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001482 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001483 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001484 pInode->nShared++;
1485 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001486 goto end_lock;
1487 }
1488
danielk19779a1d0ab2004-06-01 14:09:28 +00001489
drh3cde3bb2004-06-12 02:17:14 +00001490 /* A PENDING lock is needed before acquiring a SHARED lock and before
1491 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1492 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001493 */
drh0c2694b2009-09-03 16:23:44 +00001494 lock.l_len = 1L;
1495 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001496 if( eFileLock==SHARED_LOCK
1497 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001498 ){
drh308c2a52010-05-14 11:30:18 +00001499 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001500 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001501 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001502 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001503 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001504 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001505 pFile->lastErrno = tErrno;
1506 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001507 goto end_lock;
1508 }
drh3cde3bb2004-06-12 02:17:14 +00001509 }
1510
1511
1512 /* If control gets to this point, then actually go ahead and make
1513 ** operating system calls for the specified lock.
1514 */
drh308c2a52010-05-14 11:30:18 +00001515 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001516 assert( pInode->nShared==0 );
1517 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001518 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001519
drh2ac3ee92004-06-07 16:27:46 +00001520 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001521 lock.l_start = SHARED_FIRST;
1522 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001523 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001524 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001525 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001526 }
dan661d71a2011-03-30 19:08:03 +00001527
drh2ac3ee92004-06-07 16:27:46 +00001528 /* Drop the temporary PENDING lock */
1529 lock.l_start = PENDING_BYTE;
1530 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001531 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001532 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1533 /* This could happen with a network mount */
1534 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001535 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001536 }
dan661d71a2011-03-30 19:08:03 +00001537
1538 if( rc ){
1539 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001540 pFile->lastErrno = tErrno;
1541 }
dan661d71a2011-03-30 19:08:03 +00001542 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001543 }else{
drh308c2a52010-05-14 11:30:18 +00001544 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001545 pInode->nLock++;
1546 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001547 }
drh8af6c222010-05-14 12:43:01 +00001548 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001549 /* We are trying for an exclusive lock but another thread in this
1550 ** same process is still holding a shared lock. */
1551 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001552 }else{
drh3cde3bb2004-06-12 02:17:14 +00001553 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001554 ** assumed that there is a SHARED or greater lock on the file
1555 ** already.
1556 */
drh308c2a52010-05-14 11:30:18 +00001557 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001558 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001559
1560 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1561 if( eFileLock==RESERVED_LOCK ){
1562 lock.l_start = RESERVED_BYTE;
1563 lock.l_len = 1L;
1564 }else{
1565 lock.l_start = SHARED_FIRST;
1566 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001567 }
dan661d71a2011-03-30 19:08:03 +00001568
1569 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001570 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001571 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001572 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001573 pFile->lastErrno = tErrno;
1574 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001575 }
drhbbd42a62004-05-22 17:41:58 +00001576 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001577
drh8f941bc2009-01-14 23:03:40 +00001578
drhd3d8c042012-05-29 17:02:40 +00001579#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001580 /* Set up the transaction-counter change checking flags when
1581 ** transitioning from a SHARED to a RESERVED lock. The change
1582 ** from SHARED to RESERVED marks the beginning of a normal
1583 ** write operation (not a hot journal rollback).
1584 */
1585 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001586 && pFile->eFileLock<=SHARED_LOCK
1587 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001588 ){
1589 pFile->transCntrChng = 0;
1590 pFile->dbUpdate = 0;
1591 pFile->inNormalWrite = 1;
1592 }
1593#endif
1594
1595
danielk1977ecb2a962004-06-02 06:30:16 +00001596 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001597 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001598 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001599 }else if( eFileLock==EXCLUSIVE_LOCK ){
1600 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001601 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001602 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001603
1604end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001605 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001606 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1607 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001608 return rc;
1609}
1610
1611/*
dan08da86a2009-08-21 17:18:03 +00001612** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001613** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001614*/
1615static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001616 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001617 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001618 p->pNext = pInode->pUnused;
1619 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001620 pFile->h = -1;
1621 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001622}
1623
1624/*
drh308c2a52010-05-14 11:30:18 +00001625** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001626** must be either NO_LOCK or SHARED_LOCK.
1627**
1628** If the locking level of the file descriptor is already at or below
1629** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001630**
1631** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1632** the byte range is divided into 2 parts and the first part is unlocked then
1633** set to a read lock, then the other part is simply unlocked. This works
1634** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1635** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001636*/
drha7e61d82011-03-12 17:02:57 +00001637static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001638 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001639 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001640 struct flock lock;
1641 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001642
drh054889e2005-11-30 03:20:31 +00001643 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001644 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001645 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001646 getpid()));
drha6abd042004-06-09 17:37:22 +00001647
drh308c2a52010-05-14 11:30:18 +00001648 assert( eFileLock<=SHARED_LOCK );
1649 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001650 return SQLITE_OK;
1651 }
drh6c7d5c52008-11-21 20:32:33 +00001652 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001653 pInode = pFile->pInode;
1654 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001655 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001656 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001657
drhd3d8c042012-05-29 17:02:40 +00001658#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001659 /* When reducing a lock such that other processes can start
1660 ** reading the database file again, make sure that the
1661 ** transaction counter was updated if any part of the database
1662 ** file changed. If the transaction counter is not updated,
1663 ** other connections to the same file might not realize that
1664 ** the file has changed and hence might not know to flush their
1665 ** cache. The use of a stale cache can lead to database corruption.
1666 */
drh8f941bc2009-01-14 23:03:40 +00001667 pFile->inNormalWrite = 0;
1668#endif
1669
drh7ed97b92010-01-20 13:07:21 +00001670 /* downgrading to a shared lock on NFS involves clearing the write lock
1671 ** before establishing the readlock - to avoid a race condition we downgrade
1672 ** the lock in 2 blocks, so that part of the range will be covered by a
1673 ** write lock until the rest is covered by a read lock:
1674 ** 1: [WWWWW]
1675 ** 2: [....W]
1676 ** 3: [RRRRW]
1677 ** 4: [RRRR.]
1678 */
drh308c2a52010-05-14 11:30:18 +00001679 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001680
1681#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001682 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001683 assert( handleNFSUnlock==0 );
1684#endif
1685#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001686 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001687 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001688 off_t divSize = SHARED_SIZE - 1;
1689
1690 lock.l_type = F_UNLCK;
1691 lock.l_whence = SEEK_SET;
1692 lock.l_start = SHARED_FIRST;
1693 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001694 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001695 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001696 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001697 if( IS_LOCK_ERROR(rc) ){
1698 pFile->lastErrno = tErrno;
1699 }
1700 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001701 }
drh7ed97b92010-01-20 13:07:21 +00001702 lock.l_type = F_RDLCK;
1703 lock.l_whence = SEEK_SET;
1704 lock.l_start = SHARED_FIRST;
1705 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001706 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001707 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001708 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1709 if( IS_LOCK_ERROR(rc) ){
1710 pFile->lastErrno = tErrno;
1711 }
1712 goto end_unlock;
1713 }
1714 lock.l_type = F_UNLCK;
1715 lock.l_whence = SEEK_SET;
1716 lock.l_start = SHARED_FIRST+divSize;
1717 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001718 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001719 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001720 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001721 if( IS_LOCK_ERROR(rc) ){
1722 pFile->lastErrno = tErrno;
1723 }
1724 goto end_unlock;
1725 }
drh30f776f2011-02-25 03:25:07 +00001726 }else
1727#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1728 {
drh7ed97b92010-01-20 13:07:21 +00001729 lock.l_type = F_RDLCK;
1730 lock.l_whence = SEEK_SET;
1731 lock.l_start = SHARED_FIRST;
1732 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001733 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001734 /* In theory, the call to unixFileLock() cannot fail because another
1735 ** process is holding an incompatible lock. If it does, this
1736 ** indicates that the other process is not following the locking
1737 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1738 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1739 ** an assert to fail). */
1740 rc = SQLITE_IOERR_RDLOCK;
1741 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001742 goto end_unlock;
1743 }
drh9c105bb2004-10-02 20:38:28 +00001744 }
1745 }
drhbbd42a62004-05-22 17:41:58 +00001746 lock.l_type = F_UNLCK;
1747 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001748 lock.l_start = PENDING_BYTE;
1749 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001750 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001751 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001752 }else{
danea83bc62011-04-01 11:56:32 +00001753 rc = SQLITE_IOERR_UNLOCK;
1754 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001755 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001756 }
drhbbd42a62004-05-22 17:41:58 +00001757 }
drh308c2a52010-05-14 11:30:18 +00001758 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001759 /* Decrement the shared lock counter. Release the lock using an
1760 ** OS call only when all threads in this same process have released
1761 ** the lock.
1762 */
drh8af6c222010-05-14 12:43:01 +00001763 pInode->nShared--;
1764 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001765 lock.l_type = F_UNLCK;
1766 lock.l_whence = SEEK_SET;
1767 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001768 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001769 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001770 }else{
danea83bc62011-04-01 11:56:32 +00001771 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001772 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001773 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001774 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001775 }
drha6abd042004-06-09 17:37:22 +00001776 }
1777
drhbbd42a62004-05-22 17:41:58 +00001778 /* Decrement the count of locks against this same file. When the
1779 ** count reaches zero, close any other file descriptors whose close
1780 ** was deferred because of outstanding locks.
1781 */
drh8af6c222010-05-14 12:43:01 +00001782 pInode->nLock--;
1783 assert( pInode->nLock>=0 );
1784 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001785 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001786 }
1787 }
drhf2f105d2012-08-20 15:53:54 +00001788
aswift5b1a2562008-08-22 00:22:35 +00001789end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001790 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001791 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001792 return rc;
drhbbd42a62004-05-22 17:41:58 +00001793}
1794
1795/*
drh308c2a52010-05-14 11:30:18 +00001796** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001797** must be either NO_LOCK or SHARED_LOCK.
1798**
1799** If the locking level of the file descriptor is already at or below
1800** the requested locking level, this routine is a no-op.
1801*/
drh308c2a52010-05-14 11:30:18 +00001802static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001803 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001804}
1805
1806/*
danielk1977e339d652008-06-28 11:23:00 +00001807** This function performs the parts of the "close file" operation
1808** common to all locking schemes. It closes the directory and file
1809** handles, if they are valid, and sets all fields of the unixFile
1810** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001811**
1812** It is *not* necessary to hold the mutex when this routine is called,
1813** even on VxWorks. A mutex will be acquired on VxWorks by the
1814** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001815*/
1816static int closeUnixFile(sqlite3_file *id){
1817 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001818 if( pFile->h>=0 ){
1819 robust_close(pFile, pFile->h, __LINE__);
1820 pFile->h = -1;
1821 }
1822#if OS_VXWORKS
1823 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001824 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001825 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001826 }
1827 vxworksReleaseFileId(pFile->pId);
1828 pFile->pId = 0;
1829 }
1830#endif
1831 OSTRACE(("CLOSE %-3d\n", pFile->h));
1832 OpenCounter(-1);
1833 sqlite3_free(pFile->pUnused);
1834 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001835 return SQLITE_OK;
1836}
1837
1838/*
danielk1977e3026632004-06-22 11:29:02 +00001839** Close a file.
1840*/
danielk197762079062007-08-15 17:08:46 +00001841static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001842 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001843 unixFile *pFile = (unixFile *)id;
1844 unixUnlock(id, NO_LOCK);
1845 unixEnterMutex();
1846
1847 /* unixFile.pInode is always valid here. Otherwise, a different close
1848 ** routine (e.g. nolockClose()) would be called instead.
1849 */
1850 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1851 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1852 /* If there are outstanding locks, do not actually close the file just
1853 ** yet because that would clear those locks. Instead, add the file
1854 ** descriptor to pInode->pUnused list. It will be automatically closed
1855 ** when the last lock is cleared.
1856 */
1857 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001858 }
dan661d71a2011-03-30 19:08:03 +00001859 releaseInodeInfo(pFile);
1860 rc = closeUnixFile(id);
1861 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001862 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001863}
1864
drh734c9862008-11-28 15:37:20 +00001865/************** End of the posix advisory lock implementation *****************
1866******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001867
drh734c9862008-11-28 15:37:20 +00001868/******************************************************************************
1869****************************** No-op Locking **********************************
1870**
1871** Of the various locking implementations available, this is by far the
1872** simplest: locking is ignored. No attempt is made to lock the database
1873** file for reading or writing.
1874**
1875** This locking mode is appropriate for use on read-only databases
1876** (ex: databases that are burned into CD-ROM, for example.) It can
1877** also be used if the application employs some external mechanism to
1878** prevent simultaneous access of the same database by two or more
1879** database connections. But there is a serious risk of database
1880** corruption if this locking mode is used in situations where multiple
1881** database connections are accessing the same database file at the same
1882** time and one or more of those connections are writing.
1883*/
drhbfe66312006-10-03 17:40:40 +00001884
drh734c9862008-11-28 15:37:20 +00001885static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1886 UNUSED_PARAMETER(NotUsed);
1887 *pResOut = 0;
1888 return SQLITE_OK;
1889}
drh734c9862008-11-28 15:37:20 +00001890static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1891 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1892 return SQLITE_OK;
1893}
drh734c9862008-11-28 15:37:20 +00001894static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1895 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1896 return SQLITE_OK;
1897}
1898
1899/*
drh9b35ea62008-11-29 02:20:26 +00001900** Close the file.
drh734c9862008-11-28 15:37:20 +00001901*/
1902static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001903 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001904}
1905
1906/******************* End of the no-op lock implementation *********************
1907******************************************************************************/
1908
1909/******************************************************************************
1910************************* Begin dot-file Locking ******************************
1911**
drh0c2694b2009-09-03 16:23:44 +00001912** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001913** files (really a directory) to control access to the database. This works
1914** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001915**
1916** (1) There is zero concurrency. A single reader blocks all other
1917** connections from reading or writing the database.
1918**
1919** (2) An application crash or power loss can leave stale lock files
1920** sitting around that need to be cleared manually.
1921**
1922** Nevertheless, a dotlock is an appropriate locking mode for use if no
1923** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001924**
drh9ef6bc42011-11-04 02:24:02 +00001925** Dotfile locking works by creating a subdirectory in the same directory as
1926** the database and with the same name but with a ".lock" extension added.
1927** The existance of a lock directory implies an EXCLUSIVE lock. All other
1928** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001929*/
1930
1931/*
1932** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001933** lock directory.
drh734c9862008-11-28 15:37:20 +00001934*/
1935#define DOTLOCK_SUFFIX ".lock"
1936
drh7708e972008-11-29 00:56:52 +00001937/*
1938** This routine checks if there is a RESERVED lock held on the specified
1939** file by this or any other process. If such a lock is held, set *pResOut
1940** to a non-zero value otherwise *pResOut is set to zero. The return value
1941** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1942**
1943** In dotfile locking, either a lock exists or it does not. So in this
1944** variation of CheckReservedLock(), *pResOut is set to true if any lock
1945** is held on the file and false if the file is unlocked.
1946*/
drh734c9862008-11-28 15:37:20 +00001947static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1948 int rc = SQLITE_OK;
1949 int reserved = 0;
1950 unixFile *pFile = (unixFile*)id;
1951
1952 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1953
1954 assert( pFile );
1955
1956 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001957 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001958 /* Either this connection or some other connection in the same process
1959 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001960 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001961 }else{
1962 /* The lock is held if and only if the lockfile exists */
1963 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001964 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001965 }
drh308c2a52010-05-14 11:30:18 +00001966 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001967 *pResOut = reserved;
1968 return rc;
1969}
1970
drh7708e972008-11-29 00:56:52 +00001971/*
drh308c2a52010-05-14 11:30:18 +00001972** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001973** of the following:
1974**
1975** (1) SHARED_LOCK
1976** (2) RESERVED_LOCK
1977** (3) PENDING_LOCK
1978** (4) EXCLUSIVE_LOCK
1979**
1980** Sometimes when requesting one lock state, additional lock states
1981** are inserted in between. The locking might fail on one of the later
1982** transitions leaving the lock state different from what it started but
1983** still short of its goal. The following chart shows the allowed
1984** transitions and the inserted intermediate states:
1985**
1986** UNLOCKED -> SHARED
1987** SHARED -> RESERVED
1988** SHARED -> (PENDING) -> EXCLUSIVE
1989** RESERVED -> (PENDING) -> EXCLUSIVE
1990** PENDING -> EXCLUSIVE
1991**
1992** This routine will only increase a lock. Use the sqlite3OsUnlock()
1993** routine to lower a locking level.
1994**
1995** With dotfile locking, we really only support state (4): EXCLUSIVE.
1996** But we track the other locking levels internally.
1997*/
drh308c2a52010-05-14 11:30:18 +00001998static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00001999 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002000 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002001 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002002
drh7708e972008-11-29 00:56:52 +00002003
2004 /* If we have any lock, then the lock file already exists. All we have
2005 ** to do is adjust our internal record of the lock level.
2006 */
drh308c2a52010-05-14 11:30:18 +00002007 if( pFile->eFileLock > NO_LOCK ){
2008 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002009 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002010#ifdef HAVE_UTIME
2011 utime(zLockFile, NULL);
2012#else
drh734c9862008-11-28 15:37:20 +00002013 utimes(zLockFile, NULL);
2014#endif
drh7708e972008-11-29 00:56:52 +00002015 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002016 }
2017
2018 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002019 rc = osMkdir(zLockFile, 0777);
2020 if( rc<0 ){
2021 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002022 int tErrno = errno;
2023 if( EEXIST == tErrno ){
2024 rc = SQLITE_BUSY;
2025 } else {
2026 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2027 if( IS_LOCK_ERROR(rc) ){
2028 pFile->lastErrno = tErrno;
2029 }
2030 }
drh7708e972008-11-29 00:56:52 +00002031 return rc;
drh734c9862008-11-28 15:37:20 +00002032 }
drh734c9862008-11-28 15:37:20 +00002033
2034 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002035 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002036 return rc;
2037}
2038
drh7708e972008-11-29 00:56:52 +00002039/*
drh308c2a52010-05-14 11:30:18 +00002040** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002041** must be either NO_LOCK or SHARED_LOCK.
2042**
2043** If the locking level of the file descriptor is already at or below
2044** the requested locking level, this routine is a no-op.
2045**
2046** When the locking level reaches NO_LOCK, delete the lock file.
2047*/
drh308c2a52010-05-14 11:30:18 +00002048static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002049 unixFile *pFile = (unixFile*)id;
2050 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002051 int rc;
drh734c9862008-11-28 15:37:20 +00002052
2053 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002054 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002055 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002056 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002057
2058 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002059 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002060 return SQLITE_OK;
2061 }
drh7708e972008-11-29 00:56:52 +00002062
2063 /* To downgrade to shared, simply update our internal notion of the
2064 ** lock state. No need to mess with the file on disk.
2065 */
drh308c2a52010-05-14 11:30:18 +00002066 if( eFileLock==SHARED_LOCK ){
2067 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002068 return SQLITE_OK;
2069 }
2070
drh7708e972008-11-29 00:56:52 +00002071 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002072 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002073 rc = osRmdir(zLockFile);
2074 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2075 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002076 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002077 rc = 0;
drh734c9862008-11-28 15:37:20 +00002078 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002079 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002080 }
2081 if( IS_LOCK_ERROR(rc) ){
2082 pFile->lastErrno = tErrno;
2083 }
2084 return rc;
2085 }
drh308c2a52010-05-14 11:30:18 +00002086 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002087 return SQLITE_OK;
2088}
2089
2090/*
drh9b35ea62008-11-29 02:20:26 +00002091** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002092*/
2093static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002094 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002095 if( id ){
2096 unixFile *pFile = (unixFile*)id;
2097 dotlockUnlock(id, NO_LOCK);
2098 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002099 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002100 }
drh734c9862008-11-28 15:37:20 +00002101 return rc;
2102}
2103/****************** End of the dot-file lock implementation *******************
2104******************************************************************************/
2105
2106/******************************************************************************
2107************************** Begin flock Locking ********************************
2108**
2109** Use the flock() system call to do file locking.
2110**
drh6b9d6dd2008-12-03 19:34:47 +00002111** flock() locking is like dot-file locking in that the various
2112** fine-grain locking levels supported by SQLite are collapsed into
2113** a single exclusive lock. In other words, SHARED, RESERVED, and
2114** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2115** still works when you do this, but concurrency is reduced since
2116** only a single process can be reading the database at a time.
2117**
drh734c9862008-11-28 15:37:20 +00002118** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2119** compiling for VXWORKS.
2120*/
2121#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002122
drh6b9d6dd2008-12-03 19:34:47 +00002123/*
drhff812312011-02-23 13:33:46 +00002124** Retry flock() calls that fail with EINTR
2125*/
2126#ifdef EINTR
2127static int robust_flock(int fd, int op){
2128 int rc;
2129 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2130 return rc;
2131}
2132#else
drh5c819272011-02-23 14:00:12 +00002133# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002134#endif
2135
2136
2137/*
drh6b9d6dd2008-12-03 19:34:47 +00002138** This routine checks if there is a RESERVED lock held on the specified
2139** file by this or any other process. If such a lock is held, set *pResOut
2140** to a non-zero value otherwise *pResOut is set to zero. The return value
2141** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2142*/
drh734c9862008-11-28 15:37:20 +00002143static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2144 int rc = SQLITE_OK;
2145 int reserved = 0;
2146 unixFile *pFile = (unixFile*)id;
2147
2148 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2149
2150 assert( pFile );
2151
2152 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002153 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002154 reserved = 1;
2155 }
2156
2157 /* Otherwise see if some other process holds it. */
2158 if( !reserved ){
2159 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002160 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002161 if( !lrc ){
2162 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002163 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002164 if ( lrc ) {
2165 int tErrno = errno;
2166 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002167 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002168 if( IS_LOCK_ERROR(lrc) ){
2169 pFile->lastErrno = tErrno;
2170 rc = lrc;
2171 }
2172 }
2173 } else {
2174 int tErrno = errno;
2175 reserved = 1;
2176 /* someone else might have it reserved */
2177 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2178 if( IS_LOCK_ERROR(lrc) ){
2179 pFile->lastErrno = tErrno;
2180 rc = lrc;
2181 }
2182 }
2183 }
drh308c2a52010-05-14 11:30:18 +00002184 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002185
2186#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2187 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2188 rc = SQLITE_OK;
2189 reserved=1;
2190 }
2191#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2192 *pResOut = reserved;
2193 return rc;
2194}
2195
drh6b9d6dd2008-12-03 19:34:47 +00002196/*
drh308c2a52010-05-14 11:30:18 +00002197** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002198** of the following:
2199**
2200** (1) SHARED_LOCK
2201** (2) RESERVED_LOCK
2202** (3) PENDING_LOCK
2203** (4) EXCLUSIVE_LOCK
2204**
2205** Sometimes when requesting one lock state, additional lock states
2206** are inserted in between. The locking might fail on one of the later
2207** transitions leaving the lock state different from what it started but
2208** still short of its goal. The following chart shows the allowed
2209** transitions and the inserted intermediate states:
2210**
2211** UNLOCKED -> SHARED
2212** SHARED -> RESERVED
2213** SHARED -> (PENDING) -> EXCLUSIVE
2214** RESERVED -> (PENDING) -> EXCLUSIVE
2215** PENDING -> EXCLUSIVE
2216**
2217** flock() only really support EXCLUSIVE locks. We track intermediate
2218** lock states in the sqlite3_file structure, but all locks SHARED or
2219** above are really EXCLUSIVE locks and exclude all other processes from
2220** access the file.
2221**
2222** This routine will only increase a lock. Use the sqlite3OsUnlock()
2223** routine to lower a locking level.
2224*/
drh308c2a52010-05-14 11:30:18 +00002225static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002226 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002227 unixFile *pFile = (unixFile*)id;
2228
2229 assert( pFile );
2230
2231 /* if we already have a lock, it is exclusive.
2232 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002233 if (pFile->eFileLock > NO_LOCK) {
2234 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002235 return SQLITE_OK;
2236 }
2237
2238 /* grab an exclusive lock */
2239
drhff812312011-02-23 13:33:46 +00002240 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002241 int tErrno = errno;
2242 /* didn't get, must be busy */
2243 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2244 if( IS_LOCK_ERROR(rc) ){
2245 pFile->lastErrno = tErrno;
2246 }
2247 } else {
2248 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002249 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002250 }
drh308c2a52010-05-14 11:30:18 +00002251 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2252 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002253#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2254 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2255 rc = SQLITE_BUSY;
2256 }
2257#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2258 return rc;
2259}
2260
drh6b9d6dd2008-12-03 19:34:47 +00002261
2262/*
drh308c2a52010-05-14 11:30:18 +00002263** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002264** must be either NO_LOCK or SHARED_LOCK.
2265**
2266** If the locking level of the file descriptor is already at or below
2267** the requested locking level, this routine is a no-op.
2268*/
drh308c2a52010-05-14 11:30:18 +00002269static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002270 unixFile *pFile = (unixFile*)id;
2271
2272 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002273 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2274 pFile->eFileLock, getpid()));
2275 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002276
2277 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002278 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002279 return SQLITE_OK;
2280 }
2281
2282 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002283 if (eFileLock==SHARED_LOCK) {
2284 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002285 return SQLITE_OK;
2286 }
2287
2288 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002289 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002290#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002291 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002292#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002293 return SQLITE_IOERR_UNLOCK;
2294 }else{
drh308c2a52010-05-14 11:30:18 +00002295 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002296 return SQLITE_OK;
2297 }
2298}
2299
2300/*
2301** Close a file.
2302*/
2303static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002304 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002305 if( id ){
2306 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002307 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002308 }
drh5a05be12012-10-09 18:51:44 +00002309 return rc;
drh734c9862008-11-28 15:37:20 +00002310}
2311
2312#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2313
2314/******************* End of the flock lock implementation *********************
2315******************************************************************************/
2316
2317/******************************************************************************
2318************************ Begin Named Semaphore Locking ************************
2319**
2320** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002321**
2322** Semaphore locking is like dot-lock and flock in that it really only
2323** supports EXCLUSIVE locking. Only a single process can read or write
2324** the database file at a time. This reduces potential concurrency, but
2325** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002326*/
2327#if OS_VXWORKS
2328
drh6b9d6dd2008-12-03 19:34:47 +00002329/*
2330** This routine checks if there is a RESERVED lock held on the specified
2331** file by this or any other process. If such a lock is held, set *pResOut
2332** to a non-zero value otherwise *pResOut is set to zero. The return value
2333** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2334*/
drh734c9862008-11-28 15:37:20 +00002335static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2336 int rc = SQLITE_OK;
2337 int reserved = 0;
2338 unixFile *pFile = (unixFile*)id;
2339
2340 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2341
2342 assert( pFile );
2343
2344 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002345 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002346 reserved = 1;
2347 }
2348
2349 /* Otherwise see if some other process holds it. */
2350 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002351 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002352 struct stat statBuf;
2353
2354 if( sem_trywait(pSem)==-1 ){
2355 int tErrno = errno;
2356 if( EAGAIN != tErrno ){
2357 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2358 pFile->lastErrno = tErrno;
2359 } else {
2360 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002361 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002362 }
2363 }else{
2364 /* we could have it if we want it */
2365 sem_post(pSem);
2366 }
2367 }
drh308c2a52010-05-14 11:30:18 +00002368 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002369
2370 *pResOut = reserved;
2371 return rc;
2372}
2373
drh6b9d6dd2008-12-03 19:34:47 +00002374/*
drh308c2a52010-05-14 11:30:18 +00002375** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002376** of the following:
2377**
2378** (1) SHARED_LOCK
2379** (2) RESERVED_LOCK
2380** (3) PENDING_LOCK
2381** (4) EXCLUSIVE_LOCK
2382**
2383** Sometimes when requesting one lock state, additional lock states
2384** are inserted in between. The locking might fail on one of the later
2385** transitions leaving the lock state different from what it started but
2386** still short of its goal. The following chart shows the allowed
2387** transitions and the inserted intermediate states:
2388**
2389** UNLOCKED -> SHARED
2390** SHARED -> RESERVED
2391** SHARED -> (PENDING) -> EXCLUSIVE
2392** RESERVED -> (PENDING) -> EXCLUSIVE
2393** PENDING -> EXCLUSIVE
2394**
2395** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2396** lock states in the sqlite3_file structure, but all locks SHARED or
2397** above are really EXCLUSIVE locks and exclude all other processes from
2398** access the file.
2399**
2400** This routine will only increase a lock. Use the sqlite3OsUnlock()
2401** routine to lower a locking level.
2402*/
drh308c2a52010-05-14 11:30:18 +00002403static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002404 unixFile *pFile = (unixFile*)id;
2405 int fd;
drh8af6c222010-05-14 12:43:01 +00002406 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002407 int rc = SQLITE_OK;
2408
2409 /* if we already have a lock, it is exclusive.
2410 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002411 if (pFile->eFileLock > NO_LOCK) {
2412 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002413 rc = SQLITE_OK;
2414 goto sem_end_lock;
2415 }
2416
2417 /* lock semaphore now but bail out when already locked. */
2418 if( sem_trywait(pSem)==-1 ){
2419 rc = SQLITE_BUSY;
2420 goto sem_end_lock;
2421 }
2422
2423 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002424 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002425
2426 sem_end_lock:
2427 return rc;
2428}
2429
drh6b9d6dd2008-12-03 19:34:47 +00002430/*
drh308c2a52010-05-14 11:30:18 +00002431** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002432** must be either NO_LOCK or SHARED_LOCK.
2433**
2434** If the locking level of the file descriptor is already at or below
2435** the requested locking level, this routine is a no-op.
2436*/
drh308c2a52010-05-14 11:30:18 +00002437static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002438 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002439 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002440
2441 assert( pFile );
2442 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002443 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002444 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002445 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002446
2447 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002448 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002449 return SQLITE_OK;
2450 }
2451
2452 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002453 if (eFileLock==SHARED_LOCK) {
2454 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002455 return SQLITE_OK;
2456 }
2457
2458 /* no, really unlock. */
2459 if ( sem_post(pSem)==-1 ) {
2460 int rc, tErrno = errno;
2461 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2462 if( IS_LOCK_ERROR(rc) ){
2463 pFile->lastErrno = tErrno;
2464 }
2465 return rc;
2466 }
drh308c2a52010-05-14 11:30:18 +00002467 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002468 return SQLITE_OK;
2469}
2470
2471/*
2472 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002473 */
drh734c9862008-11-28 15:37:20 +00002474static int semClose(sqlite3_file *id) {
2475 if( id ){
2476 unixFile *pFile = (unixFile*)id;
2477 semUnlock(id, NO_LOCK);
2478 assert( pFile );
2479 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002480 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002481 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002482 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002483 }
2484 return SQLITE_OK;
2485}
2486
2487#endif /* OS_VXWORKS */
2488/*
2489** Named semaphore locking is only available on VxWorks.
2490**
2491*************** End of the named semaphore lock implementation ****************
2492******************************************************************************/
2493
2494
2495/******************************************************************************
2496*************************** Begin AFP Locking *********************************
2497**
2498** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2499** on Apple Macintosh computers - both OS9 and OSX.
2500**
2501** Third-party implementations of AFP are available. But this code here
2502** only works on OSX.
2503*/
2504
drhd2cb50b2009-01-09 21:41:17 +00002505#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002506/*
2507** The afpLockingContext structure contains all afp lock specific state
2508*/
drhbfe66312006-10-03 17:40:40 +00002509typedef struct afpLockingContext afpLockingContext;
2510struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002511 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002512 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002513};
2514
2515struct ByteRangeLockPB2
2516{
2517 unsigned long long offset; /* offset to first byte to lock */
2518 unsigned long long length; /* nbr of bytes to lock */
2519 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2520 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2521 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2522 int fd; /* file desc to assoc this lock with */
2523};
2524
drhfd131da2007-08-07 17:13:03 +00002525#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002526
drh6b9d6dd2008-12-03 19:34:47 +00002527/*
2528** This is a utility for setting or clearing a bit-range lock on an
2529** AFP filesystem.
2530**
2531** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2532*/
2533static int afpSetLock(
2534 const char *path, /* Name of the file to be locked or unlocked */
2535 unixFile *pFile, /* Open file descriptor on path */
2536 unsigned long long offset, /* First byte to be locked */
2537 unsigned long long length, /* Number of bytes to lock */
2538 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002539){
drh6b9d6dd2008-12-03 19:34:47 +00002540 struct ByteRangeLockPB2 pb;
2541 int err;
drhbfe66312006-10-03 17:40:40 +00002542
2543 pb.unLockFlag = setLockFlag ? 0 : 1;
2544 pb.startEndFlag = 0;
2545 pb.offset = offset;
2546 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002547 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002548
drh308c2a52010-05-14 11:30:18 +00002549 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002550 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002551 offset, length));
drhbfe66312006-10-03 17:40:40 +00002552 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2553 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002554 int rc;
2555 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002556 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2557 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002558#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2559 rc = SQLITE_BUSY;
2560#else
drh734c9862008-11-28 15:37:20 +00002561 rc = sqliteErrorFromPosixError(tErrno,
2562 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002563#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002564 if( IS_LOCK_ERROR(rc) ){
2565 pFile->lastErrno = tErrno;
2566 }
2567 return rc;
drhbfe66312006-10-03 17:40:40 +00002568 } else {
aswift5b1a2562008-08-22 00:22:35 +00002569 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002570 }
2571}
2572
drh6b9d6dd2008-12-03 19:34:47 +00002573/*
2574** This routine checks if there is a RESERVED lock held on the specified
2575** file by this or any other process. If such a lock is held, set *pResOut
2576** to a non-zero value otherwise *pResOut is set to zero. The return value
2577** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2578*/
danielk1977e339d652008-06-28 11:23:00 +00002579static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002580 int rc = SQLITE_OK;
2581 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002582 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002583 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002584
aswift5b1a2562008-08-22 00:22:35 +00002585 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2586
2587 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002588 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002589 if( context->reserved ){
2590 *pResOut = 1;
2591 return SQLITE_OK;
2592 }
drh8af6c222010-05-14 12:43:01 +00002593 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002594
2595 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002596 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002597 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002598 }
2599
2600 /* Otherwise see if some other process holds it.
2601 */
aswift5b1a2562008-08-22 00:22:35 +00002602 if( !reserved ){
2603 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002604 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002605 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002606 /* if we succeeded in taking the reserved lock, unlock it to restore
2607 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002608 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002609 } else {
2610 /* if we failed to get the lock then someone else must have it */
2611 reserved = 1;
2612 }
2613 if( IS_LOCK_ERROR(lrc) ){
2614 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002615 }
2616 }
drhbfe66312006-10-03 17:40:40 +00002617
drh7ed97b92010-01-20 13:07:21 +00002618 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002619 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002620
2621 *pResOut = reserved;
2622 return rc;
drhbfe66312006-10-03 17:40:40 +00002623}
2624
drh6b9d6dd2008-12-03 19:34:47 +00002625/*
drh308c2a52010-05-14 11:30:18 +00002626** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002627** of the following:
2628**
2629** (1) SHARED_LOCK
2630** (2) RESERVED_LOCK
2631** (3) PENDING_LOCK
2632** (4) EXCLUSIVE_LOCK
2633**
2634** Sometimes when requesting one lock state, additional lock states
2635** are inserted in between. The locking might fail on one of the later
2636** transitions leaving the lock state different from what it started but
2637** still short of its goal. The following chart shows the allowed
2638** transitions and the inserted intermediate states:
2639**
2640** UNLOCKED -> SHARED
2641** SHARED -> RESERVED
2642** SHARED -> (PENDING) -> EXCLUSIVE
2643** RESERVED -> (PENDING) -> EXCLUSIVE
2644** PENDING -> EXCLUSIVE
2645**
2646** This routine will only increase a lock. Use the sqlite3OsUnlock()
2647** routine to lower a locking level.
2648*/
drh308c2a52010-05-14 11:30:18 +00002649static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002650 int rc = SQLITE_OK;
2651 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002652 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002653 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002654
2655 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002656 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2657 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002658 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002659
drhbfe66312006-10-03 17:40:40 +00002660 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002661 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002662 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002663 */
drh308c2a52010-05-14 11:30:18 +00002664 if( pFile->eFileLock>=eFileLock ){
2665 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2666 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002667 return SQLITE_OK;
2668 }
2669
2670 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002671 ** (1) We never move from unlocked to anything higher than shared lock.
2672 ** (2) SQLite never explicitly requests a pendig lock.
2673 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002674 */
drh308c2a52010-05-14 11:30:18 +00002675 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2676 assert( eFileLock!=PENDING_LOCK );
2677 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002678
drh8af6c222010-05-14 12:43:01 +00002679 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002680 */
drh6c7d5c52008-11-21 20:32:33 +00002681 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002682 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002683
2684 /* If some thread using this PID has a lock via a different unixFile*
2685 ** handle that precludes the requested lock, return BUSY.
2686 */
drh8af6c222010-05-14 12:43:01 +00002687 if( (pFile->eFileLock!=pInode->eFileLock &&
2688 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002689 ){
2690 rc = SQLITE_BUSY;
2691 goto afp_end_lock;
2692 }
2693
2694 /* If a SHARED lock is requested, and some thread using this PID already
2695 ** has a SHARED or RESERVED lock, then increment reference counts and
2696 ** return SQLITE_OK.
2697 */
drh308c2a52010-05-14 11:30:18 +00002698 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002699 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002700 assert( eFileLock==SHARED_LOCK );
2701 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002702 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002703 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002704 pInode->nShared++;
2705 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002706 goto afp_end_lock;
2707 }
drhbfe66312006-10-03 17:40:40 +00002708
2709 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002710 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2711 ** be released.
2712 */
drh308c2a52010-05-14 11:30:18 +00002713 if( eFileLock==SHARED_LOCK
2714 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002715 ){
2716 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002717 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002718 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002719 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002720 goto afp_end_lock;
2721 }
2722 }
2723
2724 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002725 ** operating system calls for the specified lock.
2726 */
drh308c2a52010-05-14 11:30:18 +00002727 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002728 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002729 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002730
drh8af6c222010-05-14 12:43:01 +00002731 assert( pInode->nShared==0 );
2732 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002733
2734 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002735 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002736 /* note that the quality of the randomness doesn't matter that much */
2737 lk = random();
drh8af6c222010-05-14 12:43:01 +00002738 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002739 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002740 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002741 if( IS_LOCK_ERROR(lrc1) ){
2742 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002743 }
aswift5b1a2562008-08-22 00:22:35 +00002744 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002745 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002746
aswift5b1a2562008-08-22 00:22:35 +00002747 if( IS_LOCK_ERROR(lrc1) ) {
2748 pFile->lastErrno = lrc1Errno;
2749 rc = lrc1;
2750 goto afp_end_lock;
2751 } else if( IS_LOCK_ERROR(lrc2) ){
2752 rc = lrc2;
2753 goto afp_end_lock;
2754 } else if( lrc1 != SQLITE_OK ) {
2755 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002756 } else {
drh308c2a52010-05-14 11:30:18 +00002757 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002758 pInode->nLock++;
2759 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002760 }
drh8af6c222010-05-14 12:43:01 +00002761 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002762 /* We are trying for an exclusive lock but another thread in this
2763 ** same process is still holding a shared lock. */
2764 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002765 }else{
2766 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2767 ** assumed that there is a SHARED or greater lock on the file
2768 ** already.
2769 */
2770 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002771 assert( 0!=pFile->eFileLock );
2772 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002773 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002774 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002775 if( !failed ){
2776 context->reserved = 1;
2777 }
drhbfe66312006-10-03 17:40:40 +00002778 }
drh308c2a52010-05-14 11:30:18 +00002779 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002780 /* Acquire an EXCLUSIVE lock */
2781
2782 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002783 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002784 */
drh6b9d6dd2008-12-03 19:34:47 +00002785 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002786 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002787 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002788 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002789 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002790 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002791 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002792 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002793 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2794 ** a critical I/O error
2795 */
2796 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2797 SQLITE_IOERR_LOCK;
2798 goto afp_end_lock;
2799 }
2800 }else{
aswift5b1a2562008-08-22 00:22:35 +00002801 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002802 }
2803 }
aswift5b1a2562008-08-22 00:22:35 +00002804 if( failed ){
2805 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002806 }
2807 }
2808
2809 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002810 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002811 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002812 }else if( eFileLock==EXCLUSIVE_LOCK ){
2813 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002814 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002815 }
2816
2817afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002818 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002819 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2820 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002821 return rc;
2822}
2823
2824/*
drh308c2a52010-05-14 11:30:18 +00002825** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002826** must be either NO_LOCK or SHARED_LOCK.
2827**
2828** If the locking level of the file descriptor is already at or below
2829** the requested locking level, this routine is a no-op.
2830*/
drh308c2a52010-05-14 11:30:18 +00002831static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002832 int rc = SQLITE_OK;
2833 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002834 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002835 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2836 int skipShared = 0;
2837#ifdef SQLITE_TEST
2838 int h = pFile->h;
2839#endif
drhbfe66312006-10-03 17:40:40 +00002840
2841 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002842 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002843 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002844 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002845
drh308c2a52010-05-14 11:30:18 +00002846 assert( eFileLock<=SHARED_LOCK );
2847 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002848 return SQLITE_OK;
2849 }
drh6c7d5c52008-11-21 20:32:33 +00002850 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002851 pInode = pFile->pInode;
2852 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002853 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002854 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002855 SimulateIOErrorBenign(1);
2856 SimulateIOError( h=(-1) )
2857 SimulateIOErrorBenign(0);
2858
drhd3d8c042012-05-29 17:02:40 +00002859#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002860 /* When reducing a lock such that other processes can start
2861 ** reading the database file again, make sure that the
2862 ** transaction counter was updated if any part of the database
2863 ** file changed. If the transaction counter is not updated,
2864 ** other connections to the same file might not realize that
2865 ** the file has changed and hence might not know to flush their
2866 ** cache. The use of a stale cache can lead to database corruption.
2867 */
2868 assert( pFile->inNormalWrite==0
2869 || pFile->dbUpdate==0
2870 || pFile->transCntrChng==1 );
2871 pFile->inNormalWrite = 0;
2872#endif
aswiftaebf4132008-11-21 00:10:35 +00002873
drh308c2a52010-05-14 11:30:18 +00002874 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002875 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002876 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002877 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002878 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002879 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2880 } else {
2881 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002882 }
2883 }
drh308c2a52010-05-14 11:30:18 +00002884 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002885 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002886 }
drh308c2a52010-05-14 11:30:18 +00002887 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002888 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2889 if( !rc ){
2890 context->reserved = 0;
2891 }
aswiftaebf4132008-11-21 00:10:35 +00002892 }
drh8af6c222010-05-14 12:43:01 +00002893 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2894 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002895 }
aswiftaebf4132008-11-21 00:10:35 +00002896 }
drh308c2a52010-05-14 11:30:18 +00002897 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002898
drh7ed97b92010-01-20 13:07:21 +00002899 /* Decrement the shared lock counter. Release the lock using an
2900 ** OS call only when all threads in this same process have released
2901 ** the lock.
2902 */
drh8af6c222010-05-14 12:43:01 +00002903 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2904 pInode->nShared--;
2905 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002906 SimulateIOErrorBenign(1);
2907 SimulateIOError( h=(-1) )
2908 SimulateIOErrorBenign(0);
2909 if( !skipShared ){
2910 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2911 }
2912 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002913 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002914 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002915 }
2916 }
2917 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002918 pInode->nLock--;
2919 assert( pInode->nLock>=0 );
2920 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002921 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002922 }
2923 }
drhbfe66312006-10-03 17:40:40 +00002924 }
drh7ed97b92010-01-20 13:07:21 +00002925
drh6c7d5c52008-11-21 20:32:33 +00002926 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002927 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002928 return rc;
2929}
2930
2931/*
drh339eb0b2008-03-07 15:34:11 +00002932** Close a file & cleanup AFP specific locking context
2933*/
danielk1977e339d652008-06-28 11:23:00 +00002934static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002935 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002936 if( id ){
2937 unixFile *pFile = (unixFile*)id;
2938 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002939 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002940 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002941 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002942 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002943 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002944 ** the last lock is cleared.
2945 */
dan08da86a2009-08-21 17:18:03 +00002946 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002947 }
danb0ac3e32010-06-16 10:55:42 +00002948 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002949 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002950 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002951 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002952 }
drh7ed97b92010-01-20 13:07:21 +00002953 return rc;
drhbfe66312006-10-03 17:40:40 +00002954}
2955
drhd2cb50b2009-01-09 21:41:17 +00002956#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002957/*
2958** The code above is the AFP lock implementation. The code is specific
2959** to MacOSX and does not work on other unix platforms. No alternative
2960** is available. If you don't compile for a mac, then the "unix-afp"
2961** VFS is not available.
2962**
2963********************* End of the AFP lock implementation **********************
2964******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002965
drh7ed97b92010-01-20 13:07:21 +00002966/******************************************************************************
2967*************************** Begin NFS Locking ********************************/
2968
2969#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2970/*
drh308c2a52010-05-14 11:30:18 +00002971 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002972 ** must be either NO_LOCK or SHARED_LOCK.
2973 **
2974 ** If the locking level of the file descriptor is already at or below
2975 ** the requested locking level, this routine is a no-op.
2976 */
drh308c2a52010-05-14 11:30:18 +00002977static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002978 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002979}
2980
2981#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2982/*
2983** The code above is the NFS lock implementation. The code is specific
2984** to MacOSX and does not work on other unix platforms. No alternative
2985** is available.
2986**
2987********************* End of the NFS lock implementation **********************
2988******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002989
2990/******************************************************************************
2991**************** Non-locking sqlite3_file methods *****************************
2992**
2993** The next division contains implementations for all methods of the
2994** sqlite3_file object other than the locking methods. The locking
2995** methods were defined in divisions above (one locking method per
2996** division). Those methods that are common to all locking modes
2997** are gather together into this division.
2998*/
drhbfe66312006-10-03 17:40:40 +00002999
3000/*
drh734c9862008-11-28 15:37:20 +00003001** Seek to the offset passed as the second argument, then read cnt
3002** bytes into pBuf. Return the number of bytes actually read.
3003**
3004** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3005** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3006** one system to another. Since SQLite does not define USE_PREAD
3007** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3008** See tickets #2741 and #2681.
3009**
3010** To avoid stomping the errno value on a failed read the lastErrno value
3011** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003012*/
drh734c9862008-11-28 15:37:20 +00003013static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3014 int got;
drh58024642011-11-07 18:16:00 +00003015 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003016#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003017 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003018#endif
drh734c9862008-11-28 15:37:20 +00003019 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003020 assert( cnt==(cnt&0x1ffff) );
3021 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003022 do{
drh734c9862008-11-28 15:37:20 +00003023#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003024 got = osPread(id->h, pBuf, cnt, offset);
3025 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003026#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003027 got = osPread64(id->h, pBuf, cnt, offset);
3028 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003029#else
drh58024642011-11-07 18:16:00 +00003030 newOffset = lseek(id->h, offset, SEEK_SET);
3031 SimulateIOError( newOffset-- );
3032 if( newOffset!=offset ){
3033 if( newOffset == -1 ){
3034 ((unixFile*)id)->lastErrno = errno;
3035 }else{
drhf2f105d2012-08-20 15:53:54 +00003036 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003037 }
3038 return -1;
drh734c9862008-11-28 15:37:20 +00003039 }
drh58024642011-11-07 18:16:00 +00003040 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003041#endif
drh58024642011-11-07 18:16:00 +00003042 if( got==cnt ) break;
3043 if( got<0 ){
3044 if( errno==EINTR ){ got = 1; continue; }
3045 prior = 0;
3046 ((unixFile*)id)->lastErrno = errno;
3047 break;
3048 }else if( got>0 ){
3049 cnt -= got;
3050 offset += got;
3051 prior += got;
3052 pBuf = (void*)(got + (char*)pBuf);
3053 }
3054 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003055 TIMER_END;
drh58024642011-11-07 18:16:00 +00003056 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3057 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3058 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003059}
3060
3061/*
drh734c9862008-11-28 15:37:20 +00003062** Read data from a file into a buffer. Return SQLITE_OK if all
3063** bytes were read successfully and SQLITE_IOERR if anything goes
3064** wrong.
drh339eb0b2008-03-07 15:34:11 +00003065*/
drh734c9862008-11-28 15:37:20 +00003066static int unixRead(
3067 sqlite3_file *id,
3068 void *pBuf,
3069 int amt,
3070 sqlite3_int64 offset
3071){
dan08da86a2009-08-21 17:18:03 +00003072 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003073 int got;
3074 assert( id );
drh08c6d442009-02-09 17:34:07 +00003075
dan08da86a2009-08-21 17:18:03 +00003076 /* If this is a database file (not a journal, master-journal or temp
3077 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003078#if 0
dane946c392009-08-22 11:39:46 +00003079 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003080 || offset>=PENDING_BYTE+512
3081 || offset+amt<=PENDING_BYTE
3082 );
dan7c246102010-04-12 19:00:29 +00003083#endif
drh08c6d442009-02-09 17:34:07 +00003084
dan08da86a2009-08-21 17:18:03 +00003085 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003086 if( got==amt ){
3087 return SQLITE_OK;
3088 }else if( got<0 ){
3089 /* lastErrno set by seekAndRead */
3090 return SQLITE_IOERR_READ;
3091 }else{
dan08da86a2009-08-21 17:18:03 +00003092 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003093 /* Unread parts of the buffer must be zero-filled */
3094 memset(&((char*)pBuf)[got], 0, amt-got);
3095 return SQLITE_IOERR_SHORT_READ;
3096 }
3097}
3098
3099/*
3100** Seek to the offset in id->offset then read cnt bytes into pBuf.
3101** Return the number of bytes actually read. Update the offset.
3102**
3103** To avoid stomping the errno value on a failed write the lastErrno value
3104** is set before returning.
3105*/
3106static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3107 int got;
drh7ed97b92010-01-20 13:07:21 +00003108#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003109 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003110#endif
drhc1fd2cf2012-10-01 12:16:26 +00003111 assert( cnt==(cnt&0x1ffff) );
3112 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003113 TIMER_START;
3114#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003115 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003116#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003117 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003118#else
drhbd1e50c2011-08-19 14:54:12 +00003119 do{
3120 newOffset = lseek(id->h, offset, SEEK_SET);
3121 SimulateIOError( newOffset-- );
3122 if( newOffset!=offset ){
3123 if( newOffset == -1 ){
3124 ((unixFile*)id)->lastErrno = errno;
3125 }else{
drhf2f105d2012-08-20 15:53:54 +00003126 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003127 }
3128 return -1;
drh734c9862008-11-28 15:37:20 +00003129 }
drhbd1e50c2011-08-19 14:54:12 +00003130 got = osWrite(id->h, pBuf, cnt);
3131 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003132#endif
3133 TIMER_END;
3134 if( got<0 ){
3135 ((unixFile*)id)->lastErrno = errno;
3136 }
3137
drh308c2a52010-05-14 11:30:18 +00003138 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003139 return got;
3140}
3141
3142
3143/*
3144** Write data from a buffer into a file. Return SQLITE_OK on success
3145** or some other error code on failure.
3146*/
3147static int unixWrite(
3148 sqlite3_file *id,
3149 const void *pBuf,
3150 int amt,
3151 sqlite3_int64 offset
3152){
dan08da86a2009-08-21 17:18:03 +00003153 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003154 int wrote = 0;
3155 assert( id );
3156 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003157
dan08da86a2009-08-21 17:18:03 +00003158 /* If this is a database file (not a journal, master-journal or temp
3159 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003160#if 0
dane946c392009-08-22 11:39:46 +00003161 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003162 || offset>=PENDING_BYTE+512
3163 || offset+amt<=PENDING_BYTE
3164 );
dan7c246102010-04-12 19:00:29 +00003165#endif
drh08c6d442009-02-09 17:34:07 +00003166
drhd3d8c042012-05-29 17:02:40 +00003167#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003168 /* If we are doing a normal write to a database file (as opposed to
3169 ** doing a hot-journal rollback or a write to some file other than a
3170 ** normal database file) then record the fact that the database
3171 ** has changed. If the transaction counter is modified, record that
3172 ** fact too.
3173 */
dan08da86a2009-08-21 17:18:03 +00003174 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003175 pFile->dbUpdate = 1; /* The database has been modified */
3176 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003177 int rc;
drh8f941bc2009-01-14 23:03:40 +00003178 char oldCntr[4];
3179 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003180 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003181 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003182 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003183 pFile->transCntrChng = 1; /* The transaction counter has changed */
3184 }
3185 }
3186 }
3187#endif
3188
dan08da86a2009-08-21 17:18:03 +00003189 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003190 amt -= wrote;
3191 offset += wrote;
3192 pBuf = &((char*)pBuf)[wrote];
3193 }
3194 SimulateIOError(( wrote=(-1), amt=1 ));
3195 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003196
drh734c9862008-11-28 15:37:20 +00003197 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003198 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003199 /* lastErrno set by seekAndWrite */
3200 return SQLITE_IOERR_WRITE;
3201 }else{
dan08da86a2009-08-21 17:18:03 +00003202 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003203 return SQLITE_FULL;
3204 }
3205 }
dan6e09d692010-07-27 18:34:15 +00003206
drh734c9862008-11-28 15:37:20 +00003207 return SQLITE_OK;
3208}
3209
3210#ifdef SQLITE_TEST
3211/*
3212** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003213** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003214*/
3215int sqlite3_sync_count = 0;
3216int sqlite3_fullsync_count = 0;
3217#endif
3218
3219/*
drh89240432009-03-25 01:06:01 +00003220** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003221** Others do no. To be safe, we will stick with the (slightly slower)
3222** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003223** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003224*/
drh20f8e132011-08-31 21:01:55 +00003225#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003226# define fdatasync fsync
3227#endif
3228
3229/*
3230** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3231** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3232** only available on Mac OS X. But that could change.
3233*/
3234#ifdef F_FULLFSYNC
3235# define HAVE_FULLFSYNC 1
3236#else
3237# define HAVE_FULLFSYNC 0
3238#endif
3239
3240
3241/*
3242** The fsync() system call does not work as advertised on many
3243** unix systems. The following procedure is an attempt to make
3244** it work better.
3245**
3246** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3247** for testing when we want to run through the test suite quickly.
3248** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3249** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3250** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003251**
3252** SQLite sets the dataOnly flag if the size of the file is unchanged.
3253** The idea behind dataOnly is that it should only write the file content
3254** to disk, not the inode. We only set dataOnly if the file size is
3255** unchanged since the file size is part of the inode. However,
3256** Ted Ts'o tells us that fdatasync() will also write the inode if the
3257** file size has changed. The only real difference between fdatasync()
3258** and fsync(), Ted tells us, is that fdatasync() will not flush the
3259** inode if the mtime or owner or other inode attributes have changed.
3260** We only care about the file size, not the other file attributes, so
3261** as far as SQLite is concerned, an fdatasync() is always adequate.
3262** So, we always use fdatasync() if it is available, regardless of
3263** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003264*/
3265static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003266 int rc;
drh734c9862008-11-28 15:37:20 +00003267
3268 /* The following "ifdef/elif/else/" block has the same structure as
3269 ** the one below. It is replicated here solely to avoid cluttering
3270 ** up the real code with the UNUSED_PARAMETER() macros.
3271 */
3272#ifdef SQLITE_NO_SYNC
3273 UNUSED_PARAMETER(fd);
3274 UNUSED_PARAMETER(fullSync);
3275 UNUSED_PARAMETER(dataOnly);
3276#elif HAVE_FULLFSYNC
3277 UNUSED_PARAMETER(dataOnly);
3278#else
3279 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003280 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003281#endif
3282
3283 /* Record the number of times that we do a normal fsync() and
3284 ** FULLSYNC. This is used during testing to verify that this procedure
3285 ** gets called with the correct arguments.
3286 */
3287#ifdef SQLITE_TEST
3288 if( fullSync ) sqlite3_fullsync_count++;
3289 sqlite3_sync_count++;
3290#endif
3291
3292 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3293 ** no-op
3294 */
3295#ifdef SQLITE_NO_SYNC
3296 rc = SQLITE_OK;
3297#elif HAVE_FULLFSYNC
3298 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003299 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003300 }else{
3301 rc = 1;
3302 }
3303 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003304 ** It shouldn't be possible for fullfsync to fail on the local
3305 ** file system (on OSX), so failure indicates that FULLFSYNC
3306 ** isn't supported for this file system. So, attempt an fsync
3307 ** and (for now) ignore the overhead of a superfluous fcntl call.
3308 ** It'd be better to detect fullfsync support once and avoid
3309 ** the fcntl call every time sync is called.
3310 */
drh734c9862008-11-28 15:37:20 +00003311 if( rc ) rc = fsync(fd);
3312
drh7ed97b92010-01-20 13:07:21 +00003313#elif defined(__APPLE__)
3314 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3315 ** so currently we default to the macro that redefines fdatasync to fsync
3316 */
3317 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003318#else
drh0b647ff2009-03-21 14:41:04 +00003319 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003320#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003321 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003322 rc = fsync(fd);
3323 }
drh0b647ff2009-03-21 14:41:04 +00003324#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003325#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3326
3327 if( OS_VXWORKS && rc!= -1 ){
3328 rc = 0;
3329 }
chw97185482008-11-17 08:05:31 +00003330 return rc;
drhbfe66312006-10-03 17:40:40 +00003331}
3332
drh734c9862008-11-28 15:37:20 +00003333/*
drh0059eae2011-08-08 23:48:40 +00003334** Open a file descriptor to the directory containing file zFilename.
3335** If successful, *pFd is set to the opened file descriptor and
3336** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3337** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3338** value.
3339**
drh90315a22011-08-10 01:52:12 +00003340** The directory file descriptor is used for only one thing - to
3341** fsync() a directory to make sure file creation and deletion events
3342** are flushed to disk. Such fsyncs are not needed on newer
3343** journaling filesystems, but are required on older filesystems.
3344**
3345** This routine can be overridden using the xSetSysCall interface.
3346** The ability to override this routine was added in support of the
3347** chromium sandbox. Opening a directory is a security risk (we are
3348** told) so making it overrideable allows the chromium sandbox to
3349** replace this routine with a harmless no-op. To make this routine
3350** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3351** *pFd set to a negative number.
3352**
drh0059eae2011-08-08 23:48:40 +00003353** If SQLITE_OK is returned, the caller is responsible for closing
3354** the file descriptor *pFd using close().
3355*/
3356static int openDirectory(const char *zFilename, int *pFd){
3357 int ii;
3358 int fd = -1;
3359 char zDirname[MAX_PATHNAME+1];
3360
3361 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3362 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3363 if( ii>0 ){
3364 zDirname[ii] = '\0';
3365 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3366 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003367 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3368 }
3369 }
3370 *pFd = fd;
3371 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3372}
3373
3374/*
drh734c9862008-11-28 15:37:20 +00003375** Make sure all writes to a particular file are committed to disk.
3376**
3377** If dataOnly==0 then both the file itself and its metadata (file
3378** size, access time, etc) are synced. If dataOnly!=0 then only the
3379** file data is synced.
3380**
3381** Under Unix, also make sure that the directory entry for the file
3382** has been created by fsync-ing the directory that contains the file.
3383** If we do not do this and we encounter a power failure, the directory
3384** entry for the journal might not exist after we reboot. The next
3385** SQLite to access the file will not know that the journal exists (because
3386** the directory entry for the journal was never created) and the transaction
3387** will not roll back - possibly leading to database corruption.
3388*/
3389static int unixSync(sqlite3_file *id, int flags){
3390 int rc;
3391 unixFile *pFile = (unixFile*)id;
3392
3393 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3394 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3395
3396 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3397 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3398 || (flags&0x0F)==SQLITE_SYNC_FULL
3399 );
3400
3401 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3402 ** line is to test that doing so does not cause any problems.
3403 */
3404 SimulateDiskfullError( return SQLITE_FULL );
3405
3406 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003407 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003408 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3409 SimulateIOError( rc=1 );
3410 if( rc ){
3411 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003412 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003413 }
drh0059eae2011-08-08 23:48:40 +00003414
3415 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003416 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3417 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003418 */
3419 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3420 int dirfd;
3421 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003422 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003423 rc = osOpenDirectory(pFile->zPath, &dirfd);
3424 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003425 full_fsync(dirfd, 0, 0);
3426 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003427 }else if( rc==SQLITE_CANTOPEN ){
3428 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003429 }
drh0059eae2011-08-08 23:48:40 +00003430 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003431 }
3432 return rc;
3433}
3434
3435/*
3436** Truncate an open file to a specified size
3437*/
3438static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003439 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003440 int rc;
dan6e09d692010-07-27 18:34:15 +00003441 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003442 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003443
3444 /* If the user has configured a chunk-size for this file, truncate the
3445 ** file so that it consists of an integer number of chunks (i.e. the
3446 ** actual file size after the operation may be larger than the requested
3447 ** size).
3448 */
drhb8af4b72012-04-05 20:04:39 +00003449 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003450 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3451 }
3452
drhff812312011-02-23 13:33:46 +00003453 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003454 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003455 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003456 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003457 }else{
drhd3d8c042012-05-29 17:02:40 +00003458#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003459 /* If we are doing a normal write to a database file (as opposed to
3460 ** doing a hot-journal rollback or a write to some file other than a
3461 ** normal database file) and we truncate the file to zero length,
3462 ** that effectively updates the change counter. This might happen
3463 ** when restoring a database using the backup API from a zero-length
3464 ** source.
3465 */
dan6e09d692010-07-27 18:34:15 +00003466 if( pFile->inNormalWrite && nByte==0 ){
3467 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003468 }
3469#endif
3470
drh734c9862008-11-28 15:37:20 +00003471 return SQLITE_OK;
3472 }
3473}
3474
3475/*
3476** Determine the current size of a file in bytes
3477*/
3478static int unixFileSize(sqlite3_file *id, i64 *pSize){
3479 int rc;
3480 struct stat buf;
3481 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003482 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003483 SimulateIOError( rc=1 );
3484 if( rc!=0 ){
3485 ((unixFile*)id)->lastErrno = errno;
3486 return SQLITE_IOERR_FSTAT;
3487 }
3488 *pSize = buf.st_size;
3489
drh8af6c222010-05-14 12:43:01 +00003490 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003491 ** writes a single byte into that file in order to work around a bug
3492 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3493 ** layers, we need to report this file size as zero even though it is
3494 ** really 1. Ticket #3260.
3495 */
3496 if( *pSize==1 ) *pSize = 0;
3497
3498
3499 return SQLITE_OK;
3500}
3501
drhd2cb50b2009-01-09 21:41:17 +00003502#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003503/*
3504** Handler for proxy-locking file-control verbs. Defined below in the
3505** proxying locking division.
3506*/
3507static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003508#endif
drh715ff302008-12-03 22:32:44 +00003509
dan502019c2010-07-28 14:26:17 +00003510/*
3511** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003512** file-control operation. Enlarge the database to nBytes in size
3513** (rounded up to the next chunk-size). If the database is already
3514** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003515*/
3516static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003517 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003518 i64 nSize; /* Required file size */
3519 struct stat buf; /* Used to hold return values of fstat() */
3520
drh99ab3b12011-03-02 15:09:07 +00003521 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003522
3523 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3524 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003525
dan502019c2010-07-28 14:26:17 +00003526#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003527 /* The code below is handling the return value of osFallocate()
3528 ** correctly. posix_fallocate() is defined to "returns zero on success,
3529 ** or an error number on failure". See the manpage for details. */
3530 int err;
drhff812312011-02-23 13:33:46 +00003531 do{
dan661d71a2011-03-30 19:08:03 +00003532 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3533 }while( err==EINTR );
3534 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003535#else
3536 /* If the OS does not have posix_fallocate(), fake it. First use
3537 ** ftruncate() to set the file size, then write a single byte to
3538 ** the last byte in each block within the extended region. This
3539 ** is the same technique used by glibc to implement posix_fallocate()
3540 ** on systems that do not have a real fallocate() system call.
3541 */
3542 int nBlk = buf.st_blksize; /* File-system block size */
3543 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003544
drhff812312011-02-23 13:33:46 +00003545 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003546 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003547 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003548 }
3549 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003550 while( iWrite<nSize ){
3551 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3552 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003553 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003554 }
dan502019c2010-07-28 14:26:17 +00003555#endif
3556 }
3557 }
3558
3559 return SQLITE_OK;
3560}
danielk1977ad94b582007-08-20 06:44:22 +00003561
danielk1977e3026632004-06-22 11:29:02 +00003562/*
drhf12b3f62011-12-21 14:42:29 +00003563** If *pArg is inititially negative then this is a query. Set *pArg to
3564** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3565**
3566** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3567*/
3568static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3569 if( *pArg<0 ){
3570 *pArg = (pFile->ctrlFlags & mask)!=0;
3571 }else if( (*pArg)==0 ){
3572 pFile->ctrlFlags &= ~mask;
3573 }else{
3574 pFile->ctrlFlags |= mask;
3575 }
3576}
3577
drh696b33e2012-12-06 19:01:42 +00003578/* Forward declaration */
3579static int unixGetTempname(int nBuf, char *zBuf);
3580
drhf12b3f62011-12-21 14:42:29 +00003581/*
drh9e33c2c2007-08-31 18:34:59 +00003582** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003583*/
drhcc6bb3e2007-08-31 16:11:35 +00003584static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003585 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003586 switch( op ){
3587 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003588 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003589 return SQLITE_OK;
3590 }
drh7708e972008-11-29 00:56:52 +00003591 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003592 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003593 return SQLITE_OK;
3594 }
dan6e09d692010-07-27 18:34:15 +00003595 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003596 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003597 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003598 }
drh9ff27ec2010-05-19 19:26:05 +00003599 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003600 int rc;
3601 SimulateIOErrorBenign(1);
3602 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3603 SimulateIOErrorBenign(0);
3604 return rc;
drhf0b190d2011-07-26 16:03:07 +00003605 }
3606 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003607 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3608 return SQLITE_OK;
3609 }
drhcb15f352011-12-23 01:04:17 +00003610 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3611 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003612 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003613 }
drhde60fc22011-12-14 17:53:36 +00003614 case SQLITE_FCNTL_VFSNAME: {
3615 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3616 return SQLITE_OK;
3617 }
drh696b33e2012-12-06 19:01:42 +00003618 case SQLITE_FCNTL_TEMPFILENAME: {
3619 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3620 if( zTFile ){
3621 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3622 *(char**)pArg = zTFile;
3623 }
3624 return SQLITE_OK;
3625 }
danb2d3de32013-03-14 18:34:37 +00003626 case SQLITE_FCNTL_GETFD: {
3627 *(int*)pArg = pFile->h;
3628 return SQLITE_OK;
3629 }
drhd3d8c042012-05-29 17:02:40 +00003630#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003631 /* The pager calls this method to signal that it has done
3632 ** a rollback and that the database is therefore unchanged and
3633 ** it hence it is OK for the transaction change counter to be
3634 ** unchanged.
3635 */
3636 case SQLITE_FCNTL_DB_UNCHANGED: {
3637 ((unixFile*)id)->dbUpdate = 0;
3638 return SQLITE_OK;
3639 }
3640#endif
drhd2cb50b2009-01-09 21:41:17 +00003641#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003642 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003643 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003644 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003645 }
drhd2cb50b2009-01-09 21:41:17 +00003646#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003647 }
drh0b52b7d2011-01-26 19:46:22 +00003648 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003649}
3650
3651/*
danielk1977a3d4c882007-03-23 10:08:38 +00003652** Return the sector size in bytes of the underlying block device for
3653** the specified file. This is almost always 512 bytes, but may be
3654** larger for some devices.
3655**
3656** SQLite code assumes this function cannot fail. It also assumes that
3657** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003658** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003659** same for both.
3660*/
drh537dddf2012-10-26 13:46:24 +00003661#ifndef __QNXNTO__
3662static int unixSectorSize(sqlite3_file *NotUsed){
3663 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003664 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003665}
drh537dddf2012-10-26 13:46:24 +00003666#endif
3667
3668/*
3669** The following version of unixSectorSize() is optimized for QNX.
3670*/
3671#ifdef __QNXNTO__
3672#include <sys/dcmd_blk.h>
3673#include <sys/statvfs.h>
3674static int unixSectorSize(sqlite3_file *id){
3675 unixFile *pFile = (unixFile*)id;
3676 if( pFile->sectorSize == 0 ){
3677 struct statvfs fsInfo;
3678
3679 /* Set defaults for non-supported filesystems */
3680 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3681 pFile->deviceCharacteristics = 0;
3682 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3683 return pFile->sectorSize;
3684 }
3685
3686 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3687 pFile->sectorSize = fsInfo.f_bsize;
3688 pFile->deviceCharacteristics =
3689 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3690 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3691 ** the write succeeds */
3692 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3693 ** so it is ordered */
3694 0;
3695 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3696 pFile->sectorSize = fsInfo.f_bsize;
3697 pFile->deviceCharacteristics =
3698 /* etfs cluster size writes are atomic */
3699 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3700 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3701 ** the write succeeds */
3702 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3703 ** so it is ordered */
3704 0;
3705 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3706 pFile->sectorSize = fsInfo.f_bsize;
3707 pFile->deviceCharacteristics =
3708 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3709 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3710 ** the write succeeds */
3711 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3712 ** so it is ordered */
3713 0;
3714 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3715 pFile->sectorSize = fsInfo.f_bsize;
3716 pFile->deviceCharacteristics =
3717 /* full bitset of atomics from max sector size and smaller */
3718 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3719 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3720 ** so it is ordered */
3721 0;
3722 }else if( strstr(fsInfo.f_basetype, "dos") ){
3723 pFile->sectorSize = fsInfo.f_bsize;
3724 pFile->deviceCharacteristics =
3725 /* full bitset of atomics from max sector size and smaller */
3726 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3727 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3728 ** so it is ordered */
3729 0;
3730 }else{
3731 pFile->deviceCharacteristics =
3732 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3733 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3734 ** the write succeeds */
3735 0;
3736 }
3737 }
3738 /* Last chance verification. If the sector size isn't a multiple of 512
3739 ** then it isn't valid.*/
3740 if( pFile->sectorSize % 512 != 0 ){
3741 pFile->deviceCharacteristics = 0;
3742 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3743 }
3744 return pFile->sectorSize;
3745}
3746#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003747
danielk197790949c22007-08-17 16:50:38 +00003748/*
drhf12b3f62011-12-21 14:42:29 +00003749** Return the device characteristics for the file.
3750**
drhcb15f352011-12-23 01:04:17 +00003751** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3752** However, that choice is contraversial since technically the underlying
3753** file system does not always provide powersafe overwrites. (In other
3754** words, after a power-loss event, parts of the file that were never
3755** written might end up being altered.) However, non-PSOW behavior is very,
3756** very rare. And asserting PSOW makes a large reduction in the amount
3757** of required I/O for journaling, since a lot of padding is eliminated.
3758** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3759** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003760*/
drhf12b3f62011-12-21 14:42:29 +00003761static int unixDeviceCharacteristics(sqlite3_file *id){
3762 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003763 int rc = 0;
3764#ifdef __QNXNTO__
3765 if( p->sectorSize==0 ) unixSectorSize(id);
3766 rc = p->deviceCharacteristics;
3767#endif
drhcb15f352011-12-23 01:04:17 +00003768 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003769 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003770 }
drh537dddf2012-10-26 13:46:24 +00003771 return rc;
danielk197762079062007-08-15 17:08:46 +00003772}
3773
drhd9e5c4f2010-05-12 18:01:39 +00003774#ifndef SQLITE_OMIT_WAL
3775
3776
3777/*
drhd91c68f2010-05-14 14:52:25 +00003778** Object used to represent an shared memory buffer.
3779**
3780** When multiple threads all reference the same wal-index, each thread
3781** has its own unixShm object, but they all point to a single instance
3782** of this unixShmNode object. In other words, each wal-index is opened
3783** only once per process.
3784**
3785** Each unixShmNode object is connected to a single unixInodeInfo object.
3786** We could coalesce this object into unixInodeInfo, but that would mean
3787** every open file that does not use shared memory (in other words, most
3788** open files) would have to carry around this extra information. So
3789** the unixInodeInfo object contains a pointer to this unixShmNode object
3790** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003791**
3792** unixMutexHeld() must be true when creating or destroying
3793** this object or while reading or writing the following fields:
3794**
3795** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003796**
3797** The following fields are read-only after the object is created:
3798**
3799** fid
3800** zFilename
3801**
drhd91c68f2010-05-14 14:52:25 +00003802** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003803** unixMutexHeld() is true when reading or writing any other field
3804** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003805*/
drhd91c68f2010-05-14 14:52:25 +00003806struct unixShmNode {
3807 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003808 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003809 char *zFilename; /* Name of the mmapped file */
3810 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003811 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003812 u16 nRegion; /* Size of array apRegion */
3813 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003814 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003815 int nRef; /* Number of unixShm objects pointing to this */
3816 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003817#ifdef SQLITE_DEBUG
3818 u8 exclMask; /* Mask of exclusive locks held */
3819 u8 sharedMask; /* Mask of shared locks held */
3820 u8 nextShmId; /* Next available unixShm.id value */
3821#endif
3822};
3823
3824/*
drhd9e5c4f2010-05-12 18:01:39 +00003825** Structure used internally by this VFS to record the state of an
3826** open shared memory connection.
3827**
drhd91c68f2010-05-14 14:52:25 +00003828** The following fields are initialized when this object is created and
3829** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003830**
drhd91c68f2010-05-14 14:52:25 +00003831** unixShm.pFile
3832** unixShm.id
3833**
3834** All other fields are read/write. The unixShm.pFile->mutex must be held
3835** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003836*/
3837struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003838 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3839 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003840 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003841 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003842 u16 sharedMask; /* Mask of shared locks held */
3843 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003844};
3845
3846/*
drhd9e5c4f2010-05-12 18:01:39 +00003847** Constants used for locking
3848*/
drhbd9676c2010-06-23 17:58:38 +00003849#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003850#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003851
drhd9e5c4f2010-05-12 18:01:39 +00003852/*
drh73b64e42010-05-30 19:55:15 +00003853** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003854**
3855** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3856** otherwise.
3857*/
3858static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003859 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3860 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003861 int ofst, /* First byte of the locking range */
3862 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003863){
3864 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003865 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003866
drhd91c68f2010-05-14 14:52:25 +00003867 /* Access to the unixShmNode object is serialized by the caller */
3868 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003869
drh73b64e42010-05-30 19:55:15 +00003870 /* Shared locks never span more than one byte */
3871 assert( n==1 || lockType!=F_RDLCK );
3872
3873 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003874 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003875
drh3cb93392011-03-12 18:10:44 +00003876 if( pShmNode->h>=0 ){
3877 /* Initialize the locking parameters */
3878 memset(&f, 0, sizeof(f));
3879 f.l_type = lockType;
3880 f.l_whence = SEEK_SET;
3881 f.l_start = ofst;
3882 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003883
drh3cb93392011-03-12 18:10:44 +00003884 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3885 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3886 }
drhd9e5c4f2010-05-12 18:01:39 +00003887
3888 /* Update the global lock state and do debug tracing */
3889#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003890 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003891 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003892 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003893 if( rc==SQLITE_OK ){
3894 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003895 OSTRACE(("unlock %d ok", ofst));
3896 pShmNode->exclMask &= ~mask;
3897 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003898 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003899 OSTRACE(("read-lock %d ok", ofst));
3900 pShmNode->exclMask &= ~mask;
3901 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003902 }else{
3903 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003904 OSTRACE(("write-lock %d ok", ofst));
3905 pShmNode->exclMask |= mask;
3906 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003907 }
3908 }else{
3909 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003910 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003911 }else if( lockType==F_RDLCK ){
3912 OSTRACE(("read-lock failed"));
3913 }else{
3914 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003915 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003916 }
3917 }
drh20e1f082010-05-31 16:10:12 +00003918 OSTRACE((" - afterwards %03x,%03x\n",
3919 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003920 }
drhd9e5c4f2010-05-12 18:01:39 +00003921#endif
3922
3923 return rc;
3924}
3925
drhd9e5c4f2010-05-12 18:01:39 +00003926
3927/*
drhd91c68f2010-05-14 14:52:25 +00003928** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003929**
3930** This is not a VFS shared-memory method; it is a utility function called
3931** by VFS shared-memory methods.
3932*/
drhd91c68f2010-05-14 14:52:25 +00003933static void unixShmPurge(unixFile *pFd){
3934 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003935 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003936 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003937 int i;
drhd91c68f2010-05-14 14:52:25 +00003938 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003939 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003940 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003941 if( p->h>=0 ){
3942 munmap(p->apRegion[i], p->szRegion);
3943 }else{
3944 sqlite3_free(p->apRegion[i]);
3945 }
dan13a3cb82010-06-11 19:04:21 +00003946 }
dan18801912010-06-14 14:07:50 +00003947 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003948 if( p->h>=0 ){
3949 robust_close(pFd, p->h, __LINE__);
3950 p->h = -1;
3951 }
drhd91c68f2010-05-14 14:52:25 +00003952 p->pInode->pShmNode = 0;
3953 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003954 }
3955}
3956
3957/*
danda9fe0c2010-07-13 18:44:03 +00003958** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003959** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003960**
drh7234c6d2010-06-19 15:10:09 +00003961** The file used to implement shared-memory is in the same directory
3962** as the open database file and has the same name as the open database
3963** file with the "-shm" suffix added. For example, if the database file
3964** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003965** for shared memory will be called "/home/user1/config.db-shm".
3966**
3967** Another approach to is to use files in /dev/shm or /dev/tmp or an
3968** some other tmpfs mount. But if a file in a different directory
3969** from the database file is used, then differing access permissions
3970** or a chroot() might cause two different processes on the same
3971** database to end up using different files for shared memory -
3972** meaning that their memory would not really be shared - resulting
3973** in database corruption. Nevertheless, this tmpfs file usage
3974** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3975** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3976** option results in an incompatible build of SQLite; builds of SQLite
3977** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3978** same database file at the same time, database corruption will likely
3979** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3980** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003981**
3982** When opening a new shared-memory file, if no other instances of that
3983** file are currently open, in this process or in other processes, then
3984** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003985**
3986** If the original database file (pDbFd) is using the "unix-excl" VFS
3987** that means that an exclusive lock is held on the database file and
3988** that no other processes are able to read or write the database. In
3989** that case, we do not really need shared memory. No shared memory
3990** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003991*/
danda9fe0c2010-07-13 18:44:03 +00003992static int unixOpenSharedMemory(unixFile *pDbFd){
3993 struct unixShm *p = 0; /* The connection to be opened */
3994 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3995 int rc; /* Result code */
3996 unixInodeInfo *pInode; /* The inode of fd */
3997 char *zShmFilename; /* Name of the file used for SHM */
3998 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003999
danda9fe0c2010-07-13 18:44:03 +00004000 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004001 p = sqlite3_malloc( sizeof(*p) );
4002 if( p==0 ) return SQLITE_NOMEM;
4003 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004004 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004005
danda9fe0c2010-07-13 18:44:03 +00004006 /* Check to see if a unixShmNode object already exists. Reuse an existing
4007 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004008 */
4009 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004010 pInode = pDbFd->pInode;
4011 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004012 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004013 struct stat sStat; /* fstat() info for database file */
4014
4015 /* Call fstat() to figure out the permissions on the database file. If
4016 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004017 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004018 */
drh3cb93392011-03-12 18:10:44 +00004019 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004020 rc = SQLITE_IOERR_FSTAT;
4021 goto shm_open_err;
4022 }
4023
drha4ced192010-07-15 18:32:40 +00004024#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004025 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004026#else
drh52bcde02012-01-03 14:50:45 +00004027 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004028#endif
drh7234c6d2010-06-19 15:10:09 +00004029 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004030 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004031 rc = SQLITE_NOMEM;
4032 goto shm_open_err;
4033 }
drh9cb5a0d2012-01-05 21:19:54 +00004034 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004035 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004036#ifdef SQLITE_SHM_DIRECTORY
4037 sqlite3_snprintf(nShmFilename, zShmFilename,
4038 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4039 (u32)sStat.st_ino, (u32)sStat.st_dev);
4040#else
drh7234c6d2010-06-19 15:10:09 +00004041 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004042 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004043#endif
drhd91c68f2010-05-14 14:52:25 +00004044 pShmNode->h = -1;
4045 pDbFd->pInode->pShmNode = pShmNode;
4046 pShmNode->pInode = pDbFd->pInode;
4047 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4048 if( pShmNode->mutex==0 ){
4049 rc = SQLITE_NOMEM;
4050 goto shm_open_err;
4051 }
drhd9e5c4f2010-05-12 18:01:39 +00004052
drh3cb93392011-03-12 18:10:44 +00004053 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004054 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004055 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004056 openFlags = O_RDONLY;
4057 pShmNode->isReadonly = 1;
4058 }
4059 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004060 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004061 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4062 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004063 }
drhac7c3ac2012-02-11 19:23:48 +00004064
4065 /* If this process is running as root, make sure that the SHM file
4066 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004067 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004068 */
drhed466822012-05-31 13:10:49 +00004069 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004070
4071 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004072 ** If not, truncate the file to zero length.
4073 */
4074 rc = SQLITE_OK;
4075 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4076 if( robust_ftruncate(pShmNode->h, 0) ){
4077 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004078 }
4079 }
drh66dfec8b2011-06-01 20:01:49 +00004080 if( rc==SQLITE_OK ){
4081 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4082 }
4083 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004084 }
drhd9e5c4f2010-05-12 18:01:39 +00004085 }
4086
drhd91c68f2010-05-14 14:52:25 +00004087 /* Make the new connection a child of the unixShmNode */
4088 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004089#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004090 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004091#endif
drhd91c68f2010-05-14 14:52:25 +00004092 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004093 pDbFd->pShm = p;
4094 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004095
4096 /* The reference count on pShmNode has already been incremented under
4097 ** the cover of the unixEnterMutex() mutex and the pointer from the
4098 ** new (struct unixShm) object to the pShmNode has been set. All that is
4099 ** left to do is to link the new object into the linked list starting
4100 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4101 ** mutex.
4102 */
4103 sqlite3_mutex_enter(pShmNode->mutex);
4104 p->pNext = pShmNode->pFirst;
4105 pShmNode->pFirst = p;
4106 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004107 return SQLITE_OK;
4108
4109 /* Jump here on any error */
4110shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004111 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004112 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004113 unixLeaveMutex();
4114 return rc;
4115}
4116
4117/*
danda9fe0c2010-07-13 18:44:03 +00004118** This function is called to obtain a pointer to region iRegion of the
4119** shared-memory associated with the database file fd. Shared-memory regions
4120** are numbered starting from zero. Each shared-memory region is szRegion
4121** bytes in size.
4122**
4123** If an error occurs, an error code is returned and *pp is set to NULL.
4124**
4125** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4126** region has not been allocated (by any client, including one running in a
4127** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4128** bExtend is non-zero and the requested shared-memory region has not yet
4129** been allocated, it is allocated by this function.
4130**
4131** If the shared-memory region has already been allocated or is allocated by
4132** this call as described above, then it is mapped into this processes
4133** address space (if it is not already), *pp is set to point to the mapped
4134** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004135*/
danda9fe0c2010-07-13 18:44:03 +00004136static int unixShmMap(
4137 sqlite3_file *fd, /* Handle open on database file */
4138 int iRegion, /* Region to retrieve */
4139 int szRegion, /* Size of regions */
4140 int bExtend, /* True to extend file if necessary */
4141 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004142){
danda9fe0c2010-07-13 18:44:03 +00004143 unixFile *pDbFd = (unixFile*)fd;
4144 unixShm *p;
4145 unixShmNode *pShmNode;
4146 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004147
danda9fe0c2010-07-13 18:44:03 +00004148 /* If the shared-memory file has not yet been opened, open it now. */
4149 if( pDbFd->pShm==0 ){
4150 rc = unixOpenSharedMemory(pDbFd);
4151 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004152 }
drhd9e5c4f2010-05-12 18:01:39 +00004153
danda9fe0c2010-07-13 18:44:03 +00004154 p = pDbFd->pShm;
4155 pShmNode = p->pShmNode;
4156 sqlite3_mutex_enter(pShmNode->mutex);
4157 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004158 assert( pShmNode->pInode==pDbFd->pInode );
4159 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4160 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004161
4162 if( pShmNode->nRegion<=iRegion ){
4163 char **apNew; /* New apRegion[] array */
4164 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4165 struct stat sStat; /* Used by fstat() */
4166
4167 pShmNode->szRegion = szRegion;
4168
drh3cb93392011-03-12 18:10:44 +00004169 if( pShmNode->h>=0 ){
4170 /* The requested region is not mapped into this processes address space.
4171 ** Check to see if it has been allocated (i.e. if the wal-index file is
4172 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004173 */
drh3cb93392011-03-12 18:10:44 +00004174 if( osFstat(pShmNode->h, &sStat) ){
4175 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004176 goto shmpage_out;
4177 }
drh3cb93392011-03-12 18:10:44 +00004178
4179 if( sStat.st_size<nByte ){
4180 /* The requested memory region does not exist. If bExtend is set to
4181 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4182 **
4183 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4184 ** the requested memory region.
4185 */
4186 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004187#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4188 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4189 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4190 pShmNode->zFilename);
4191 goto shmpage_out;
4192 }
4193#else
drh3cb93392011-03-12 18:10:44 +00004194 if( robust_ftruncate(pShmNode->h, nByte) ){
4195 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4196 pShmNode->zFilename);
4197 goto shmpage_out;
4198 }
drh0fbb50e2012-11-13 10:54:12 +00004199#endif
drh3cb93392011-03-12 18:10:44 +00004200 }
danda9fe0c2010-07-13 18:44:03 +00004201 }
4202
4203 /* Map the requested memory region into this processes address space. */
4204 apNew = (char **)sqlite3_realloc(
4205 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4206 );
4207 if( !apNew ){
4208 rc = SQLITE_IOERR_NOMEM;
4209 goto shmpage_out;
4210 }
4211 pShmNode->apRegion = apNew;
4212 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004213 void *pMem;
4214 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004215 pMem = mmap(0, szRegion,
4216 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004217 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004218 );
4219 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004220 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004221 goto shmpage_out;
4222 }
4223 }else{
4224 pMem = sqlite3_malloc(szRegion);
4225 if( pMem==0 ){
4226 rc = SQLITE_NOMEM;
4227 goto shmpage_out;
4228 }
4229 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004230 }
4231 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4232 pShmNode->nRegion++;
4233 }
4234 }
4235
4236shmpage_out:
4237 if( pShmNode->nRegion>iRegion ){
4238 *pp = pShmNode->apRegion[iRegion];
4239 }else{
4240 *pp = 0;
4241 }
drh66dfec8b2011-06-01 20:01:49 +00004242 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004243 sqlite3_mutex_leave(pShmNode->mutex);
4244 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004245}
4246
4247/*
drhd9e5c4f2010-05-12 18:01:39 +00004248** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004249**
4250** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4251** different here than in posix. In xShmLock(), one can go from unlocked
4252** to shared and back or from unlocked to exclusive and back. But one may
4253** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004254*/
4255static int unixShmLock(
4256 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004257 int ofst, /* First lock to acquire or release */
4258 int n, /* Number of locks to acquire or release */
4259 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004260){
drh73b64e42010-05-30 19:55:15 +00004261 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4262 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4263 unixShm *pX; /* For looping over all siblings */
4264 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4265 int rc = SQLITE_OK; /* Result code */
4266 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004267
drhd91c68f2010-05-14 14:52:25 +00004268 assert( pShmNode==pDbFd->pInode->pShmNode );
4269 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004270 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004271 assert( n>=1 );
4272 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4273 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4274 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4275 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4276 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004277 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4278 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004279
drhc99597c2010-05-31 01:41:15 +00004280 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004281 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004282 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004283 if( flags & SQLITE_SHM_UNLOCK ){
4284 u16 allMask = 0; /* Mask of locks held by siblings */
4285
4286 /* See if any siblings hold this same lock */
4287 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4288 if( pX==p ) continue;
4289 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4290 allMask |= pX->sharedMask;
4291 }
4292
4293 /* Unlock the system-level locks */
4294 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004295 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004296 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004297 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004298 }
drh73b64e42010-05-30 19:55:15 +00004299
4300 /* Undo the local locks */
4301 if( rc==SQLITE_OK ){
4302 p->exclMask &= ~mask;
4303 p->sharedMask &= ~mask;
4304 }
4305 }else if( flags & SQLITE_SHM_SHARED ){
4306 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4307
4308 /* Find out which shared locks are already held by sibling connections.
4309 ** If any sibling already holds an exclusive lock, go ahead and return
4310 ** SQLITE_BUSY.
4311 */
4312 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004313 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004314 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004315 break;
4316 }
4317 allShared |= pX->sharedMask;
4318 }
4319
4320 /* Get shared locks at the system level, if necessary */
4321 if( rc==SQLITE_OK ){
4322 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004323 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004324 }else{
drh73b64e42010-05-30 19:55:15 +00004325 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004326 }
drhd9e5c4f2010-05-12 18:01:39 +00004327 }
drh73b64e42010-05-30 19:55:15 +00004328
4329 /* Get the local shared locks */
4330 if( rc==SQLITE_OK ){
4331 p->sharedMask |= mask;
4332 }
4333 }else{
4334 /* Make sure no sibling connections hold locks that will block this
4335 ** lock. If any do, return SQLITE_BUSY right away.
4336 */
4337 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004338 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4339 rc = SQLITE_BUSY;
4340 break;
4341 }
4342 }
4343
4344 /* Get the exclusive locks at the system level. Then if successful
4345 ** also mark the local connection as being locked.
4346 */
4347 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004348 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004349 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004350 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004351 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004352 }
drhd9e5c4f2010-05-12 18:01:39 +00004353 }
4354 }
drhd91c68f2010-05-14 14:52:25 +00004355 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004356 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4357 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004358 return rc;
4359}
4360
drh286a2882010-05-20 23:51:06 +00004361/*
4362** Implement a memory barrier or memory fence on shared memory.
4363**
4364** All loads and stores begun before the barrier must complete before
4365** any load or store begun after the barrier.
4366*/
4367static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004368 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004369){
drhff828942010-06-26 21:34:06 +00004370 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004371 unixEnterMutex();
4372 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004373}
4374
dan18801912010-06-14 14:07:50 +00004375/*
danda9fe0c2010-07-13 18:44:03 +00004376** Close a connection to shared-memory. Delete the underlying
4377** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004378**
4379** If there is no shared memory associated with the connection then this
4380** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004381*/
danda9fe0c2010-07-13 18:44:03 +00004382static int unixShmUnmap(
4383 sqlite3_file *fd, /* The underlying database file */
4384 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004385){
danda9fe0c2010-07-13 18:44:03 +00004386 unixShm *p; /* The connection to be closed */
4387 unixShmNode *pShmNode; /* The underlying shared-memory file */
4388 unixShm **pp; /* For looping over sibling connections */
4389 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004390
danda9fe0c2010-07-13 18:44:03 +00004391 pDbFd = (unixFile*)fd;
4392 p = pDbFd->pShm;
4393 if( p==0 ) return SQLITE_OK;
4394 pShmNode = p->pShmNode;
4395
4396 assert( pShmNode==pDbFd->pInode->pShmNode );
4397 assert( pShmNode->pInode==pDbFd->pInode );
4398
4399 /* Remove connection p from the set of connections associated
4400 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004401 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004402 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4403 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004404
danda9fe0c2010-07-13 18:44:03 +00004405 /* Free the connection p */
4406 sqlite3_free(p);
4407 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004408 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004409
4410 /* If pShmNode->nRef has reached 0, then close the underlying
4411 ** shared-memory file, too */
4412 unixEnterMutex();
4413 assert( pShmNode->nRef>0 );
4414 pShmNode->nRef--;
4415 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004416 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004417 unixShmPurge(pDbFd);
4418 }
4419 unixLeaveMutex();
4420
4421 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004422}
drh286a2882010-05-20 23:51:06 +00004423
danda9fe0c2010-07-13 18:44:03 +00004424
drhd9e5c4f2010-05-12 18:01:39 +00004425#else
drh6b017cc2010-06-14 18:01:46 +00004426# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004427# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004428# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004429# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004430#endif /* #ifndef SQLITE_OMIT_WAL */
4431
drh734c9862008-11-28 15:37:20 +00004432/*
dand306e1a2013-03-20 18:25:49 +00004433** Arguments x and y are both integers. Argument y must be a power of 2.
4434** Round x up to the nearest integer multiple of y. For example:
4435**
4436** ROUNDUP(0, 8) -> 0
4437** ROUNDUP(13, 8) -> 16
4438** ROUNDUP(32, 8) -> 32
4439*/
4440#define ROUNDUP(x,y) (((x)+y-1)&~(y-1))
4441
4442/*
dan5d8a1372013-03-19 19:28:06 +00004443** Map, remap or unmap part of the database file.
4444*/
4445static int unixMremap(
4446 sqlite3_file *fd, /* Main database file */
daneb97b292013-03-20 14:26:59 +00004447 int flags, /* Mask of SQLITE_MREMAP_XXX flags */
dan5d8a1372013-03-19 19:28:06 +00004448 sqlite3_int64 iOff, /* Offset to start mapping at */
4449 sqlite3_int64 nOld, /* Size of old mapping, or zero */
4450 sqlite3_int64 nNew, /* Size of new mapping, or zero */
4451 void **ppMap /* IN/OUT: Old/new mappings */
4452){
4453 unixFile *p = (unixFile *)fd; /* The underlying database file */
4454 int rc = SQLITE_OK; /* Return code */
4455 void *pNew = 0; /* New mapping */
dand306e1a2013-03-20 18:25:49 +00004456 i64 nNewRnd; /* nNew rounded up */
4457 i64 nOldRnd; /* nOld rounded up */
dan5d8a1372013-03-19 19:28:06 +00004458
4459 assert( iOff==0 );
daneb97b292013-03-20 14:26:59 +00004460
4461 /* If the SQLITE_MREMAP_EXTEND flag is set, then the size of the requested
4462 ** mapping (nNew bytes) may be greater than the size of the database file.
4463 ** If this is the case, extend the file on disk using ftruncate(). */
4464 assert( nNew>0 || (flags & SQLITE_MREMAP_EXTEND)==0 );
4465 if( flags & SQLITE_MREMAP_EXTEND ){
4466 struct stat statbuf; /* Low-level file information */
4467 rc = osFstat(p->h, &statbuf);
4468 if( rc==SQLITE_OK && nNew>statbuf.st_size ){
4469 rc = robust_ftruncate(p->h, nNew);
4470 }
4471 if( rc!=SQLITE_OK ) return rc;
4472 }
4473
dand306e1a2013-03-20 18:25:49 +00004474 /* According to some sources, the effect of changing the size of the
4475 ** underlying file on mapped regions that correspond to the added or
4476 ** removed pages is undefined. However, there is reason to believe that
4477 ** on modern platforms like Linux or OSX, things just work. For example,
4478 ** it is possible to create a mapping larger than the file on disk and
4479 ** extend the file on disk later on.
4480 **
danc71b45e2013-03-21 14:47:47 +00004481 ** Exploit this on Linux and OSX to reduce the number of munmap()/mmap()
4482 ** calls required if the file size is changing. In this case all mappings
4483 ** are rounded up to the nearest 4MB. And if a new mapping is requested
4484 ** that has the same rounded size as an old mapping, the old mapping can
4485 ** be reused as is. */
4486#if defined(__APPLE__) || defined(__linux__)
dand306e1a2013-03-20 18:25:49 +00004487 nNewRnd = ROUNDUP(nNew, 4096*1024);
4488 nOldRnd = ROUNDUP(nOld, 4096*1024);
4489#else
4490 nNewRnd = ROUNDUP(nNew, 4096*1);
4491 nOldRnd = ROUNDUP(nOld, 4096*1);
4492#endif
4493
4494 /* On OSX or Linux, reuse the old mapping if it is the right size. */
4495#if defined(__APPLE__) || defined(__linux__)
4496 if( nNewRnd==nOldRnd ){
4497 return SQLITE_OK;
4498 }
4499#endif
4500
dand306e1a2013-03-20 18:25:49 +00004501 /* If we get this far, unmap any old mapping. */
4502 if( nOldRnd!=0 ){
dan5d8a1372013-03-19 19:28:06 +00004503 void *pOld = *ppMap;
dand306e1a2013-03-20 18:25:49 +00004504 munmap(pOld, nOldRnd);
dan5d8a1372013-03-19 19:28:06 +00004505 }
4506
dand306e1a2013-03-20 18:25:49 +00004507 /* And, if required, use mmap() to create a new mapping. */
4508 if( nNewRnd>0 ){
dan5d8a1372013-03-19 19:28:06 +00004509 int flags = PROT_READ;
4510 if( (p->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
dand306e1a2013-03-20 18:25:49 +00004511 pNew = mmap(0, nNewRnd, flags, MAP_SHARED, p->h, iOff);
dan5d8a1372013-03-19 19:28:06 +00004512 if( pNew==MAP_FAILED ){
4513 pNew = 0;
daneb97b292013-03-20 14:26:59 +00004514 rc = SQLITE_IOERR_MREMAP;
dan5d8a1372013-03-19 19:28:06 +00004515 }
4516 }
4517
4518 *ppMap = pNew;
4519 return rc;
4520}
4521
4522/*
drh734c9862008-11-28 15:37:20 +00004523** Here ends the implementation of all sqlite3_file methods.
4524**
4525********************** End sqlite3_file Methods *******************************
4526******************************************************************************/
4527
4528/*
drh6b9d6dd2008-12-03 19:34:47 +00004529** This division contains definitions of sqlite3_io_methods objects that
4530** implement various file locking strategies. It also contains definitions
4531** of "finder" functions. A finder-function is used to locate the appropriate
4532** sqlite3_io_methods object for a particular database file. The pAppData
4533** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4534** the correct finder-function for that VFS.
4535**
4536** Most finder functions return a pointer to a fixed sqlite3_io_methods
4537** object. The only interesting finder-function is autolockIoFinder, which
4538** looks at the filesystem type and tries to guess the best locking
4539** strategy from that.
4540**
drh1875f7a2008-12-08 18:19:17 +00004541** For finder-funtion F, two objects are created:
4542**
4543** (1) The real finder-function named "FImpt()".
4544**
dane946c392009-08-22 11:39:46 +00004545** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004546**
4547**
4548** A pointer to the F pointer is used as the pAppData value for VFS
4549** objects. We have to do this instead of letting pAppData point
4550** directly at the finder-function since C90 rules prevent a void*
4551** from be cast into a function pointer.
4552**
drh6b9d6dd2008-12-03 19:34:47 +00004553**
drh7708e972008-11-29 00:56:52 +00004554** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004555**
drh7708e972008-11-29 00:56:52 +00004556** * A constant sqlite3_io_methods object call METHOD that has locking
4557** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4558**
4559** * An I/O method finder function called FINDER that returns a pointer
4560** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004561*/
drhd9e5c4f2010-05-12 18:01:39 +00004562#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004563static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004564 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004565 CLOSE, /* xClose */ \
4566 unixRead, /* xRead */ \
4567 unixWrite, /* xWrite */ \
4568 unixTruncate, /* xTruncate */ \
4569 unixSync, /* xSync */ \
4570 unixFileSize, /* xFileSize */ \
4571 LOCK, /* xLock */ \
4572 UNLOCK, /* xUnlock */ \
4573 CKLOCK, /* xCheckReservedLock */ \
4574 unixFileControl, /* xFileControl */ \
4575 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004576 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004577 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004578 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004579 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004580 unixShmUnmap, /* xShmUnmap */ \
4581 unixMremap, /* xMremap */ \
drh7708e972008-11-29 00:56:52 +00004582}; \
drh0c2694b2009-09-03 16:23:44 +00004583static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4584 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004585 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004586} \
drh0c2694b2009-09-03 16:23:44 +00004587static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004588 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004589
4590/*
4591** Here are all of the sqlite3_io_methods objects for each of the
4592** locking strategies. Functions that return pointers to these methods
4593** are also created.
4594*/
4595IOMETHODS(
4596 posixIoFinder, /* Finder function name */
4597 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004598 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004599 unixClose, /* xClose method */
4600 unixLock, /* xLock method */
4601 unixUnlock, /* xUnlock method */
4602 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004603)
drh7708e972008-11-29 00:56:52 +00004604IOMETHODS(
4605 nolockIoFinder, /* Finder function name */
4606 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004607 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004608 nolockClose, /* xClose method */
4609 nolockLock, /* xLock method */
4610 nolockUnlock, /* xUnlock method */
4611 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004612)
drh7708e972008-11-29 00:56:52 +00004613IOMETHODS(
4614 dotlockIoFinder, /* Finder function name */
4615 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004616 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004617 dotlockClose, /* xClose method */
4618 dotlockLock, /* xLock method */
4619 dotlockUnlock, /* xUnlock method */
4620 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004621)
drh7708e972008-11-29 00:56:52 +00004622
chw78a13182009-04-07 05:35:03 +00004623#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004624IOMETHODS(
4625 flockIoFinder, /* Finder function name */
4626 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004627 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004628 flockClose, /* xClose method */
4629 flockLock, /* xLock method */
4630 flockUnlock, /* xUnlock method */
4631 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004632)
drh7708e972008-11-29 00:56:52 +00004633#endif
4634
drh6c7d5c52008-11-21 20:32:33 +00004635#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004636IOMETHODS(
4637 semIoFinder, /* Finder function name */
4638 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004639 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004640 semClose, /* xClose method */
4641 semLock, /* xLock method */
4642 semUnlock, /* xUnlock method */
4643 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004644)
aswiftaebf4132008-11-21 00:10:35 +00004645#endif
drh7708e972008-11-29 00:56:52 +00004646
drhd2cb50b2009-01-09 21:41:17 +00004647#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004648IOMETHODS(
4649 afpIoFinder, /* Finder function name */
4650 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004651 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004652 afpClose, /* xClose method */
4653 afpLock, /* xLock method */
4654 afpUnlock, /* xUnlock method */
4655 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004656)
drh715ff302008-12-03 22:32:44 +00004657#endif
4658
4659/*
4660** The proxy locking method is a "super-method" in the sense that it
4661** opens secondary file descriptors for the conch and lock files and
4662** it uses proxy, dot-file, AFP, and flock() locking methods on those
4663** secondary files. For this reason, the division that implements
4664** proxy locking is located much further down in the file. But we need
4665** to go ahead and define the sqlite3_io_methods and finder function
4666** for proxy locking here. So we forward declare the I/O methods.
4667*/
drhd2cb50b2009-01-09 21:41:17 +00004668#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004669static int proxyClose(sqlite3_file*);
4670static int proxyLock(sqlite3_file*, int);
4671static int proxyUnlock(sqlite3_file*, int);
4672static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004673IOMETHODS(
4674 proxyIoFinder, /* Finder function name */
4675 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004676 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004677 proxyClose, /* xClose method */
4678 proxyLock, /* xLock method */
4679 proxyUnlock, /* xUnlock method */
4680 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004681)
aswiftaebf4132008-11-21 00:10:35 +00004682#endif
drh7708e972008-11-29 00:56:52 +00004683
drh7ed97b92010-01-20 13:07:21 +00004684/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4685#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4686IOMETHODS(
4687 nfsIoFinder, /* Finder function name */
4688 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004689 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004690 unixClose, /* xClose method */
4691 unixLock, /* xLock method */
4692 nfsUnlock, /* xUnlock method */
4693 unixCheckReservedLock /* xCheckReservedLock method */
4694)
4695#endif
drh7708e972008-11-29 00:56:52 +00004696
drhd2cb50b2009-01-09 21:41:17 +00004697#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004698/*
drh6b9d6dd2008-12-03 19:34:47 +00004699** This "finder" function attempts to determine the best locking strategy
4700** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004701** object that implements that strategy.
4702**
4703** This is for MacOSX only.
4704*/
drh1875f7a2008-12-08 18:19:17 +00004705static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004706 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004707 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004708){
4709 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004710 const char *zFilesystem; /* Filesystem type name */
4711 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004712 } aMap[] = {
4713 { "hfs", &posixIoMethods },
4714 { "ufs", &posixIoMethods },
4715 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004716 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004717 { "webdav", &nolockIoMethods },
4718 { 0, 0 }
4719 };
4720 int i;
4721 struct statfs fsInfo;
4722 struct flock lockInfo;
4723
4724 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004725 /* If filePath==NULL that means we are dealing with a transient file
4726 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004727 return &nolockIoMethods;
4728 }
4729 if( statfs(filePath, &fsInfo) != -1 ){
4730 if( fsInfo.f_flags & MNT_RDONLY ){
4731 return &nolockIoMethods;
4732 }
4733 for(i=0; aMap[i].zFilesystem; i++){
4734 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4735 return aMap[i].pMethods;
4736 }
4737 }
4738 }
4739
4740 /* Default case. Handles, amongst others, "nfs".
4741 ** Test byte-range lock using fcntl(). If the call succeeds,
4742 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004743 */
drh7708e972008-11-29 00:56:52 +00004744 lockInfo.l_len = 1;
4745 lockInfo.l_start = 0;
4746 lockInfo.l_whence = SEEK_SET;
4747 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004748 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004749 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4750 return &nfsIoMethods;
4751 } else {
4752 return &posixIoMethods;
4753 }
drh7708e972008-11-29 00:56:52 +00004754 }else{
4755 return &dotlockIoMethods;
4756 }
4757}
drh0c2694b2009-09-03 16:23:44 +00004758static const sqlite3_io_methods
4759 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004760
drhd2cb50b2009-01-09 21:41:17 +00004761#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004762
chw78a13182009-04-07 05:35:03 +00004763#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4764/*
4765** This "finder" function attempts to determine the best locking strategy
4766** for the database file "filePath". It then returns the sqlite3_io_methods
4767** object that implements that strategy.
4768**
4769** This is for VXWorks only.
4770*/
4771static const sqlite3_io_methods *autolockIoFinderImpl(
4772 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004773 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004774){
4775 struct flock lockInfo;
4776
4777 if( !filePath ){
4778 /* If filePath==NULL that means we are dealing with a transient file
4779 ** that does not need to be locked. */
4780 return &nolockIoMethods;
4781 }
4782
4783 /* Test if fcntl() is supported and use POSIX style locks.
4784 ** Otherwise fall back to the named semaphore method.
4785 */
4786 lockInfo.l_len = 1;
4787 lockInfo.l_start = 0;
4788 lockInfo.l_whence = SEEK_SET;
4789 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004790 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004791 return &posixIoMethods;
4792 }else{
4793 return &semIoMethods;
4794 }
4795}
drh0c2694b2009-09-03 16:23:44 +00004796static const sqlite3_io_methods
4797 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004798
4799#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4800
drh7708e972008-11-29 00:56:52 +00004801/*
4802** An abstract type for a pointer to a IO method finder function:
4803*/
drh0c2694b2009-09-03 16:23:44 +00004804typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004805
aswiftaebf4132008-11-21 00:10:35 +00004806
drh734c9862008-11-28 15:37:20 +00004807/****************************************************************************
4808**************************** sqlite3_vfs methods ****************************
4809**
4810** This division contains the implementation of methods on the
4811** sqlite3_vfs object.
4812*/
4813
danielk1977a3d4c882007-03-23 10:08:38 +00004814/*
danielk1977e339d652008-06-28 11:23:00 +00004815** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004816*/
4817static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004818 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004819 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004820 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004821 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004822 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004823){
drh7708e972008-11-29 00:56:52 +00004824 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004825 unixFile *pNew = (unixFile *)pId;
4826 int rc = SQLITE_OK;
4827
drh8af6c222010-05-14 12:43:01 +00004828 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004829
dan00157392010-10-05 11:33:15 +00004830 /* Usually the path zFilename should not be a relative pathname. The
4831 ** exception is when opening the proxy "conch" file in builds that
4832 ** include the special Apple locking styles.
4833 */
dan00157392010-10-05 11:33:15 +00004834#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004835 assert( zFilename==0 || zFilename[0]=='/'
4836 || pVfs->pAppData==(void*)&autolockIoFinder );
4837#else
4838 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004839#endif
dan00157392010-10-05 11:33:15 +00004840
drhb07028f2011-10-14 21:49:18 +00004841 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004842 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004843
drh308c2a52010-05-14 11:30:18 +00004844 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004845 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004846 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004847 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004848 pNew->ctrlFlags = (u8)ctrlFlags;
4849 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4850 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004851 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004852 }
drh503a6862013-03-01 01:07:17 +00004853 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00004854 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004855 }
drh339eb0b2008-03-07 15:34:11 +00004856
drh6c7d5c52008-11-21 20:32:33 +00004857#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004858 pNew->pId = vxworksFindFileId(zFilename);
4859 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004860 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004861 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004862 }
4863#endif
4864
drhc02a43a2012-01-10 23:18:38 +00004865 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004866 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004867 }else{
drh0c2694b2009-09-03 16:23:44 +00004868 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004869#if SQLITE_ENABLE_LOCKING_STYLE
4870 /* Cache zFilename in the locking context (AFP and dotlock override) for
4871 ** proxyLock activation is possible (remote proxy is based on db name)
4872 ** zFilename remains valid until file is closed, to support */
4873 pNew->lockingContext = (void*)zFilename;
4874#endif
drhda0e7682008-07-30 15:27:54 +00004875 }
danielk1977e339d652008-06-28 11:23:00 +00004876
drh7ed97b92010-01-20 13:07:21 +00004877 if( pLockingStyle == &posixIoMethods
4878#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4879 || pLockingStyle == &nfsIoMethods
4880#endif
4881 ){
drh7708e972008-11-29 00:56:52 +00004882 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004883 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004884 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004885 /* If an error occured in findInodeInfo(), close the file descriptor
4886 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004887 ** in two scenarios:
4888 **
4889 ** (a) A call to fstat() failed.
4890 ** (b) A malloc failed.
4891 **
4892 ** Scenario (b) may only occur if the process is holding no other
4893 ** file descriptors open on the same file. If there were other file
4894 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004895 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004896 ** handle h - as it is guaranteed that no posix locks will be released
4897 ** by doing so.
4898 **
4899 ** If scenario (a) caused the error then things are not so safe. The
4900 ** implicit assumption here is that if fstat() fails, things are in
4901 ** such bad shape that dropping a lock or two doesn't matter much.
4902 */
drh0e9365c2011-03-02 02:08:13 +00004903 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004904 h = -1;
4905 }
drh7708e972008-11-29 00:56:52 +00004906 unixLeaveMutex();
4907 }
danielk1977e339d652008-06-28 11:23:00 +00004908
drhd2cb50b2009-01-09 21:41:17 +00004909#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004910 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004911 /* AFP locking uses the file path so it needs to be included in
4912 ** the afpLockingContext.
4913 */
4914 afpLockingContext *pCtx;
4915 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4916 if( pCtx==0 ){
4917 rc = SQLITE_NOMEM;
4918 }else{
4919 /* NB: zFilename exists and remains valid until the file is closed
4920 ** according to requirement F11141. So we do not need to make a
4921 ** copy of the filename. */
4922 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004923 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004924 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004925 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004926 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004927 if( rc!=SQLITE_OK ){
4928 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004929 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004930 h = -1;
4931 }
drh7708e972008-11-29 00:56:52 +00004932 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004933 }
drh7708e972008-11-29 00:56:52 +00004934 }
4935#endif
danielk1977e339d652008-06-28 11:23:00 +00004936
drh7708e972008-11-29 00:56:52 +00004937 else if( pLockingStyle == &dotlockIoMethods ){
4938 /* Dotfile locking uses the file path so it needs to be included in
4939 ** the dotlockLockingContext
4940 */
4941 char *zLockFile;
4942 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004943 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004944 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004945 zLockFile = (char *)sqlite3_malloc(nFilename);
4946 if( zLockFile==0 ){
4947 rc = SQLITE_NOMEM;
4948 }else{
4949 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004950 }
drh7708e972008-11-29 00:56:52 +00004951 pNew->lockingContext = zLockFile;
4952 }
danielk1977e339d652008-06-28 11:23:00 +00004953
drh6c7d5c52008-11-21 20:32:33 +00004954#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004955 else if( pLockingStyle == &semIoMethods ){
4956 /* Named semaphore locking uses the file path so it needs to be
4957 ** included in the semLockingContext
4958 */
4959 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004960 rc = findInodeInfo(pNew, &pNew->pInode);
4961 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4962 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004963 int n;
drh2238dcc2009-08-27 17:56:20 +00004964 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004965 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004966 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004967 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004968 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4969 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004970 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004971 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004972 }
chw97185482008-11-17 08:05:31 +00004973 }
drh7708e972008-11-29 00:56:52 +00004974 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004975 }
drh7708e972008-11-29 00:56:52 +00004976#endif
aswift5b1a2562008-08-22 00:22:35 +00004977
4978 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004979#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004980 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004981 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004982 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004983 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004984 isDelete = 0;
4985 }
drhc02a43a2012-01-10 23:18:38 +00004986 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004987#endif
danielk1977e339d652008-06-28 11:23:00 +00004988 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004989 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004990 }else{
drh7708e972008-11-29 00:56:52 +00004991 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004992 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004993 }
danielk1977e339d652008-06-28 11:23:00 +00004994 return rc;
drh054889e2005-11-30 03:20:31 +00004995}
drh9c06c952005-11-26 00:25:00 +00004996
danielk1977ad94b582007-08-20 06:44:22 +00004997/*
drh8b3cf822010-06-01 21:02:51 +00004998** Return the name of a directory in which to put temporary files.
4999** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005000*/
drh7234c6d2010-06-19 15:10:09 +00005001static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005002 static const char *azDirs[] = {
5003 0,
aswiftaebf4132008-11-21 00:10:35 +00005004 0,
danielk197717b90b52008-06-06 11:11:25 +00005005 "/var/tmp",
5006 "/usr/tmp",
5007 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005008 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005009 };
drh8b3cf822010-06-01 21:02:51 +00005010 unsigned int i;
5011 struct stat buf;
5012 const char *zDir = 0;
5013
5014 azDirs[0] = sqlite3_temp_directory;
5015 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005016 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005017 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005018 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005019 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005020 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005021 break;
5022 }
5023 return zDir;
5024}
5025
5026/*
5027** Create a temporary file name in zBuf. zBuf must be allocated
5028** by the calling process and must be big enough to hold at least
5029** pVfs->mxPathname bytes.
5030*/
5031static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005032 static const unsigned char zChars[] =
5033 "abcdefghijklmnopqrstuvwxyz"
5034 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5035 "0123456789";
drh41022642008-11-21 00:24:42 +00005036 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005037 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005038
5039 /* It's odd to simulate an io-error here, but really this is just
5040 ** using the io-error infrastructure to test that SQLite handles this
5041 ** function failing.
5042 */
5043 SimulateIOError( return SQLITE_IOERR );
5044
drh7234c6d2010-06-19 15:10:09 +00005045 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005046 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005047
5048 /* Check that the output buffer is large enough for the temporary file
5049 ** name. If it is not, return SQLITE_ERROR.
5050 */
drhc02a43a2012-01-10 23:18:38 +00005051 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005052 return SQLITE_ERROR;
5053 }
5054
5055 do{
drhc02a43a2012-01-10 23:18:38 +00005056 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005057 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005058 sqlite3_randomness(15, &zBuf[j]);
5059 for(i=0; i<15; i++, j++){
5060 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5061 }
5062 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005063 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005064 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005065 return SQLITE_OK;
5066}
5067
drhd2cb50b2009-01-09 21:41:17 +00005068#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005069/*
5070** Routine to transform a unixFile into a proxy-locking unixFile.
5071** Implementation in the proxy-lock division, but used by unixOpen()
5072** if SQLITE_PREFER_PROXY_LOCKING is defined.
5073*/
5074static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005075#endif
drhc66d5b62008-12-03 22:48:32 +00005076
dan08da86a2009-08-21 17:18:03 +00005077/*
5078** Search for an unused file descriptor that was opened on the database
5079** file (not a journal or master-journal file) identified by pathname
5080** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5081** argument to this function.
5082**
5083** Such a file descriptor may exist if a database connection was closed
5084** but the associated file descriptor could not be closed because some
5085** other file descriptor open on the same file is holding a file-lock.
5086** Refer to comments in the unixClose() function and the lengthy comment
5087** describing "Posix Advisory Locking" at the start of this file for
5088** further details. Also, ticket #4018.
5089**
5090** If a suitable file descriptor is found, then it is returned. If no
5091** such file descriptor is located, -1 is returned.
5092*/
dane946c392009-08-22 11:39:46 +00005093static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5094 UnixUnusedFd *pUnused = 0;
5095
5096 /* Do not search for an unused file descriptor on vxworks. Not because
5097 ** vxworks would not benefit from the change (it might, we're not sure),
5098 ** but because no way to test it is currently available. It is better
5099 ** not to risk breaking vxworks support for the sake of such an obscure
5100 ** feature. */
5101#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005102 struct stat sStat; /* Results of stat() call */
5103
5104 /* A stat() call may fail for various reasons. If this happens, it is
5105 ** almost certain that an open() call on the same path will also fail.
5106 ** For this reason, if an error occurs in the stat() call here, it is
5107 ** ignored and -1 is returned. The caller will try to open a new file
5108 ** descriptor on the same path, fail, and return an error to SQLite.
5109 **
5110 ** Even if a subsequent open() call does succeed, the consequences of
5111 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005112 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005113 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005114
5115 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005116 pInode = inodeList;
5117 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5118 || pInode->fileId.ino!=sStat.st_ino) ){
5119 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005120 }
drh8af6c222010-05-14 12:43:01 +00005121 if( pInode ){
dane946c392009-08-22 11:39:46 +00005122 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005123 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005124 pUnused = *pp;
5125 if( pUnused ){
5126 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005127 }
5128 }
5129 unixLeaveMutex();
5130 }
dane946c392009-08-22 11:39:46 +00005131#endif /* if !OS_VXWORKS */
5132 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005133}
danielk197717b90b52008-06-06 11:11:25 +00005134
5135/*
danddb0ac42010-07-14 14:48:58 +00005136** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005137** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005138** and a value suitable for passing as the third argument to open(2) is
5139** written to *pMode. If an IO error occurs, an SQLite error code is
5140** returned and the value of *pMode is not modified.
5141**
drh8c815d12012-02-13 20:16:37 +00005142** In most cases cases, this routine sets *pMode to 0, which will become
5143** an indication to robust_open() to create the file using
5144** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5145** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005146** this function queries the file-system for the permissions on the
5147** corresponding database file and sets *pMode to this value. Whenever
5148** possible, WAL and journal files are created using the same permissions
5149** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005150**
5151** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5152** original filename is unavailable. But 8_3_NAMES is only used for
5153** FAT filesystems and permissions do not matter there, so just use
5154** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005155*/
5156static int findCreateFileMode(
5157 const char *zPath, /* Path of file (possibly) being created */
5158 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005159 mode_t *pMode, /* OUT: Permissions to open file with */
5160 uid_t *pUid, /* OUT: uid to set on the file */
5161 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005162){
5163 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005164 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005165 *pUid = 0;
5166 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005167 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005168 char zDb[MAX_PATHNAME+1]; /* Database file path */
5169 int nDb; /* Number of valid bytes in zDb */
5170 struct stat sStat; /* Output of stat() on database file */
5171
dana0c989d2010-11-05 18:07:37 +00005172 /* zPath is a path to a WAL or journal file. The following block derives
5173 ** the path to the associated database file from zPath. This block handles
5174 ** the following naming conventions:
5175 **
5176 ** "<path to db>-journal"
5177 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005178 ** "<path to db>-journalNN"
5179 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005180 **
drhd337c5b2011-10-20 18:23:35 +00005181 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005182 ** used by the test_multiplex.c module.
5183 */
5184 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005185#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005186 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005187 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005188#else
5189 while( zPath[nDb]!='-' ){
5190 assert( nDb>0 );
5191 assert( zPath[nDb]!='\n' );
5192 nDb--;
5193 }
5194#endif
danddb0ac42010-07-14 14:48:58 +00005195 memcpy(zDb, zPath, nDb);
5196 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005197
drh58384f12011-07-28 00:14:45 +00005198 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005199 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005200 *pUid = sStat.st_uid;
5201 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005202 }else{
5203 rc = SQLITE_IOERR_FSTAT;
5204 }
5205 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5206 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005207 }
5208 return rc;
5209}
5210
5211/*
danielk1977ad94b582007-08-20 06:44:22 +00005212** Open the file zPath.
5213**
danielk1977b4b47412007-08-17 15:53:36 +00005214** Previously, the SQLite OS layer used three functions in place of this
5215** one:
5216**
5217** sqlite3OsOpenReadWrite();
5218** sqlite3OsOpenReadOnly();
5219** sqlite3OsOpenExclusive();
5220**
5221** These calls correspond to the following combinations of flags:
5222**
5223** ReadWrite() -> (READWRITE | CREATE)
5224** ReadOnly() -> (READONLY)
5225** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5226**
5227** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5228** true, the file was configured to be automatically deleted when the
5229** file handle closed. To achieve the same effect using this new
5230** interface, add the DELETEONCLOSE flag to those specified above for
5231** OpenExclusive().
5232*/
5233static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005234 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5235 const char *zPath, /* Pathname of file to be opened */
5236 sqlite3_file *pFile, /* The file descriptor to be filled in */
5237 int flags, /* Input flags to control the opening */
5238 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005239){
dan08da86a2009-08-21 17:18:03 +00005240 unixFile *p = (unixFile *)pFile;
5241 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005242 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005243 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005244 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005245 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005246 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005247
5248 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5249 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5250 int isCreate = (flags & SQLITE_OPEN_CREATE);
5251 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5252 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005253#if SQLITE_ENABLE_LOCKING_STYLE
5254 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5255#endif
drh3d4435b2011-08-26 20:55:50 +00005256#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5257 struct statfs fsInfo;
5258#endif
danielk1977b4b47412007-08-17 15:53:36 +00005259
danielk1977fee2d252007-08-18 10:59:19 +00005260 /* If creating a master or main-file journal, this function will open
5261 ** a file-descriptor on the directory too. The first time unixSync()
5262 ** is called the directory file descriptor will be fsync()ed and close()d.
5263 */
drh0059eae2011-08-08 23:48:40 +00005264 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005265 eType==SQLITE_OPEN_MASTER_JOURNAL
5266 || eType==SQLITE_OPEN_MAIN_JOURNAL
5267 || eType==SQLITE_OPEN_WAL
5268 ));
danielk1977fee2d252007-08-18 10:59:19 +00005269
danielk197717b90b52008-06-06 11:11:25 +00005270 /* If argument zPath is a NULL pointer, this function is required to open
5271 ** a temporary file. Use this buffer to store the file name in.
5272 */
drhc02a43a2012-01-10 23:18:38 +00005273 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005274 const char *zName = zPath;
5275
danielk1977fee2d252007-08-18 10:59:19 +00005276 /* Check the following statements are true:
5277 **
5278 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5279 ** (b) if CREATE is set, then READWRITE must also be set, and
5280 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005281 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005282 */
danielk1977b4b47412007-08-17 15:53:36 +00005283 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005284 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005285 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005286 assert(isDelete==0 || isCreate);
5287
danddb0ac42010-07-14 14:48:58 +00005288 /* The main DB, main journal, WAL file and master journal are never
5289 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005290 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5291 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5292 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005293 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005294
danielk1977fee2d252007-08-18 10:59:19 +00005295 /* Assert that the upper layer has set one of the "file-type" flags. */
5296 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5297 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5298 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005299 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005300 );
5301
dan08da86a2009-08-21 17:18:03 +00005302 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005303
dan08da86a2009-08-21 17:18:03 +00005304 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005305 UnixUnusedFd *pUnused;
5306 pUnused = findReusableFd(zName, flags);
5307 if( pUnused ){
5308 fd = pUnused->fd;
5309 }else{
dan6aa657f2009-08-24 18:57:58 +00005310 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005311 if( !pUnused ){
5312 return SQLITE_NOMEM;
5313 }
5314 }
5315 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005316
5317 /* Database filenames are double-zero terminated if they are not
5318 ** URIs with parameters. Hence, they can always be passed into
5319 ** sqlite3_uri_parameter(). */
5320 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5321
dan08da86a2009-08-21 17:18:03 +00005322 }else if( !zName ){
5323 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005324 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005325 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005326 if( rc!=SQLITE_OK ){
5327 return rc;
5328 }
5329 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005330
5331 /* Generated temporary filenames are always double-zero terminated
5332 ** for use by sqlite3_uri_parameter(). */
5333 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005334 }
5335
dan08da86a2009-08-21 17:18:03 +00005336 /* Determine the value of the flags parameter passed to POSIX function
5337 ** open(). These must be calculated even if open() is not called, as
5338 ** they may be stored as part of the file handle and used by the
5339 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005340 if( isReadonly ) openFlags |= O_RDONLY;
5341 if( isReadWrite ) openFlags |= O_RDWR;
5342 if( isCreate ) openFlags |= O_CREAT;
5343 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5344 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005345
danielk1977b4b47412007-08-17 15:53:36 +00005346 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005347 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005348 uid_t uid; /* Userid for the file */
5349 gid_t gid; /* Groupid for the file */
5350 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005351 if( rc!=SQLITE_OK ){
5352 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005353 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005354 return rc;
5355 }
drhad4f1e52011-03-04 15:43:57 +00005356 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005357 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005358 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5359 /* Failed to open the file for read/write access. Try read-only. */
5360 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005361 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005362 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005363 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005364 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005365 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005366 }
5367 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005368 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005369 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005370 }
drhac7c3ac2012-02-11 19:23:48 +00005371
5372 /* If this process is running as root and if creating a new rollback
5373 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005374 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005375 */
5376 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005377 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005378 }
danielk1977b4b47412007-08-17 15:53:36 +00005379 }
dan08da86a2009-08-21 17:18:03 +00005380 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005381 if( pOutFlags ){
5382 *pOutFlags = flags;
5383 }
5384
dane946c392009-08-22 11:39:46 +00005385 if( p->pUnused ){
5386 p->pUnused->fd = fd;
5387 p->pUnused->flags = flags;
5388 }
5389
danielk1977b4b47412007-08-17 15:53:36 +00005390 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005391#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005392 zPath = zName;
5393#else
drh036ac7f2011-08-08 23:18:05 +00005394 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005395#endif
danielk1977b4b47412007-08-17 15:53:36 +00005396 }
drh41022642008-11-21 00:24:42 +00005397#if SQLITE_ENABLE_LOCKING_STYLE
5398 else{
dan08da86a2009-08-21 17:18:03 +00005399 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005400 }
5401#endif
5402
drhda0e7682008-07-30 15:27:54 +00005403 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005404
drh7ed97b92010-01-20 13:07:21 +00005405
5406#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005407 if( fstatfs(fd, &fsInfo) == -1 ){
5408 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005409 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005410 return SQLITE_IOERR_ACCESS;
5411 }
5412 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5413 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5414 }
5415#endif
drhc02a43a2012-01-10 23:18:38 +00005416
5417 /* Set up appropriate ctrlFlags */
5418 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5419 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5420 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5421 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5422 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5423
drh7ed97b92010-01-20 13:07:21 +00005424#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005425#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005426 isAutoProxy = 1;
5427#endif
5428 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005429 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5430 int useProxy = 0;
5431
dan08da86a2009-08-21 17:18:03 +00005432 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5433 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005434 if( envforce!=NULL ){
5435 useProxy = atoi(envforce)>0;
5436 }else{
aswiftaebf4132008-11-21 00:10:35 +00005437 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005438 /* In theory, the close(fd) call is sub-optimal. If the file opened
5439 ** with fd is a database file, and there are other connections open
5440 ** on that file that are currently holding advisory locks on it,
5441 ** then the call to close() will cancel those locks. In practice,
5442 ** we're assuming that statfs() doesn't fail very often. At least
5443 ** not while other file descriptors opened by the same process on
5444 ** the same file are working. */
5445 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005446 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005447 rc = SQLITE_IOERR_ACCESS;
5448 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005449 }
5450 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5451 }
5452 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005453 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005454 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005455 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005456 if( rc!=SQLITE_OK ){
5457 /* Use unixClose to clean up the resources added in fillInUnixFile
5458 ** and clear all the structure's references. Specifically,
5459 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5460 */
5461 unixClose(pFile);
5462 return rc;
5463 }
aswiftaebf4132008-11-21 00:10:35 +00005464 }
dane946c392009-08-22 11:39:46 +00005465 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005466 }
5467 }
5468#endif
5469
drhc02a43a2012-01-10 23:18:38 +00005470 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5471
dane946c392009-08-22 11:39:46 +00005472open_finished:
5473 if( rc!=SQLITE_OK ){
5474 sqlite3_free(p->pUnused);
5475 }
5476 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005477}
5478
dane946c392009-08-22 11:39:46 +00005479
danielk1977b4b47412007-08-17 15:53:36 +00005480/*
danielk1977fee2d252007-08-18 10:59:19 +00005481** Delete the file at zPath. If the dirSync argument is true, fsync()
5482** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005483*/
drh6b9d6dd2008-12-03 19:34:47 +00005484static int unixDelete(
5485 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5486 const char *zPath, /* Name of file to be deleted */
5487 int dirSync /* If true, fsync() directory after deleting file */
5488){
danielk1977fee2d252007-08-18 10:59:19 +00005489 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005490 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005491 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005492 if( osUnlink(zPath)==(-1) ){
5493 if( errno==ENOENT ){
5494 rc = SQLITE_IOERR_DELETE_NOENT;
5495 }else{
drhb4308162012-11-09 21:40:02 +00005496 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005497 }
drhb4308162012-11-09 21:40:02 +00005498 return rc;
drh5d4feff2010-07-14 01:45:22 +00005499 }
danielk1977d39fa702008-10-16 13:27:40 +00005500#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005501 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005502 int fd;
drh90315a22011-08-10 01:52:12 +00005503 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005504 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005505#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005506 if( fsync(fd)==-1 )
5507#else
5508 if( fsync(fd) )
5509#endif
5510 {
dane18d4952011-02-21 11:46:24 +00005511 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005512 }
drh0e9365c2011-03-02 02:08:13 +00005513 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005514 }else if( rc==SQLITE_CANTOPEN ){
5515 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005516 }
5517 }
danielk1977d138dd82008-10-15 16:02:48 +00005518#endif
danielk1977fee2d252007-08-18 10:59:19 +00005519 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005520}
5521
danielk197790949c22007-08-17 16:50:38 +00005522/*
5523** Test the existance of or access permissions of file zPath. The
5524** test performed depends on the value of flags:
5525**
5526** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5527** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5528** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5529**
5530** Otherwise return 0.
5531*/
danielk1977861f7452008-06-05 11:39:11 +00005532static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005533 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5534 const char *zPath, /* Path of the file to examine */
5535 int flags, /* What do we want to learn about the zPath file? */
5536 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005537){
rse25c0d1a2007-09-20 08:38:14 +00005538 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005539 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005540 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005541 switch( flags ){
5542 case SQLITE_ACCESS_EXISTS:
5543 amode = F_OK;
5544 break;
5545 case SQLITE_ACCESS_READWRITE:
5546 amode = W_OK|R_OK;
5547 break;
drh50d3f902007-08-27 21:10:36 +00005548 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005549 amode = R_OK;
5550 break;
5551
5552 default:
5553 assert(!"Invalid flags argument");
5554 }
drh99ab3b12011-03-02 15:09:07 +00005555 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005556 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5557 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005558 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005559 *pResOut = 0;
5560 }
5561 }
danielk1977861f7452008-06-05 11:39:11 +00005562 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005563}
5564
danielk1977b4b47412007-08-17 15:53:36 +00005565
5566/*
5567** Turn a relative pathname into a full pathname. The relative path
5568** is stored as a nul-terminated string in the buffer pointed to by
5569** zPath.
5570**
5571** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5572** (in this case, MAX_PATHNAME bytes). The full-path is written to
5573** this buffer before returning.
5574*/
danielk1977adfb9b02007-09-17 07:02:56 +00005575static int unixFullPathname(
5576 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5577 const char *zPath, /* Possibly relative input path */
5578 int nOut, /* Size of output buffer in bytes */
5579 char *zOut /* Output buffer */
5580){
danielk1977843e65f2007-09-01 16:16:15 +00005581
5582 /* It's odd to simulate an io-error here, but really this is just
5583 ** using the io-error infrastructure to test that SQLite handles this
5584 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005585 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005586 */
5587 SimulateIOError( return SQLITE_ERROR );
5588
drh153c62c2007-08-24 03:51:33 +00005589 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005590 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005591
drh3c7f2dc2007-12-06 13:26:20 +00005592 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005593 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005594 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005595 }else{
5596 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005597 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005598 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005599 }
drhea678832008-12-10 19:26:22 +00005600 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005601 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005602 }
5603 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005604}
5605
drh0ccebe72005-06-07 22:22:50 +00005606
drh761df872006-12-21 01:29:22 +00005607#ifndef SQLITE_OMIT_LOAD_EXTENSION
5608/*
5609** Interfaces for opening a shared library, finding entry points
5610** within the shared library, and closing the shared library.
5611*/
5612#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005613static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5614 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005615 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5616}
danielk197795c8a542007-09-01 06:51:27 +00005617
5618/*
5619** SQLite calls this function immediately after a call to unixDlSym() or
5620** unixDlOpen() fails (returns a null pointer). If a more detailed error
5621** message is available, it is written to zBufOut. If no error message
5622** is available, zBufOut is left unmodified and SQLite uses a default
5623** error message.
5624*/
danielk1977397d65f2008-11-19 11:35:39 +00005625static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005626 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005627 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005628 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005629 zErr = dlerror();
5630 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005631 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005632 }
drh6c7d5c52008-11-21 20:32:33 +00005633 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005634}
drh1875f7a2008-12-08 18:19:17 +00005635static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5636 /*
5637 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5638 ** cast into a pointer to a function. And yet the library dlsym() routine
5639 ** returns a void* which is really a pointer to a function. So how do we
5640 ** use dlsym() with -pedantic-errors?
5641 **
5642 ** Variable x below is defined to be a pointer to a function taking
5643 ** parameters void* and const char* and returning a pointer to a function.
5644 ** We initialize x by assigning it a pointer to the dlsym() function.
5645 ** (That assignment requires a cast.) Then we call the function that
5646 ** x points to.
5647 **
5648 ** This work-around is unlikely to work correctly on any system where
5649 ** you really cannot cast a function pointer into void*. But then, on the
5650 ** other hand, dlsym() will not work on such a system either, so we have
5651 ** not really lost anything.
5652 */
5653 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005654 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005655 x = (void(*(*)(void*,const char*))(void))dlsym;
5656 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005657}
danielk1977397d65f2008-11-19 11:35:39 +00005658static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5659 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005660 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005661}
danielk1977b4b47412007-08-17 15:53:36 +00005662#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5663 #define unixDlOpen 0
5664 #define unixDlError 0
5665 #define unixDlSym 0
5666 #define unixDlClose 0
5667#endif
5668
5669/*
danielk197790949c22007-08-17 16:50:38 +00005670** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005671*/
danielk1977397d65f2008-11-19 11:35:39 +00005672static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5673 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005674 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005675
drhbbd42a62004-05-22 17:41:58 +00005676 /* We have to initialize zBuf to prevent valgrind from reporting
5677 ** errors. The reports issued by valgrind are incorrect - we would
5678 ** prefer that the randomness be increased by making use of the
5679 ** uninitialized space in zBuf - but valgrind errors tend to worry
5680 ** some users. Rather than argue, it seems easier just to initialize
5681 ** the whole array and silence valgrind, even if that means less randomness
5682 ** in the random seed.
5683 **
5684 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005685 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005686 ** tests repeatable.
5687 */
danielk1977b4b47412007-08-17 15:53:36 +00005688 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005689#if !defined(SQLITE_TEST)
5690 {
drhc18b4042012-02-10 03:10:27 +00005691 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005692 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005693 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005694 time_t t;
5695 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005696 memcpy(zBuf, &t, sizeof(t));
5697 pid = getpid();
5698 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005699 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005700 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005701 }else{
drhc18b4042012-02-10 03:10:27 +00005702 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005703 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005704 }
drhbbd42a62004-05-22 17:41:58 +00005705 }
5706#endif
drh72cbd072008-10-14 17:58:38 +00005707 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005708}
5709
danielk1977b4b47412007-08-17 15:53:36 +00005710
drhbbd42a62004-05-22 17:41:58 +00005711/*
5712** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005713** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005714** The return value is the number of microseconds of sleep actually
5715** requested from the underlying operating system, a number which
5716** might be greater than or equal to the argument, but not less
5717** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005718*/
danielk1977397d65f2008-11-19 11:35:39 +00005719static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005720#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005721 struct timespec sp;
5722
5723 sp.tv_sec = microseconds / 1000000;
5724 sp.tv_nsec = (microseconds % 1000000) * 1000;
5725 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005726 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005727 return microseconds;
5728#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005729 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005730 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005731 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005732#else
danielk1977b4b47412007-08-17 15:53:36 +00005733 int seconds = (microseconds+999999)/1000000;
5734 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005735 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005736 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005737#endif
drh88f474a2006-01-02 20:00:12 +00005738}
5739
5740/*
drh6b9d6dd2008-12-03 19:34:47 +00005741** The following variable, if set to a non-zero value, is interpreted as
5742** the number of seconds since 1970 and is used to set the result of
5743** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005744*/
5745#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005746int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005747#endif
5748
5749/*
drhb7e8ea22010-05-03 14:32:30 +00005750** Find the current time (in Universal Coordinated Time). Write into *piNow
5751** the current time and date as a Julian Day number times 86_400_000. In
5752** other words, write into *piNow the number of milliseconds since the Julian
5753** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5754** proleptic Gregorian calendar.
5755**
drh31702252011-10-12 23:13:43 +00005756** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5757** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005758*/
5759static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5760 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005761 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005762#if defined(NO_GETTOD)
5763 time_t t;
5764 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005765 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005766#elif OS_VXWORKS
5767 struct timespec sNow;
5768 clock_gettime(CLOCK_REALTIME, &sNow);
5769 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5770#else
5771 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005772 if( gettimeofday(&sNow, 0)==0 ){
5773 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5774 }else{
5775 rc = SQLITE_ERROR;
5776 }
drhb7e8ea22010-05-03 14:32:30 +00005777#endif
5778
5779#ifdef SQLITE_TEST
5780 if( sqlite3_current_time ){
5781 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5782 }
5783#endif
5784 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005785 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005786}
5787
5788/*
drhbbd42a62004-05-22 17:41:58 +00005789** Find the current time (in Universal Coordinated Time). Write the
5790** current time and date as a Julian Day number into *prNow and
5791** return 0. Return 1 if the time and date cannot be found.
5792*/
danielk1977397d65f2008-11-19 11:35:39 +00005793static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005794 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005795 int rc;
drhff828942010-06-26 21:34:06 +00005796 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005797 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005798 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005799 return rc;
drhbbd42a62004-05-22 17:41:58 +00005800}
danielk1977b4b47412007-08-17 15:53:36 +00005801
drh6b9d6dd2008-12-03 19:34:47 +00005802/*
5803** We added the xGetLastError() method with the intention of providing
5804** better low-level error messages when operating-system problems come up
5805** during SQLite operation. But so far, none of that has been implemented
5806** in the core. So this routine is never called. For now, it is merely
5807** a place-holder.
5808*/
danielk1977397d65f2008-11-19 11:35:39 +00005809static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5810 UNUSED_PARAMETER(NotUsed);
5811 UNUSED_PARAMETER(NotUsed2);
5812 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005813 return 0;
5814}
5815
drhf2424c52010-04-26 00:04:55 +00005816
5817/*
drh734c9862008-11-28 15:37:20 +00005818************************ End of sqlite3_vfs methods ***************************
5819******************************************************************************/
5820
drh715ff302008-12-03 22:32:44 +00005821/******************************************************************************
5822************************** Begin Proxy Locking ********************************
5823**
5824** Proxy locking is a "uber-locking-method" in this sense: It uses the
5825** other locking methods on secondary lock files. Proxy locking is a
5826** meta-layer over top of the primitive locking implemented above. For
5827** this reason, the division that implements of proxy locking is deferred
5828** until late in the file (here) after all of the other I/O methods have
5829** been defined - so that the primitive locking methods are available
5830** as services to help with the implementation of proxy locking.
5831**
5832****
5833**
5834** The default locking schemes in SQLite use byte-range locks on the
5835** database file to coordinate safe, concurrent access by multiple readers
5836** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5837** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5838** as POSIX read & write locks over fixed set of locations (via fsctl),
5839** on AFP and SMB only exclusive byte-range locks are available via fsctl
5840** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5841** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5842** address in the shared range is taken for a SHARED lock, the entire
5843** shared range is taken for an EXCLUSIVE lock):
5844**
drhf2f105d2012-08-20 15:53:54 +00005845** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005846** RESERVED_BYTE 0x40000001
5847** SHARED_RANGE 0x40000002 -> 0x40000200
5848**
5849** This works well on the local file system, but shows a nearly 100x
5850** slowdown in read performance on AFP because the AFP client disables
5851** the read cache when byte-range locks are present. Enabling the read
5852** cache exposes a cache coherency problem that is present on all OS X
5853** supported network file systems. NFS and AFP both observe the
5854** close-to-open semantics for ensuring cache coherency
5855** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5856** address the requirements for concurrent database access by multiple
5857** readers and writers
5858** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5859**
5860** To address the performance and cache coherency issues, proxy file locking
5861** changes the way database access is controlled by limiting access to a
5862** single host at a time and moving file locks off of the database file
5863** and onto a proxy file on the local file system.
5864**
5865**
5866** Using proxy locks
5867** -----------------
5868**
5869** C APIs
5870**
5871** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5872** <proxy_path> | ":auto:");
5873** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5874**
5875**
5876** SQL pragmas
5877**
5878** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5879** PRAGMA [database.]lock_proxy_file
5880**
5881** Specifying ":auto:" means that if there is a conch file with a matching
5882** host ID in it, the proxy path in the conch file will be used, otherwise
5883** a proxy path based on the user's temp dir
5884** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5885** actual proxy file name is generated from the name and path of the
5886** database file. For example:
5887**
5888** For database path "/Users/me/foo.db"
5889** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5890**
5891** Once a lock proxy is configured for a database connection, it can not
5892** be removed, however it may be switched to a different proxy path via
5893** the above APIs (assuming the conch file is not being held by another
5894** connection or process).
5895**
5896**
5897** How proxy locking works
5898** -----------------------
5899**
5900** Proxy file locking relies primarily on two new supporting files:
5901**
5902** * conch file to limit access to the database file to a single host
5903** at a time
5904**
5905** * proxy file to act as a proxy for the advisory locks normally
5906** taken on the database
5907**
5908** The conch file - to use a proxy file, sqlite must first "hold the conch"
5909** by taking an sqlite-style shared lock on the conch file, reading the
5910** contents and comparing the host's unique host ID (see below) and lock
5911** proxy path against the values stored in the conch. The conch file is
5912** stored in the same directory as the database file and the file name
5913** is patterned after the database file name as ".<databasename>-conch".
5914** If the conch file does not exist, or it's contents do not match the
5915** host ID and/or proxy path, then the lock is escalated to an exclusive
5916** lock and the conch file contents is updated with the host ID and proxy
5917** path and the lock is downgraded to a shared lock again. If the conch
5918** is held by another process (with a shared lock), the exclusive lock
5919** will fail and SQLITE_BUSY is returned.
5920**
5921** The proxy file - a single-byte file used for all advisory file locks
5922** normally taken on the database file. This allows for safe sharing
5923** of the database file for multiple readers and writers on the same
5924** host (the conch ensures that they all use the same local lock file).
5925**
drh715ff302008-12-03 22:32:44 +00005926** Requesting the lock proxy does not immediately take the conch, it is
5927** only taken when the first request to lock database file is made.
5928** This matches the semantics of the traditional locking behavior, where
5929** opening a connection to a database file does not take a lock on it.
5930** The shared lock and an open file descriptor are maintained until
5931** the connection to the database is closed.
5932**
5933** The proxy file and the lock file are never deleted so they only need
5934** to be created the first time they are used.
5935**
5936** Configuration options
5937** ---------------------
5938**
5939** SQLITE_PREFER_PROXY_LOCKING
5940**
5941** Database files accessed on non-local file systems are
5942** automatically configured for proxy locking, lock files are
5943** named automatically using the same logic as
5944** PRAGMA lock_proxy_file=":auto:"
5945**
5946** SQLITE_PROXY_DEBUG
5947**
5948** Enables the logging of error messages during host id file
5949** retrieval and creation
5950**
drh715ff302008-12-03 22:32:44 +00005951** LOCKPROXYDIR
5952**
5953** Overrides the default directory used for lock proxy files that
5954** are named automatically via the ":auto:" setting
5955**
5956** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5957**
5958** Permissions to use when creating a directory for storing the
5959** lock proxy files, only used when LOCKPROXYDIR is not set.
5960**
5961**
5962** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5963** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5964** force proxy locking to be used for every database file opened, and 0
5965** will force automatic proxy locking to be disabled for all database
5966** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5967** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5968*/
5969
5970/*
5971** Proxy locking is only available on MacOSX
5972*/
drhd2cb50b2009-01-09 21:41:17 +00005973#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005974
drh715ff302008-12-03 22:32:44 +00005975/*
5976** The proxyLockingContext has the path and file structures for the remote
5977** and local proxy files in it
5978*/
5979typedef struct proxyLockingContext proxyLockingContext;
5980struct proxyLockingContext {
5981 unixFile *conchFile; /* Open conch file */
5982 char *conchFilePath; /* Name of the conch file */
5983 unixFile *lockProxy; /* Open proxy lock file */
5984 char *lockProxyPath; /* Name of the proxy lock file */
5985 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005986 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005987 void *oldLockingContext; /* Original lockingcontext to restore on close */
5988 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5989};
5990
drh7ed97b92010-01-20 13:07:21 +00005991/*
5992** The proxy lock file path for the database at dbPath is written into lPath,
5993** which must point to valid, writable memory large enough for a maxLen length
5994** file path.
drh715ff302008-12-03 22:32:44 +00005995*/
drh715ff302008-12-03 22:32:44 +00005996static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5997 int len;
5998 int dbLen;
5999 int i;
6000
6001#ifdef LOCKPROXYDIR
6002 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6003#else
6004# ifdef _CS_DARWIN_USER_TEMP_DIR
6005 {
drh7ed97b92010-01-20 13:07:21 +00006006 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006007 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6008 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006009 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006010 }
drh7ed97b92010-01-20 13:07:21 +00006011 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006012 }
6013# else
6014 len = strlcpy(lPath, "/tmp/", maxLen);
6015# endif
6016#endif
6017
6018 if( lPath[len-1]!='/' ){
6019 len = strlcat(lPath, "/", maxLen);
6020 }
6021
6022 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006023 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006024 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006025 char c = dbPath[i];
6026 lPath[i+len] = (c=='/')?'_':c;
6027 }
6028 lPath[i+len]='\0';
6029 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006030 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006031 return SQLITE_OK;
6032}
6033
drh7ed97b92010-01-20 13:07:21 +00006034/*
6035 ** Creates the lock file and any missing directories in lockPath
6036 */
6037static int proxyCreateLockPath(const char *lockPath){
6038 int i, len;
6039 char buf[MAXPATHLEN];
6040 int start = 0;
6041
6042 assert(lockPath!=NULL);
6043 /* try to create all the intermediate directories */
6044 len = (int)strlen(lockPath);
6045 buf[0] = lockPath[0];
6046 for( i=1; i<len; i++ ){
6047 if( lockPath[i] == '/' && (i - start > 0) ){
6048 /* only mkdir if leaf dir != "." or "/" or ".." */
6049 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6050 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6051 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006052 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006053 int err=errno;
6054 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006055 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006056 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006057 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006058 return err;
6059 }
6060 }
6061 }
6062 start=i+1;
6063 }
6064 buf[i] = lockPath[i];
6065 }
drh308c2a52010-05-14 11:30:18 +00006066 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006067 return 0;
6068}
6069
drh715ff302008-12-03 22:32:44 +00006070/*
6071** Create a new VFS file descriptor (stored in memory obtained from
6072** sqlite3_malloc) and open the file named "path" in the file descriptor.
6073**
6074** The caller is responsible not only for closing the file descriptor
6075** but also for freeing the memory associated with the file descriptor.
6076*/
drh7ed97b92010-01-20 13:07:21 +00006077static int proxyCreateUnixFile(
6078 const char *path, /* path for the new unixFile */
6079 unixFile **ppFile, /* unixFile created and returned by ref */
6080 int islockfile /* if non zero missing dirs will be created */
6081) {
6082 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006083 unixFile *pNew;
6084 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006085 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006086 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006087 int terrno = 0;
6088 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006089
drh7ed97b92010-01-20 13:07:21 +00006090 /* 1. first try to open/create the file
6091 ** 2. if that fails, and this is a lock file (not-conch), try creating
6092 ** the parent directories and then try again.
6093 ** 3. if that fails, try to open the file read-only
6094 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6095 */
6096 pUnused = findReusableFd(path, openFlags);
6097 if( pUnused ){
6098 fd = pUnused->fd;
6099 }else{
6100 pUnused = sqlite3_malloc(sizeof(*pUnused));
6101 if( !pUnused ){
6102 return SQLITE_NOMEM;
6103 }
6104 }
6105 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006106 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006107 terrno = errno;
6108 if( fd<0 && errno==ENOENT && islockfile ){
6109 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006110 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006111 }
6112 }
6113 }
6114 if( fd<0 ){
6115 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006116 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006117 terrno = errno;
6118 }
6119 if( fd<0 ){
6120 if( islockfile ){
6121 return SQLITE_BUSY;
6122 }
6123 switch (terrno) {
6124 case EACCES:
6125 return SQLITE_PERM;
6126 case EIO:
6127 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6128 default:
drh9978c972010-02-23 17:36:32 +00006129 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006130 }
6131 }
6132
6133 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6134 if( pNew==NULL ){
6135 rc = SQLITE_NOMEM;
6136 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006137 }
6138 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006139 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006140 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006141 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006142 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006143 pUnused->fd = fd;
6144 pUnused->flags = openFlags;
6145 pNew->pUnused = pUnused;
6146
drhc02a43a2012-01-10 23:18:38 +00006147 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006148 if( rc==SQLITE_OK ){
6149 *ppFile = pNew;
6150 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006151 }
drh7ed97b92010-01-20 13:07:21 +00006152end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006153 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006154 sqlite3_free(pNew);
6155 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006156 return rc;
6157}
6158
drh7ed97b92010-01-20 13:07:21 +00006159#ifdef SQLITE_TEST
6160/* simulate multiple hosts by creating unique hostid file paths */
6161int sqlite3_hostid_num = 0;
6162#endif
6163
6164#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6165
drh0ab216a2010-07-02 17:10:40 +00006166/* Not always defined in the headers as it ought to be */
6167extern int gethostuuid(uuid_t id, const struct timespec *wait);
6168
drh7ed97b92010-01-20 13:07:21 +00006169/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6170** bytes of writable memory.
6171*/
6172static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006173 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6174 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006175#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6176 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006177 {
6178 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6179 if( gethostuuid(pHostID, &timeout) ){
6180 int err = errno;
6181 if( pError ){
6182 *pError = err;
6183 }
6184 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006185 }
drh7ed97b92010-01-20 13:07:21 +00006186 }
drh3d4435b2011-08-26 20:55:50 +00006187#else
6188 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006189#endif
drh7ed97b92010-01-20 13:07:21 +00006190#ifdef SQLITE_TEST
6191 /* simulate multiple hosts by creating unique hostid file paths */
6192 if( sqlite3_hostid_num != 0){
6193 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6194 }
6195#endif
6196
6197 return SQLITE_OK;
6198}
6199
6200/* The conch file contains the header, host id and lock file path
6201 */
6202#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6203#define PROXY_HEADERLEN 1 /* conch file header length */
6204#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6205#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6206
6207/*
6208** Takes an open conch file, copies the contents to a new path and then moves
6209** it back. The newly created file's file descriptor is assigned to the
6210** conch file structure and finally the original conch file descriptor is
6211** closed. Returns zero if successful.
6212*/
6213static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6214 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6215 unixFile *conchFile = pCtx->conchFile;
6216 char tPath[MAXPATHLEN];
6217 char buf[PROXY_MAXCONCHLEN];
6218 char *cPath = pCtx->conchFilePath;
6219 size_t readLen = 0;
6220 size_t pathLen = 0;
6221 char errmsg[64] = "";
6222 int fd = -1;
6223 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006224 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006225
6226 /* create a new path by replace the trailing '-conch' with '-break' */
6227 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6228 if( pathLen>MAXPATHLEN || pathLen<6 ||
6229 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006230 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006231 goto end_breaklock;
6232 }
6233 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006234 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006235 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006236 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006237 goto end_breaklock;
6238 }
6239 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006240 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006241 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006242 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006243 goto end_breaklock;
6244 }
drhe562be52011-03-02 18:01:10 +00006245 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006246 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006247 goto end_breaklock;
6248 }
6249 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006250 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006251 goto end_breaklock;
6252 }
6253 rc = 0;
6254 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006255 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006256 conchFile->h = fd;
6257 conchFile->openFlags = O_RDWR | O_CREAT;
6258
6259end_breaklock:
6260 if( rc ){
6261 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006262 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006263 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006264 }
6265 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6266 }
6267 return rc;
6268}
6269
6270/* Take the requested lock on the conch file and break a stale lock if the
6271** host id matches.
6272*/
6273static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6274 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6275 unixFile *conchFile = pCtx->conchFile;
6276 int rc = SQLITE_OK;
6277 int nTries = 0;
6278 struct timespec conchModTime;
6279
drh3d4435b2011-08-26 20:55:50 +00006280 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006281 do {
6282 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6283 nTries ++;
6284 if( rc==SQLITE_BUSY ){
6285 /* If the lock failed (busy):
6286 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6287 * 2nd try: fail if the mod time changed or host id is different, wait
6288 * 10 sec and try again
6289 * 3rd try: break the lock unless the mod time has changed.
6290 */
6291 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006292 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006293 pFile->lastErrno = errno;
6294 return SQLITE_IOERR_LOCK;
6295 }
6296
6297 if( nTries==1 ){
6298 conchModTime = buf.st_mtimespec;
6299 usleep(500000); /* wait 0.5 sec and try the lock again*/
6300 continue;
6301 }
6302
6303 assert( nTries>1 );
6304 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6305 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6306 return SQLITE_BUSY;
6307 }
6308
6309 if( nTries==2 ){
6310 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006311 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006312 if( len<0 ){
6313 pFile->lastErrno = errno;
6314 return SQLITE_IOERR_LOCK;
6315 }
6316 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6317 /* don't break the lock if the host id doesn't match */
6318 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6319 return SQLITE_BUSY;
6320 }
6321 }else{
6322 /* don't break the lock on short read or a version mismatch */
6323 return SQLITE_BUSY;
6324 }
6325 usleep(10000000); /* wait 10 sec and try the lock again */
6326 continue;
6327 }
6328
6329 assert( nTries==3 );
6330 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6331 rc = SQLITE_OK;
6332 if( lockType==EXCLUSIVE_LOCK ){
6333 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6334 }
6335 if( !rc ){
6336 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6337 }
6338 }
6339 }
6340 } while( rc==SQLITE_BUSY && nTries<3 );
6341
6342 return rc;
6343}
6344
6345/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006346** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6347** lockPath means that the lockPath in the conch file will be used if the
6348** host IDs match, or a new lock path will be generated automatically
6349** and written to the conch file.
6350*/
6351static int proxyTakeConch(unixFile *pFile){
6352 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6353
drh7ed97b92010-01-20 13:07:21 +00006354 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006355 return SQLITE_OK;
6356 }else{
6357 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006358 uuid_t myHostID;
6359 int pError = 0;
6360 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006361 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006362 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006363 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006364 int createConch = 0;
6365 int hostIdMatch = 0;
6366 int readLen = 0;
6367 int tryOldLockPath = 0;
6368 int forceNewLockPath = 0;
6369
drh308c2a52010-05-14 11:30:18 +00006370 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6371 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006372
drh7ed97b92010-01-20 13:07:21 +00006373 rc = proxyGetHostID(myHostID, &pError);
6374 if( (rc&0xff)==SQLITE_IOERR ){
6375 pFile->lastErrno = pError;
6376 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006377 }
drh7ed97b92010-01-20 13:07:21 +00006378 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006379 if( rc!=SQLITE_OK ){
6380 goto end_takeconch;
6381 }
drh7ed97b92010-01-20 13:07:21 +00006382 /* read the existing conch file */
6383 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6384 if( readLen<0 ){
6385 /* I/O error: lastErrno set by seekAndRead */
6386 pFile->lastErrno = conchFile->lastErrno;
6387 rc = SQLITE_IOERR_READ;
6388 goto end_takeconch;
6389 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6390 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6391 /* a short read or version format mismatch means we need to create a new
6392 ** conch file.
6393 */
6394 createConch = 1;
6395 }
6396 /* if the host id matches and the lock path already exists in the conch
6397 ** we'll try to use the path there, if we can't open that path, we'll
6398 ** retry with a new auto-generated path
6399 */
6400 do { /* in case we need to try again for an :auto: named lock file */
6401
6402 if( !createConch && !forceNewLockPath ){
6403 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6404 PROXY_HOSTIDLEN);
6405 /* if the conch has data compare the contents */
6406 if( !pCtx->lockProxyPath ){
6407 /* for auto-named local lock file, just check the host ID and we'll
6408 ** use the local lock file path that's already in there
6409 */
6410 if( hostIdMatch ){
6411 size_t pathLen = (readLen - PROXY_PATHINDEX);
6412
6413 if( pathLen>=MAXPATHLEN ){
6414 pathLen=MAXPATHLEN-1;
6415 }
6416 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6417 lockPath[pathLen] = 0;
6418 tempLockPath = lockPath;
6419 tryOldLockPath = 1;
6420 /* create a copy of the lock path if the conch is taken */
6421 goto end_takeconch;
6422 }
6423 }else if( hostIdMatch
6424 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6425 readLen-PROXY_PATHINDEX)
6426 ){
6427 /* conch host and lock path match */
6428 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006429 }
drh7ed97b92010-01-20 13:07:21 +00006430 }
6431
6432 /* if the conch isn't writable and doesn't match, we can't take it */
6433 if( (conchFile->openFlags&O_RDWR) == 0 ){
6434 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006435 goto end_takeconch;
6436 }
drh7ed97b92010-01-20 13:07:21 +00006437
6438 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006439 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006440 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6441 tempLockPath = lockPath;
6442 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006443 }
drh7ed97b92010-01-20 13:07:21 +00006444
6445 /* update conch with host and path (this will fail if other process
6446 ** has a shared lock already), if the host id matches, use the big
6447 ** stick.
drh715ff302008-12-03 22:32:44 +00006448 */
drh7ed97b92010-01-20 13:07:21 +00006449 futimes(conchFile->h, NULL);
6450 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006451 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006452 /* We are trying for an exclusive lock but another thread in this
6453 ** same process is still holding a shared lock. */
6454 rc = SQLITE_BUSY;
6455 } else {
6456 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006457 }
drh715ff302008-12-03 22:32:44 +00006458 }else{
drh7ed97b92010-01-20 13:07:21 +00006459 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006460 }
drh7ed97b92010-01-20 13:07:21 +00006461 if( rc==SQLITE_OK ){
6462 char writeBuffer[PROXY_MAXCONCHLEN];
6463 int writeSize = 0;
6464
6465 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6466 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6467 if( pCtx->lockProxyPath!=NULL ){
6468 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6469 }else{
6470 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6471 }
6472 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006473 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006474 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6475 fsync(conchFile->h);
6476 /* If we created a new conch file (not just updated the contents of a
6477 ** valid conch file), try to match the permissions of the database
6478 */
6479 if( rc==SQLITE_OK && createConch ){
6480 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006481 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006482 if( err==0 ){
6483 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6484 S_IROTH|S_IWOTH);
6485 /* try to match the database file R/W permissions, ignore failure */
6486#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006487 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006488#else
drhff812312011-02-23 13:33:46 +00006489 do{
drhe562be52011-03-02 18:01:10 +00006490 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006491 }while( rc==(-1) && errno==EINTR );
6492 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006493 int code = errno;
6494 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6495 cmode, code, strerror(code));
6496 } else {
6497 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6498 }
6499 }else{
6500 int code = errno;
6501 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6502 err, code, strerror(code));
6503#endif
6504 }
drh715ff302008-12-03 22:32:44 +00006505 }
6506 }
drh7ed97b92010-01-20 13:07:21 +00006507 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6508
6509 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006510 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006511 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006512 int fd;
drh7ed97b92010-01-20 13:07:21 +00006513 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006514 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006515 }
6516 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006517 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006518 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006519 if( fd>=0 ){
6520 pFile->h = fd;
6521 }else{
drh9978c972010-02-23 17:36:32 +00006522 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006523 during locking */
6524 }
6525 }
6526 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6527 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6528 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6529 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6530 /* we couldn't create the proxy lock file with the old lock file path
6531 ** so try again via auto-naming
6532 */
6533 forceNewLockPath = 1;
6534 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006535 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006536 }
6537 }
6538 if( rc==SQLITE_OK ){
6539 /* Need to make a copy of path if we extracted the value
6540 ** from the conch file or the path was allocated on the stack
6541 */
6542 if( tempLockPath ){
6543 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6544 if( !pCtx->lockProxyPath ){
6545 rc = SQLITE_NOMEM;
6546 }
6547 }
6548 }
6549 if( rc==SQLITE_OK ){
6550 pCtx->conchHeld = 1;
6551
6552 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6553 afpLockingContext *afpCtx;
6554 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6555 afpCtx->dbPath = pCtx->lockProxyPath;
6556 }
6557 } else {
6558 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6559 }
drh308c2a52010-05-14 11:30:18 +00006560 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6561 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006562 return rc;
drh308c2a52010-05-14 11:30:18 +00006563 } while (1); /* in case we need to retry the :auto: lock file -
6564 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006565 }
6566}
6567
6568/*
6569** If pFile holds a lock on a conch file, then release that lock.
6570*/
6571static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006572 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006573 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6574 unixFile *conchFile; /* Name of the conch file */
6575
6576 pCtx = (proxyLockingContext *)pFile->lockingContext;
6577 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006578 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006579 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006580 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006581 if( pCtx->conchHeld>0 ){
6582 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6583 }
drh715ff302008-12-03 22:32:44 +00006584 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006585 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6586 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006587 return rc;
6588}
6589
6590/*
6591** Given the name of a database file, compute the name of its conch file.
6592** Store the conch filename in memory obtained from sqlite3_malloc().
6593** Make *pConchPath point to the new name. Return SQLITE_OK on success
6594** or SQLITE_NOMEM if unable to obtain memory.
6595**
6596** The caller is responsible for ensuring that the allocated memory
6597** space is eventually freed.
6598**
6599** *pConchPath is set to NULL if a memory allocation error occurs.
6600*/
6601static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6602 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006603 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006604 char *conchPath; /* buffer in which to construct conch name */
6605
6606 /* Allocate space for the conch filename and initialize the name to
6607 ** the name of the original database file. */
6608 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6609 if( conchPath==0 ){
6610 return SQLITE_NOMEM;
6611 }
6612 memcpy(conchPath, dbPath, len+1);
6613
6614 /* now insert a "." before the last / character */
6615 for( i=(len-1); i>=0; i-- ){
6616 if( conchPath[i]=='/' ){
6617 i++;
6618 break;
6619 }
6620 }
6621 conchPath[i]='.';
6622 while ( i<len ){
6623 conchPath[i+1]=dbPath[i];
6624 i++;
6625 }
6626
6627 /* append the "-conch" suffix to the file */
6628 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006629 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006630
6631 return SQLITE_OK;
6632}
6633
6634
6635/* Takes a fully configured proxy locking-style unix file and switches
6636** the local lock file path
6637*/
6638static int switchLockProxyPath(unixFile *pFile, const char *path) {
6639 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6640 char *oldPath = pCtx->lockProxyPath;
6641 int rc = SQLITE_OK;
6642
drh308c2a52010-05-14 11:30:18 +00006643 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006644 return SQLITE_BUSY;
6645 }
6646
6647 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6648 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6649 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6650 return SQLITE_OK;
6651 }else{
6652 unixFile *lockProxy = pCtx->lockProxy;
6653 pCtx->lockProxy=NULL;
6654 pCtx->conchHeld = 0;
6655 if( lockProxy!=NULL ){
6656 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6657 if( rc ) return rc;
6658 sqlite3_free(lockProxy);
6659 }
6660 sqlite3_free(oldPath);
6661 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6662 }
6663
6664 return rc;
6665}
6666
6667/*
6668** pFile is a file that has been opened by a prior xOpen call. dbPath
6669** is a string buffer at least MAXPATHLEN+1 characters in size.
6670**
6671** This routine find the filename associated with pFile and writes it
6672** int dbPath.
6673*/
6674static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006675#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006676 if( pFile->pMethod == &afpIoMethods ){
6677 /* afp style keeps a reference to the db path in the filePath field
6678 ** of the struct */
drhea678832008-12-10 19:26:22 +00006679 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006680 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6681 } else
drh715ff302008-12-03 22:32:44 +00006682#endif
6683 if( pFile->pMethod == &dotlockIoMethods ){
6684 /* dot lock style uses the locking context to store the dot lock
6685 ** file path */
6686 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6687 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6688 }else{
6689 /* all other styles use the locking context to store the db file path */
6690 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006691 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006692 }
6693 return SQLITE_OK;
6694}
6695
6696/*
6697** Takes an already filled in unix file and alters it so all file locking
6698** will be performed on the local proxy lock file. The following fields
6699** are preserved in the locking context so that they can be restored and
6700** the unix structure properly cleaned up at close time:
6701** ->lockingContext
6702** ->pMethod
6703*/
6704static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6705 proxyLockingContext *pCtx;
6706 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6707 char *lockPath=NULL;
6708 int rc = SQLITE_OK;
6709
drh308c2a52010-05-14 11:30:18 +00006710 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006711 return SQLITE_BUSY;
6712 }
6713 proxyGetDbPathForUnixFile(pFile, dbPath);
6714 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6715 lockPath=NULL;
6716 }else{
6717 lockPath=(char *)path;
6718 }
6719
drh308c2a52010-05-14 11:30:18 +00006720 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6721 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006722
6723 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6724 if( pCtx==0 ){
6725 return SQLITE_NOMEM;
6726 }
6727 memset(pCtx, 0, sizeof(*pCtx));
6728
6729 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6730 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006731 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6732 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6733 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6734 ** (c) the file system is read-only, then enable no-locking access.
6735 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6736 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6737 */
6738 struct statfs fsInfo;
6739 struct stat conchInfo;
6740 int goLockless = 0;
6741
drh99ab3b12011-03-02 15:09:07 +00006742 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006743 int err = errno;
6744 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6745 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6746 }
6747 }
6748 if( goLockless ){
6749 pCtx->conchHeld = -1; /* read only FS/ lockless */
6750 rc = SQLITE_OK;
6751 }
6752 }
drh715ff302008-12-03 22:32:44 +00006753 }
6754 if( rc==SQLITE_OK && lockPath ){
6755 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6756 }
6757
6758 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006759 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6760 if( pCtx->dbPath==NULL ){
6761 rc = SQLITE_NOMEM;
6762 }
6763 }
6764 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006765 /* all memory is allocated, proxys are created and assigned,
6766 ** switch the locking context and pMethod then return.
6767 */
drh715ff302008-12-03 22:32:44 +00006768 pCtx->oldLockingContext = pFile->lockingContext;
6769 pFile->lockingContext = pCtx;
6770 pCtx->pOldMethod = pFile->pMethod;
6771 pFile->pMethod = &proxyIoMethods;
6772 }else{
6773 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006774 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006775 sqlite3_free(pCtx->conchFile);
6776 }
drhd56b1212010-08-11 06:14:15 +00006777 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006778 sqlite3_free(pCtx->conchFilePath);
6779 sqlite3_free(pCtx);
6780 }
drh308c2a52010-05-14 11:30:18 +00006781 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6782 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006783 return rc;
6784}
6785
6786
6787/*
6788** This routine handles sqlite3_file_control() calls that are specific
6789** to proxy locking.
6790*/
6791static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6792 switch( op ){
6793 case SQLITE_GET_LOCKPROXYFILE: {
6794 unixFile *pFile = (unixFile*)id;
6795 if( pFile->pMethod == &proxyIoMethods ){
6796 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6797 proxyTakeConch(pFile);
6798 if( pCtx->lockProxyPath ){
6799 *(const char **)pArg = pCtx->lockProxyPath;
6800 }else{
6801 *(const char **)pArg = ":auto: (not held)";
6802 }
6803 } else {
6804 *(const char **)pArg = NULL;
6805 }
6806 return SQLITE_OK;
6807 }
6808 case SQLITE_SET_LOCKPROXYFILE: {
6809 unixFile *pFile = (unixFile*)id;
6810 int rc = SQLITE_OK;
6811 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6812 if( pArg==NULL || (const char *)pArg==0 ){
6813 if( isProxyStyle ){
6814 /* turn off proxy locking - not supported */
6815 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6816 }else{
6817 /* turn off proxy locking - already off - NOOP */
6818 rc = SQLITE_OK;
6819 }
6820 }else{
6821 const char *proxyPath = (const char *)pArg;
6822 if( isProxyStyle ){
6823 proxyLockingContext *pCtx =
6824 (proxyLockingContext*)pFile->lockingContext;
6825 if( !strcmp(pArg, ":auto:")
6826 || (pCtx->lockProxyPath &&
6827 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6828 ){
6829 rc = SQLITE_OK;
6830 }else{
6831 rc = switchLockProxyPath(pFile, proxyPath);
6832 }
6833 }else{
6834 /* turn on proxy file locking */
6835 rc = proxyTransformUnixFile(pFile, proxyPath);
6836 }
6837 }
6838 return rc;
6839 }
6840 default: {
6841 assert( 0 ); /* The call assures that only valid opcodes are sent */
6842 }
6843 }
6844 /*NOTREACHED*/
6845 return SQLITE_ERROR;
6846}
6847
6848/*
6849** Within this division (the proxying locking implementation) the procedures
6850** above this point are all utilities. The lock-related methods of the
6851** proxy-locking sqlite3_io_method object follow.
6852*/
6853
6854
6855/*
6856** This routine checks if there is a RESERVED lock held on the specified
6857** file by this or any other process. If such a lock is held, set *pResOut
6858** to a non-zero value otherwise *pResOut is set to zero. The return value
6859** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6860*/
6861static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6862 unixFile *pFile = (unixFile*)id;
6863 int rc = proxyTakeConch(pFile);
6864 if( rc==SQLITE_OK ){
6865 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006866 if( pCtx->conchHeld>0 ){
6867 unixFile *proxy = pCtx->lockProxy;
6868 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6869 }else{ /* conchHeld < 0 is lockless */
6870 pResOut=0;
6871 }
drh715ff302008-12-03 22:32:44 +00006872 }
6873 return rc;
6874}
6875
6876/*
drh308c2a52010-05-14 11:30:18 +00006877** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006878** of the following:
6879**
6880** (1) SHARED_LOCK
6881** (2) RESERVED_LOCK
6882** (3) PENDING_LOCK
6883** (4) EXCLUSIVE_LOCK
6884**
6885** Sometimes when requesting one lock state, additional lock states
6886** are inserted in between. The locking might fail on one of the later
6887** transitions leaving the lock state different from what it started but
6888** still short of its goal. The following chart shows the allowed
6889** transitions and the inserted intermediate states:
6890**
6891** UNLOCKED -> SHARED
6892** SHARED -> RESERVED
6893** SHARED -> (PENDING) -> EXCLUSIVE
6894** RESERVED -> (PENDING) -> EXCLUSIVE
6895** PENDING -> EXCLUSIVE
6896**
6897** This routine will only increase a lock. Use the sqlite3OsUnlock()
6898** routine to lower a locking level.
6899*/
drh308c2a52010-05-14 11:30:18 +00006900static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006901 unixFile *pFile = (unixFile*)id;
6902 int rc = proxyTakeConch(pFile);
6903 if( rc==SQLITE_OK ){
6904 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006905 if( pCtx->conchHeld>0 ){
6906 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006907 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6908 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006909 }else{
6910 /* conchHeld < 0 is lockless */
6911 }
drh715ff302008-12-03 22:32:44 +00006912 }
6913 return rc;
6914}
6915
6916
6917/*
drh308c2a52010-05-14 11:30:18 +00006918** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006919** must be either NO_LOCK or SHARED_LOCK.
6920**
6921** If the locking level of the file descriptor is already at or below
6922** the requested locking level, this routine is a no-op.
6923*/
drh308c2a52010-05-14 11:30:18 +00006924static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006925 unixFile *pFile = (unixFile*)id;
6926 int rc = proxyTakeConch(pFile);
6927 if( rc==SQLITE_OK ){
6928 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006929 if( pCtx->conchHeld>0 ){
6930 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006931 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6932 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006933 }else{
6934 /* conchHeld < 0 is lockless */
6935 }
drh715ff302008-12-03 22:32:44 +00006936 }
6937 return rc;
6938}
6939
6940/*
6941** Close a file that uses proxy locks.
6942*/
6943static int proxyClose(sqlite3_file *id) {
6944 if( id ){
6945 unixFile *pFile = (unixFile*)id;
6946 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6947 unixFile *lockProxy = pCtx->lockProxy;
6948 unixFile *conchFile = pCtx->conchFile;
6949 int rc = SQLITE_OK;
6950
6951 if( lockProxy ){
6952 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6953 if( rc ) return rc;
6954 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6955 if( rc ) return rc;
6956 sqlite3_free(lockProxy);
6957 pCtx->lockProxy = 0;
6958 }
6959 if( conchFile ){
6960 if( pCtx->conchHeld ){
6961 rc = proxyReleaseConch(pFile);
6962 if( rc ) return rc;
6963 }
6964 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6965 if( rc ) return rc;
6966 sqlite3_free(conchFile);
6967 }
drhd56b1212010-08-11 06:14:15 +00006968 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006969 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006970 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006971 /* restore the original locking context and pMethod then close it */
6972 pFile->lockingContext = pCtx->oldLockingContext;
6973 pFile->pMethod = pCtx->pOldMethod;
6974 sqlite3_free(pCtx);
6975 return pFile->pMethod->xClose(id);
6976 }
6977 return SQLITE_OK;
6978}
6979
6980
6981
drhd2cb50b2009-01-09 21:41:17 +00006982#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006983/*
6984** The proxy locking style is intended for use with AFP filesystems.
6985** And since AFP is only supported on MacOSX, the proxy locking is also
6986** restricted to MacOSX.
6987**
6988**
6989******************* End of the proxy lock implementation **********************
6990******************************************************************************/
6991
drh734c9862008-11-28 15:37:20 +00006992/*
danielk1977e339d652008-06-28 11:23:00 +00006993** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006994**
6995** This routine registers all VFS implementations for unix-like operating
6996** systems. This routine, and the sqlite3_os_end() routine that follows,
6997** should be the only routines in this file that are visible from other
6998** files.
drh6b9d6dd2008-12-03 19:34:47 +00006999**
7000** This routine is called once during SQLite initialization and by a
7001** single thread. The memory allocation and mutex subsystems have not
7002** necessarily been initialized when this routine is called, and so they
7003** should not be used.
drh153c62c2007-08-24 03:51:33 +00007004*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007005int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007006 /*
7007 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007008 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7009 ** to the "finder" function. (pAppData is a pointer to a pointer because
7010 ** silly C90 rules prohibit a void* from being cast to a function pointer
7011 ** and so we have to go through the intermediate pointer to avoid problems
7012 ** when compiling with -pedantic-errors on GCC.)
7013 **
7014 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007015 ** finder-function. The finder-function returns a pointer to the
7016 ** sqlite_io_methods object that implements the desired locking
7017 ** behaviors. See the division above that contains the IOMETHODS
7018 ** macro for addition information on finder-functions.
7019 **
7020 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7021 ** object. But the "autolockIoFinder" available on MacOSX does a little
7022 ** more than that; it looks at the filesystem type that hosts the
7023 ** database file and tries to choose an locking method appropriate for
7024 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007025 */
drh7708e972008-11-29 00:56:52 +00007026 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007027 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007028 sizeof(unixFile), /* szOsFile */ \
7029 MAX_PATHNAME, /* mxPathname */ \
7030 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007031 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007032 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007033 unixOpen, /* xOpen */ \
7034 unixDelete, /* xDelete */ \
7035 unixAccess, /* xAccess */ \
7036 unixFullPathname, /* xFullPathname */ \
7037 unixDlOpen, /* xDlOpen */ \
7038 unixDlError, /* xDlError */ \
7039 unixDlSym, /* xDlSym */ \
7040 unixDlClose, /* xDlClose */ \
7041 unixRandomness, /* xRandomness */ \
7042 unixSleep, /* xSleep */ \
7043 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007044 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007045 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007046 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007047 unixGetSystemCall, /* xGetSystemCall */ \
7048 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007049 }
7050
drh6b9d6dd2008-12-03 19:34:47 +00007051 /*
7052 ** All default VFSes for unix are contained in the following array.
7053 **
7054 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7055 ** by the SQLite core when the VFS is registered. So the following
7056 ** array cannot be const.
7057 */
danielk1977e339d652008-06-28 11:23:00 +00007058 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007059#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007060 UNIXVFS("unix", autolockIoFinder ),
7061#else
7062 UNIXVFS("unix", posixIoFinder ),
7063#endif
7064 UNIXVFS("unix-none", nolockIoFinder ),
7065 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007066 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007067#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007068 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007069#endif
7070#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007071 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007072#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007073 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007074#endif
chw78a13182009-04-07 05:35:03 +00007075#endif
drhd2cb50b2009-01-09 21:41:17 +00007076#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007077 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007078 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007079 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007080#endif
drh153c62c2007-08-24 03:51:33 +00007081 };
drh6b9d6dd2008-12-03 19:34:47 +00007082 unsigned int i; /* Loop counter */
7083
drh2aa5a002011-04-13 13:42:25 +00007084 /* Double-check that the aSyscall[] array has been constructed
7085 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhe1186ab2013-01-04 20:45:13 +00007086 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00007087
drh6b9d6dd2008-12-03 19:34:47 +00007088 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007089 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007090 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007091 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007092 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007093}
danielk1977e339d652008-06-28 11:23:00 +00007094
7095/*
drh6b9d6dd2008-12-03 19:34:47 +00007096** Shutdown the operating system interface.
7097**
7098** Some operating systems might need to do some cleanup in this routine,
7099** to release dynamically allocated objects. But not on unix.
7100** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007101*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007102int sqlite3_os_end(void){
7103 return SQLITE_OK;
7104}
drhdce8bdb2007-08-16 13:01:44 +00007105
danielk197729bafea2008-06-26 10:41:19 +00007106#endif /* SQLITE_OS_UNIX */