blob: 8f094bdc1985509134fcba539f9444ed3bb5d80b [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 }
drhd3d8c042012-05-29 17:02:40 +00003626#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003627 /* The pager calls this method to signal that it has done
3628 ** a rollback and that the database is therefore unchanged and
3629 ** it hence it is OK for the transaction change counter to be
3630 ** unchanged.
3631 */
3632 case SQLITE_FCNTL_DB_UNCHANGED: {
3633 ((unixFile*)id)->dbUpdate = 0;
3634 return SQLITE_OK;
3635 }
3636#endif
drhd2cb50b2009-01-09 21:41:17 +00003637#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003638 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003639 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003640 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003641 }
drhd2cb50b2009-01-09 21:41:17 +00003642#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003643 }
drh0b52b7d2011-01-26 19:46:22 +00003644 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003645}
3646
3647/*
danielk1977a3d4c882007-03-23 10:08:38 +00003648** Return the sector size in bytes of the underlying block device for
3649** the specified file. This is almost always 512 bytes, but may be
3650** larger for some devices.
3651**
3652** SQLite code assumes this function cannot fail. It also assumes that
3653** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003654** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003655** same for both.
3656*/
drh537dddf2012-10-26 13:46:24 +00003657#ifndef __QNXNTO__
3658static int unixSectorSize(sqlite3_file *NotUsed){
3659 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003660 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003661}
drh537dddf2012-10-26 13:46:24 +00003662#endif
3663
3664/*
3665** The following version of unixSectorSize() is optimized for QNX.
3666*/
3667#ifdef __QNXNTO__
3668#include <sys/dcmd_blk.h>
3669#include <sys/statvfs.h>
3670static int unixSectorSize(sqlite3_file *id){
3671 unixFile *pFile = (unixFile*)id;
3672 if( pFile->sectorSize == 0 ){
3673 struct statvfs fsInfo;
3674
3675 /* Set defaults for non-supported filesystems */
3676 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3677 pFile->deviceCharacteristics = 0;
3678 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3679 return pFile->sectorSize;
3680 }
3681
3682 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3683 pFile->sectorSize = fsInfo.f_bsize;
3684 pFile->deviceCharacteristics =
3685 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3686 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3687 ** the write succeeds */
3688 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3689 ** so it is ordered */
3690 0;
3691 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3692 pFile->sectorSize = fsInfo.f_bsize;
3693 pFile->deviceCharacteristics =
3694 /* etfs cluster size writes are atomic */
3695 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3696 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3697 ** the write succeeds */
3698 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3699 ** so it is ordered */
3700 0;
3701 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3702 pFile->sectorSize = fsInfo.f_bsize;
3703 pFile->deviceCharacteristics =
3704 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3705 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3706 ** the write succeeds */
3707 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3708 ** so it is ordered */
3709 0;
3710 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3711 pFile->sectorSize = fsInfo.f_bsize;
3712 pFile->deviceCharacteristics =
3713 /* full bitset of atomics from max sector size and smaller */
3714 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3715 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3716 ** so it is ordered */
3717 0;
3718 }else if( strstr(fsInfo.f_basetype, "dos") ){
3719 pFile->sectorSize = fsInfo.f_bsize;
3720 pFile->deviceCharacteristics =
3721 /* full bitset of atomics from max sector size and smaller */
3722 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3723 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3724 ** so it is ordered */
3725 0;
3726 }else{
3727 pFile->deviceCharacteristics =
3728 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3729 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3730 ** the write succeeds */
3731 0;
3732 }
3733 }
3734 /* Last chance verification. If the sector size isn't a multiple of 512
3735 ** then it isn't valid.*/
3736 if( pFile->sectorSize % 512 != 0 ){
3737 pFile->deviceCharacteristics = 0;
3738 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3739 }
3740 return pFile->sectorSize;
3741}
3742#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003743
danielk197790949c22007-08-17 16:50:38 +00003744/*
drhf12b3f62011-12-21 14:42:29 +00003745** Return the device characteristics for the file.
3746**
drhcb15f352011-12-23 01:04:17 +00003747** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3748** However, that choice is contraversial since technically the underlying
3749** file system does not always provide powersafe overwrites. (In other
3750** words, after a power-loss event, parts of the file that were never
3751** written might end up being altered.) However, non-PSOW behavior is very,
3752** very rare. And asserting PSOW makes a large reduction in the amount
3753** of required I/O for journaling, since a lot of padding is eliminated.
3754** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3755** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003756*/
drhf12b3f62011-12-21 14:42:29 +00003757static int unixDeviceCharacteristics(sqlite3_file *id){
3758 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003759 int rc = 0;
3760#ifdef __QNXNTO__
3761 if( p->sectorSize==0 ) unixSectorSize(id);
3762 rc = p->deviceCharacteristics;
3763#endif
drhcb15f352011-12-23 01:04:17 +00003764 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003765 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003766 }
drh537dddf2012-10-26 13:46:24 +00003767 return rc;
danielk197762079062007-08-15 17:08:46 +00003768}
3769
drhd9e5c4f2010-05-12 18:01:39 +00003770#ifndef SQLITE_OMIT_WAL
3771
3772
3773/*
drhd91c68f2010-05-14 14:52:25 +00003774** Object used to represent an shared memory buffer.
3775**
3776** When multiple threads all reference the same wal-index, each thread
3777** has its own unixShm object, but they all point to a single instance
3778** of this unixShmNode object. In other words, each wal-index is opened
3779** only once per process.
3780**
3781** Each unixShmNode object is connected to a single unixInodeInfo object.
3782** We could coalesce this object into unixInodeInfo, but that would mean
3783** every open file that does not use shared memory (in other words, most
3784** open files) would have to carry around this extra information. So
3785** the unixInodeInfo object contains a pointer to this unixShmNode object
3786** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003787**
3788** unixMutexHeld() must be true when creating or destroying
3789** this object or while reading or writing the following fields:
3790**
3791** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003792**
3793** The following fields are read-only after the object is created:
3794**
3795** fid
3796** zFilename
3797**
drhd91c68f2010-05-14 14:52:25 +00003798** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003799** unixMutexHeld() is true when reading or writing any other field
3800** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003801*/
drhd91c68f2010-05-14 14:52:25 +00003802struct unixShmNode {
3803 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003804 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003805 char *zFilename; /* Name of the mmapped file */
3806 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003807 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003808 u16 nRegion; /* Size of array apRegion */
3809 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003810 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003811 int nRef; /* Number of unixShm objects pointing to this */
3812 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003813#ifdef SQLITE_DEBUG
3814 u8 exclMask; /* Mask of exclusive locks held */
3815 u8 sharedMask; /* Mask of shared locks held */
3816 u8 nextShmId; /* Next available unixShm.id value */
3817#endif
3818};
3819
3820/*
drhd9e5c4f2010-05-12 18:01:39 +00003821** Structure used internally by this VFS to record the state of an
3822** open shared memory connection.
3823**
drhd91c68f2010-05-14 14:52:25 +00003824** The following fields are initialized when this object is created and
3825** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003826**
drhd91c68f2010-05-14 14:52:25 +00003827** unixShm.pFile
3828** unixShm.id
3829**
3830** All other fields are read/write. The unixShm.pFile->mutex must be held
3831** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003832*/
3833struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003834 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3835 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003836 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003837 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003838 u16 sharedMask; /* Mask of shared locks held */
3839 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003840};
3841
3842/*
drhd9e5c4f2010-05-12 18:01:39 +00003843** Constants used for locking
3844*/
drhbd9676c2010-06-23 17:58:38 +00003845#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003846#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003847
drhd9e5c4f2010-05-12 18:01:39 +00003848/*
drh73b64e42010-05-30 19:55:15 +00003849** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003850**
3851** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3852** otherwise.
3853*/
3854static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003855 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3856 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003857 int ofst, /* First byte of the locking range */
3858 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003859){
3860 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003861 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003862
drhd91c68f2010-05-14 14:52:25 +00003863 /* Access to the unixShmNode object is serialized by the caller */
3864 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003865
drh73b64e42010-05-30 19:55:15 +00003866 /* Shared locks never span more than one byte */
3867 assert( n==1 || lockType!=F_RDLCK );
3868
3869 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003870 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003871
drh3cb93392011-03-12 18:10:44 +00003872 if( pShmNode->h>=0 ){
3873 /* Initialize the locking parameters */
3874 memset(&f, 0, sizeof(f));
3875 f.l_type = lockType;
3876 f.l_whence = SEEK_SET;
3877 f.l_start = ofst;
3878 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003879
drh3cb93392011-03-12 18:10:44 +00003880 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3881 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3882 }
drhd9e5c4f2010-05-12 18:01:39 +00003883
3884 /* Update the global lock state and do debug tracing */
3885#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003886 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003887 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003888 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003889 if( rc==SQLITE_OK ){
3890 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003891 OSTRACE(("unlock %d ok", ofst));
3892 pShmNode->exclMask &= ~mask;
3893 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003894 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003895 OSTRACE(("read-lock %d ok", ofst));
3896 pShmNode->exclMask &= ~mask;
3897 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003898 }else{
3899 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003900 OSTRACE(("write-lock %d ok", ofst));
3901 pShmNode->exclMask |= mask;
3902 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003903 }
3904 }else{
3905 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003906 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003907 }else if( lockType==F_RDLCK ){
3908 OSTRACE(("read-lock failed"));
3909 }else{
3910 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003911 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003912 }
3913 }
drh20e1f082010-05-31 16:10:12 +00003914 OSTRACE((" - afterwards %03x,%03x\n",
3915 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003916 }
drhd9e5c4f2010-05-12 18:01:39 +00003917#endif
3918
3919 return rc;
3920}
3921
drhd9e5c4f2010-05-12 18:01:39 +00003922
3923/*
drhd91c68f2010-05-14 14:52:25 +00003924** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003925**
3926** This is not a VFS shared-memory method; it is a utility function called
3927** by VFS shared-memory methods.
3928*/
drhd91c68f2010-05-14 14:52:25 +00003929static void unixShmPurge(unixFile *pFd){
3930 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003931 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003932 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003933 int i;
drhd91c68f2010-05-14 14:52:25 +00003934 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003935 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003936 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003937 if( p->h>=0 ){
3938 munmap(p->apRegion[i], p->szRegion);
3939 }else{
3940 sqlite3_free(p->apRegion[i]);
3941 }
dan13a3cb82010-06-11 19:04:21 +00003942 }
dan18801912010-06-14 14:07:50 +00003943 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003944 if( p->h>=0 ){
3945 robust_close(pFd, p->h, __LINE__);
3946 p->h = -1;
3947 }
drhd91c68f2010-05-14 14:52:25 +00003948 p->pInode->pShmNode = 0;
3949 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003950 }
3951}
3952
3953/*
danda9fe0c2010-07-13 18:44:03 +00003954** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003955** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003956**
drh7234c6d2010-06-19 15:10:09 +00003957** The file used to implement shared-memory is in the same directory
3958** as the open database file and has the same name as the open database
3959** file with the "-shm" suffix added. For example, if the database file
3960** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003961** for shared memory will be called "/home/user1/config.db-shm".
3962**
3963** Another approach to is to use files in /dev/shm or /dev/tmp or an
3964** some other tmpfs mount. But if a file in a different directory
3965** from the database file is used, then differing access permissions
3966** or a chroot() might cause two different processes on the same
3967** database to end up using different files for shared memory -
3968** meaning that their memory would not really be shared - resulting
3969** in database corruption. Nevertheless, this tmpfs file usage
3970** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3971** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3972** option results in an incompatible build of SQLite; builds of SQLite
3973** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3974** same database file at the same time, database corruption will likely
3975** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3976** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003977**
3978** When opening a new shared-memory file, if no other instances of that
3979** file are currently open, in this process or in other processes, then
3980** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003981**
3982** If the original database file (pDbFd) is using the "unix-excl" VFS
3983** that means that an exclusive lock is held on the database file and
3984** that no other processes are able to read or write the database. In
3985** that case, we do not really need shared memory. No shared memory
3986** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003987*/
danda9fe0c2010-07-13 18:44:03 +00003988static int unixOpenSharedMemory(unixFile *pDbFd){
3989 struct unixShm *p = 0; /* The connection to be opened */
3990 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3991 int rc; /* Result code */
3992 unixInodeInfo *pInode; /* The inode of fd */
3993 char *zShmFilename; /* Name of the file used for SHM */
3994 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00003995
danda9fe0c2010-07-13 18:44:03 +00003996 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00003997 p = sqlite3_malloc( sizeof(*p) );
3998 if( p==0 ) return SQLITE_NOMEM;
3999 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004000 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004001
danda9fe0c2010-07-13 18:44:03 +00004002 /* Check to see if a unixShmNode object already exists. Reuse an existing
4003 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004004 */
4005 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004006 pInode = pDbFd->pInode;
4007 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004008 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004009 struct stat sStat; /* fstat() info for database file */
4010
4011 /* Call fstat() to figure out the permissions on the database file. If
4012 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004013 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004014 */
drh3cb93392011-03-12 18:10:44 +00004015 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004016 rc = SQLITE_IOERR_FSTAT;
4017 goto shm_open_err;
4018 }
4019
drha4ced192010-07-15 18:32:40 +00004020#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004021 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004022#else
drh52bcde02012-01-03 14:50:45 +00004023 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004024#endif
drh7234c6d2010-06-19 15:10:09 +00004025 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004026 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004027 rc = SQLITE_NOMEM;
4028 goto shm_open_err;
4029 }
drh9cb5a0d2012-01-05 21:19:54 +00004030 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004031 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004032#ifdef SQLITE_SHM_DIRECTORY
4033 sqlite3_snprintf(nShmFilename, zShmFilename,
4034 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4035 (u32)sStat.st_ino, (u32)sStat.st_dev);
4036#else
drh7234c6d2010-06-19 15:10:09 +00004037 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004038 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004039#endif
drhd91c68f2010-05-14 14:52:25 +00004040 pShmNode->h = -1;
4041 pDbFd->pInode->pShmNode = pShmNode;
4042 pShmNode->pInode = pDbFd->pInode;
4043 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4044 if( pShmNode->mutex==0 ){
4045 rc = SQLITE_NOMEM;
4046 goto shm_open_err;
4047 }
drhd9e5c4f2010-05-12 18:01:39 +00004048
drh3cb93392011-03-12 18:10:44 +00004049 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004050 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004051 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004052 openFlags = O_RDONLY;
4053 pShmNode->isReadonly = 1;
4054 }
4055 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004056 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004057 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4058 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004059 }
drhac7c3ac2012-02-11 19:23:48 +00004060
4061 /* If this process is running as root, make sure that the SHM file
4062 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004063 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004064 */
drhed466822012-05-31 13:10:49 +00004065 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004066
4067 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004068 ** If not, truncate the file to zero length.
4069 */
4070 rc = SQLITE_OK;
4071 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4072 if( robust_ftruncate(pShmNode->h, 0) ){
4073 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004074 }
4075 }
drh66dfec8b2011-06-01 20:01:49 +00004076 if( rc==SQLITE_OK ){
4077 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4078 }
4079 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004080 }
drhd9e5c4f2010-05-12 18:01:39 +00004081 }
4082
drhd91c68f2010-05-14 14:52:25 +00004083 /* Make the new connection a child of the unixShmNode */
4084 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004085#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004086 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004087#endif
drhd91c68f2010-05-14 14:52:25 +00004088 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004089 pDbFd->pShm = p;
4090 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004091
4092 /* The reference count on pShmNode has already been incremented under
4093 ** the cover of the unixEnterMutex() mutex and the pointer from the
4094 ** new (struct unixShm) object to the pShmNode has been set. All that is
4095 ** left to do is to link the new object into the linked list starting
4096 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4097 ** mutex.
4098 */
4099 sqlite3_mutex_enter(pShmNode->mutex);
4100 p->pNext = pShmNode->pFirst;
4101 pShmNode->pFirst = p;
4102 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004103 return SQLITE_OK;
4104
4105 /* Jump here on any error */
4106shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004107 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004108 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004109 unixLeaveMutex();
4110 return rc;
4111}
4112
4113/*
danda9fe0c2010-07-13 18:44:03 +00004114** This function is called to obtain a pointer to region iRegion of the
4115** shared-memory associated with the database file fd. Shared-memory regions
4116** are numbered starting from zero. Each shared-memory region is szRegion
4117** bytes in size.
4118**
4119** If an error occurs, an error code is returned and *pp is set to NULL.
4120**
4121** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4122** region has not been allocated (by any client, including one running in a
4123** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4124** bExtend is non-zero and the requested shared-memory region has not yet
4125** been allocated, it is allocated by this function.
4126**
4127** If the shared-memory region has already been allocated or is allocated by
4128** this call as described above, then it is mapped into this processes
4129** address space (if it is not already), *pp is set to point to the mapped
4130** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004131*/
danda9fe0c2010-07-13 18:44:03 +00004132static int unixShmMap(
4133 sqlite3_file *fd, /* Handle open on database file */
4134 int iRegion, /* Region to retrieve */
4135 int szRegion, /* Size of regions */
4136 int bExtend, /* True to extend file if necessary */
4137 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004138){
danda9fe0c2010-07-13 18:44:03 +00004139 unixFile *pDbFd = (unixFile*)fd;
4140 unixShm *p;
4141 unixShmNode *pShmNode;
4142 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004143
danda9fe0c2010-07-13 18:44:03 +00004144 /* If the shared-memory file has not yet been opened, open it now. */
4145 if( pDbFd->pShm==0 ){
4146 rc = unixOpenSharedMemory(pDbFd);
4147 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004148 }
drhd9e5c4f2010-05-12 18:01:39 +00004149
danda9fe0c2010-07-13 18:44:03 +00004150 p = pDbFd->pShm;
4151 pShmNode = p->pShmNode;
4152 sqlite3_mutex_enter(pShmNode->mutex);
4153 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004154 assert( pShmNode->pInode==pDbFd->pInode );
4155 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4156 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004157
4158 if( pShmNode->nRegion<=iRegion ){
4159 char **apNew; /* New apRegion[] array */
4160 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4161 struct stat sStat; /* Used by fstat() */
4162
4163 pShmNode->szRegion = szRegion;
4164
drh3cb93392011-03-12 18:10:44 +00004165 if( pShmNode->h>=0 ){
4166 /* The requested region is not mapped into this processes address space.
4167 ** Check to see if it has been allocated (i.e. if the wal-index file is
4168 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004169 */
drh3cb93392011-03-12 18:10:44 +00004170 if( osFstat(pShmNode->h, &sStat) ){
4171 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004172 goto shmpage_out;
4173 }
drh3cb93392011-03-12 18:10:44 +00004174
4175 if( sStat.st_size<nByte ){
4176 /* The requested memory region does not exist. If bExtend is set to
4177 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4178 **
4179 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4180 ** the requested memory region.
4181 */
4182 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004183#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4184 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4185 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4186 pShmNode->zFilename);
4187 goto shmpage_out;
4188 }
4189#else
drh3cb93392011-03-12 18:10:44 +00004190 if( robust_ftruncate(pShmNode->h, nByte) ){
4191 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4192 pShmNode->zFilename);
4193 goto shmpage_out;
4194 }
drh0fbb50e2012-11-13 10:54:12 +00004195#endif
drh3cb93392011-03-12 18:10:44 +00004196 }
danda9fe0c2010-07-13 18:44:03 +00004197 }
4198
4199 /* Map the requested memory region into this processes address space. */
4200 apNew = (char **)sqlite3_realloc(
4201 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4202 );
4203 if( !apNew ){
4204 rc = SQLITE_IOERR_NOMEM;
4205 goto shmpage_out;
4206 }
4207 pShmNode->apRegion = apNew;
4208 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004209 void *pMem;
4210 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004211 pMem = mmap(0, szRegion,
4212 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004213 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004214 );
4215 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004216 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004217 goto shmpage_out;
4218 }
4219 }else{
4220 pMem = sqlite3_malloc(szRegion);
4221 if( pMem==0 ){
4222 rc = SQLITE_NOMEM;
4223 goto shmpage_out;
4224 }
4225 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004226 }
4227 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4228 pShmNode->nRegion++;
4229 }
4230 }
4231
4232shmpage_out:
4233 if( pShmNode->nRegion>iRegion ){
4234 *pp = pShmNode->apRegion[iRegion];
4235 }else{
4236 *pp = 0;
4237 }
drh66dfec8b2011-06-01 20:01:49 +00004238 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004239 sqlite3_mutex_leave(pShmNode->mutex);
4240 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004241}
4242
4243/*
drhd9e5c4f2010-05-12 18:01:39 +00004244** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004245**
4246** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4247** different here than in posix. In xShmLock(), one can go from unlocked
4248** to shared and back or from unlocked to exclusive and back. But one may
4249** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004250*/
4251static int unixShmLock(
4252 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004253 int ofst, /* First lock to acquire or release */
4254 int n, /* Number of locks to acquire or release */
4255 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004256){
drh73b64e42010-05-30 19:55:15 +00004257 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4258 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4259 unixShm *pX; /* For looping over all siblings */
4260 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4261 int rc = SQLITE_OK; /* Result code */
4262 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004263
drhd91c68f2010-05-14 14:52:25 +00004264 assert( pShmNode==pDbFd->pInode->pShmNode );
4265 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004266 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004267 assert( n>=1 );
4268 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4269 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4270 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4271 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4272 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004273 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4274 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004275
drhc99597c2010-05-31 01:41:15 +00004276 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004277 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004278 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004279 if( flags & SQLITE_SHM_UNLOCK ){
4280 u16 allMask = 0; /* Mask of locks held by siblings */
4281
4282 /* See if any siblings hold this same lock */
4283 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4284 if( pX==p ) continue;
4285 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4286 allMask |= pX->sharedMask;
4287 }
4288
4289 /* Unlock the system-level locks */
4290 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004291 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004292 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004293 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004294 }
drh73b64e42010-05-30 19:55:15 +00004295
4296 /* Undo the local locks */
4297 if( rc==SQLITE_OK ){
4298 p->exclMask &= ~mask;
4299 p->sharedMask &= ~mask;
4300 }
4301 }else if( flags & SQLITE_SHM_SHARED ){
4302 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4303
4304 /* Find out which shared locks are already held by sibling connections.
4305 ** If any sibling already holds an exclusive lock, go ahead and return
4306 ** SQLITE_BUSY.
4307 */
4308 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004309 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004310 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004311 break;
4312 }
4313 allShared |= pX->sharedMask;
4314 }
4315
4316 /* Get shared locks at the system level, if necessary */
4317 if( rc==SQLITE_OK ){
4318 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004319 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004320 }else{
drh73b64e42010-05-30 19:55:15 +00004321 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004322 }
drhd9e5c4f2010-05-12 18:01:39 +00004323 }
drh73b64e42010-05-30 19:55:15 +00004324
4325 /* Get the local shared locks */
4326 if( rc==SQLITE_OK ){
4327 p->sharedMask |= mask;
4328 }
4329 }else{
4330 /* Make sure no sibling connections hold locks that will block this
4331 ** lock. If any do, return SQLITE_BUSY right away.
4332 */
4333 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004334 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4335 rc = SQLITE_BUSY;
4336 break;
4337 }
4338 }
4339
4340 /* Get the exclusive locks at the system level. Then if successful
4341 ** also mark the local connection as being locked.
4342 */
4343 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004344 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004345 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004346 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004347 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004348 }
drhd9e5c4f2010-05-12 18:01:39 +00004349 }
4350 }
drhd91c68f2010-05-14 14:52:25 +00004351 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004352 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4353 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004354 return rc;
4355}
4356
drh286a2882010-05-20 23:51:06 +00004357/*
4358** Implement a memory barrier or memory fence on shared memory.
4359**
4360** All loads and stores begun before the barrier must complete before
4361** any load or store begun after the barrier.
4362*/
4363static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004364 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004365){
drhff828942010-06-26 21:34:06 +00004366 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004367 unixEnterMutex();
4368 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004369}
4370
dan18801912010-06-14 14:07:50 +00004371/*
danda9fe0c2010-07-13 18:44:03 +00004372** Close a connection to shared-memory. Delete the underlying
4373** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004374**
4375** If there is no shared memory associated with the connection then this
4376** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004377*/
danda9fe0c2010-07-13 18:44:03 +00004378static int unixShmUnmap(
4379 sqlite3_file *fd, /* The underlying database file */
4380 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004381){
danda9fe0c2010-07-13 18:44:03 +00004382 unixShm *p; /* The connection to be closed */
4383 unixShmNode *pShmNode; /* The underlying shared-memory file */
4384 unixShm **pp; /* For looping over sibling connections */
4385 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004386
danda9fe0c2010-07-13 18:44:03 +00004387 pDbFd = (unixFile*)fd;
4388 p = pDbFd->pShm;
4389 if( p==0 ) return SQLITE_OK;
4390 pShmNode = p->pShmNode;
4391
4392 assert( pShmNode==pDbFd->pInode->pShmNode );
4393 assert( pShmNode->pInode==pDbFd->pInode );
4394
4395 /* Remove connection p from the set of connections associated
4396 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004397 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004398 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4399 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004400
danda9fe0c2010-07-13 18:44:03 +00004401 /* Free the connection p */
4402 sqlite3_free(p);
4403 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004404 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004405
4406 /* If pShmNode->nRef has reached 0, then close the underlying
4407 ** shared-memory file, too */
4408 unixEnterMutex();
4409 assert( pShmNode->nRef>0 );
4410 pShmNode->nRef--;
4411 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004412 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004413 unixShmPurge(pDbFd);
4414 }
4415 unixLeaveMutex();
4416
4417 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004418}
drh286a2882010-05-20 23:51:06 +00004419
danda9fe0c2010-07-13 18:44:03 +00004420
drhd9e5c4f2010-05-12 18:01:39 +00004421#else
drh6b017cc2010-06-14 18:01:46 +00004422# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004423# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004424# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004425# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004426#endif /* #ifndef SQLITE_OMIT_WAL */
4427
drh734c9862008-11-28 15:37:20 +00004428/*
4429** Here ends the implementation of all sqlite3_file methods.
4430**
4431********************** End sqlite3_file Methods *******************************
4432******************************************************************************/
4433
4434/*
drh6b9d6dd2008-12-03 19:34:47 +00004435** This division contains definitions of sqlite3_io_methods objects that
4436** implement various file locking strategies. It also contains definitions
4437** of "finder" functions. A finder-function is used to locate the appropriate
4438** sqlite3_io_methods object for a particular database file. The pAppData
4439** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4440** the correct finder-function for that VFS.
4441**
4442** Most finder functions return a pointer to a fixed sqlite3_io_methods
4443** object. The only interesting finder-function is autolockIoFinder, which
4444** looks at the filesystem type and tries to guess the best locking
4445** strategy from that.
4446**
drh1875f7a2008-12-08 18:19:17 +00004447** For finder-funtion F, two objects are created:
4448**
4449** (1) The real finder-function named "FImpt()".
4450**
dane946c392009-08-22 11:39:46 +00004451** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004452**
4453**
4454** A pointer to the F pointer is used as the pAppData value for VFS
4455** objects. We have to do this instead of letting pAppData point
4456** directly at the finder-function since C90 rules prevent a void*
4457** from be cast into a function pointer.
4458**
drh6b9d6dd2008-12-03 19:34:47 +00004459**
drh7708e972008-11-29 00:56:52 +00004460** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004461**
drh7708e972008-11-29 00:56:52 +00004462** * A constant sqlite3_io_methods object call METHOD that has locking
4463** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4464**
4465** * An I/O method finder function called FINDER that returns a pointer
4466** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004467*/
drhd9e5c4f2010-05-12 18:01:39 +00004468#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004469static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004470 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004471 CLOSE, /* xClose */ \
4472 unixRead, /* xRead */ \
4473 unixWrite, /* xWrite */ \
4474 unixTruncate, /* xTruncate */ \
4475 unixSync, /* xSync */ \
4476 unixFileSize, /* xFileSize */ \
4477 LOCK, /* xLock */ \
4478 UNLOCK, /* xUnlock */ \
4479 CKLOCK, /* xCheckReservedLock */ \
4480 unixFileControl, /* xFileControl */ \
4481 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004482 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004483 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004484 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004485 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004486 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004487}; \
drh0c2694b2009-09-03 16:23:44 +00004488static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4489 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004490 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004491} \
drh0c2694b2009-09-03 16:23:44 +00004492static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004493 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004494
4495/*
4496** Here are all of the sqlite3_io_methods objects for each of the
4497** locking strategies. Functions that return pointers to these methods
4498** are also created.
4499*/
4500IOMETHODS(
4501 posixIoFinder, /* Finder function name */
4502 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004503 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004504 unixClose, /* xClose method */
4505 unixLock, /* xLock method */
4506 unixUnlock, /* xUnlock method */
4507 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004508)
drh7708e972008-11-29 00:56:52 +00004509IOMETHODS(
4510 nolockIoFinder, /* Finder function name */
4511 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004512 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004513 nolockClose, /* xClose method */
4514 nolockLock, /* xLock method */
4515 nolockUnlock, /* xUnlock method */
4516 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004517)
drh7708e972008-11-29 00:56:52 +00004518IOMETHODS(
4519 dotlockIoFinder, /* Finder function name */
4520 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004521 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004522 dotlockClose, /* xClose method */
4523 dotlockLock, /* xLock method */
4524 dotlockUnlock, /* xUnlock method */
4525 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004526)
drh7708e972008-11-29 00:56:52 +00004527
chw78a13182009-04-07 05:35:03 +00004528#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004529IOMETHODS(
4530 flockIoFinder, /* Finder function name */
4531 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004532 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004533 flockClose, /* xClose method */
4534 flockLock, /* xLock method */
4535 flockUnlock, /* xUnlock method */
4536 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004537)
drh7708e972008-11-29 00:56:52 +00004538#endif
4539
drh6c7d5c52008-11-21 20:32:33 +00004540#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004541IOMETHODS(
4542 semIoFinder, /* Finder function name */
4543 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004544 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004545 semClose, /* xClose method */
4546 semLock, /* xLock method */
4547 semUnlock, /* xUnlock method */
4548 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004549)
aswiftaebf4132008-11-21 00:10:35 +00004550#endif
drh7708e972008-11-29 00:56:52 +00004551
drhd2cb50b2009-01-09 21:41:17 +00004552#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004553IOMETHODS(
4554 afpIoFinder, /* Finder function name */
4555 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004556 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004557 afpClose, /* xClose method */
4558 afpLock, /* xLock method */
4559 afpUnlock, /* xUnlock method */
4560 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004561)
drh715ff302008-12-03 22:32:44 +00004562#endif
4563
4564/*
4565** The proxy locking method is a "super-method" in the sense that it
4566** opens secondary file descriptors for the conch and lock files and
4567** it uses proxy, dot-file, AFP, and flock() locking methods on those
4568** secondary files. For this reason, the division that implements
4569** proxy locking is located much further down in the file. But we need
4570** to go ahead and define the sqlite3_io_methods and finder function
4571** for proxy locking here. So we forward declare the I/O methods.
4572*/
drhd2cb50b2009-01-09 21:41:17 +00004573#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004574static int proxyClose(sqlite3_file*);
4575static int proxyLock(sqlite3_file*, int);
4576static int proxyUnlock(sqlite3_file*, int);
4577static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004578IOMETHODS(
4579 proxyIoFinder, /* Finder function name */
4580 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004581 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004582 proxyClose, /* xClose method */
4583 proxyLock, /* xLock method */
4584 proxyUnlock, /* xUnlock method */
4585 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004586)
aswiftaebf4132008-11-21 00:10:35 +00004587#endif
drh7708e972008-11-29 00:56:52 +00004588
drh7ed97b92010-01-20 13:07:21 +00004589/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4590#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4591IOMETHODS(
4592 nfsIoFinder, /* Finder function name */
4593 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004594 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004595 unixClose, /* xClose method */
4596 unixLock, /* xLock method */
4597 nfsUnlock, /* xUnlock method */
4598 unixCheckReservedLock /* xCheckReservedLock method */
4599)
4600#endif
drh7708e972008-11-29 00:56:52 +00004601
drhd2cb50b2009-01-09 21:41:17 +00004602#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004603/*
drh6b9d6dd2008-12-03 19:34:47 +00004604** This "finder" function attempts to determine the best locking strategy
4605** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004606** object that implements that strategy.
4607**
4608** This is for MacOSX only.
4609*/
drh1875f7a2008-12-08 18:19:17 +00004610static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004611 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004612 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004613){
4614 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004615 const char *zFilesystem; /* Filesystem type name */
4616 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004617 } aMap[] = {
4618 { "hfs", &posixIoMethods },
4619 { "ufs", &posixIoMethods },
4620 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004621 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004622 { "webdav", &nolockIoMethods },
4623 { 0, 0 }
4624 };
4625 int i;
4626 struct statfs fsInfo;
4627 struct flock lockInfo;
4628
4629 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004630 /* If filePath==NULL that means we are dealing with a transient file
4631 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004632 return &nolockIoMethods;
4633 }
4634 if( statfs(filePath, &fsInfo) != -1 ){
4635 if( fsInfo.f_flags & MNT_RDONLY ){
4636 return &nolockIoMethods;
4637 }
4638 for(i=0; aMap[i].zFilesystem; i++){
4639 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4640 return aMap[i].pMethods;
4641 }
4642 }
4643 }
4644
4645 /* Default case. Handles, amongst others, "nfs".
4646 ** Test byte-range lock using fcntl(). If the call succeeds,
4647 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004648 */
drh7708e972008-11-29 00:56:52 +00004649 lockInfo.l_len = 1;
4650 lockInfo.l_start = 0;
4651 lockInfo.l_whence = SEEK_SET;
4652 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004653 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004654 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4655 return &nfsIoMethods;
4656 } else {
4657 return &posixIoMethods;
4658 }
drh7708e972008-11-29 00:56:52 +00004659 }else{
4660 return &dotlockIoMethods;
4661 }
4662}
drh0c2694b2009-09-03 16:23:44 +00004663static const sqlite3_io_methods
4664 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004665
drhd2cb50b2009-01-09 21:41:17 +00004666#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004667
chw78a13182009-04-07 05:35:03 +00004668#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4669/*
4670** This "finder" function attempts to determine the best locking strategy
4671** for the database file "filePath". It then returns the sqlite3_io_methods
4672** object that implements that strategy.
4673**
4674** This is for VXWorks only.
4675*/
4676static const sqlite3_io_methods *autolockIoFinderImpl(
4677 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004678 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004679){
4680 struct flock lockInfo;
4681
4682 if( !filePath ){
4683 /* If filePath==NULL that means we are dealing with a transient file
4684 ** that does not need to be locked. */
4685 return &nolockIoMethods;
4686 }
4687
4688 /* Test if fcntl() is supported and use POSIX style locks.
4689 ** Otherwise fall back to the named semaphore method.
4690 */
4691 lockInfo.l_len = 1;
4692 lockInfo.l_start = 0;
4693 lockInfo.l_whence = SEEK_SET;
4694 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004695 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004696 return &posixIoMethods;
4697 }else{
4698 return &semIoMethods;
4699 }
4700}
drh0c2694b2009-09-03 16:23:44 +00004701static const sqlite3_io_methods
4702 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004703
4704#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4705
drh7708e972008-11-29 00:56:52 +00004706/*
4707** An abstract type for a pointer to a IO method finder function:
4708*/
drh0c2694b2009-09-03 16:23:44 +00004709typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004710
aswiftaebf4132008-11-21 00:10:35 +00004711
drh734c9862008-11-28 15:37:20 +00004712/****************************************************************************
4713**************************** sqlite3_vfs methods ****************************
4714**
4715** This division contains the implementation of methods on the
4716** sqlite3_vfs object.
4717*/
4718
danielk1977a3d4c882007-03-23 10:08:38 +00004719/*
danielk1977e339d652008-06-28 11:23:00 +00004720** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004721*/
4722static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004723 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004724 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004725 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004726 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004727 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004728){
drh7708e972008-11-29 00:56:52 +00004729 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004730 unixFile *pNew = (unixFile *)pId;
4731 int rc = SQLITE_OK;
4732
drh8af6c222010-05-14 12:43:01 +00004733 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004734
dan00157392010-10-05 11:33:15 +00004735 /* Usually the path zFilename should not be a relative pathname. The
4736 ** exception is when opening the proxy "conch" file in builds that
4737 ** include the special Apple locking styles.
4738 */
dan00157392010-10-05 11:33:15 +00004739#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004740 assert( zFilename==0 || zFilename[0]=='/'
4741 || pVfs->pAppData==(void*)&autolockIoFinder );
4742#else
4743 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004744#endif
dan00157392010-10-05 11:33:15 +00004745
drhb07028f2011-10-14 21:49:18 +00004746 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004747 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004748
drh308c2a52010-05-14 11:30:18 +00004749 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004750 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004751 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004752 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004753 pNew->ctrlFlags = (u8)ctrlFlags;
4754 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4755 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004756 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004757 }
drh503a6862013-03-01 01:07:17 +00004758 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00004759 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004760 }
drh339eb0b2008-03-07 15:34:11 +00004761
drh6c7d5c52008-11-21 20:32:33 +00004762#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004763 pNew->pId = vxworksFindFileId(zFilename);
4764 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004765 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004766 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004767 }
4768#endif
4769
drhc02a43a2012-01-10 23:18:38 +00004770 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004771 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004772 }else{
drh0c2694b2009-09-03 16:23:44 +00004773 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004774#if SQLITE_ENABLE_LOCKING_STYLE
4775 /* Cache zFilename in the locking context (AFP and dotlock override) for
4776 ** proxyLock activation is possible (remote proxy is based on db name)
4777 ** zFilename remains valid until file is closed, to support */
4778 pNew->lockingContext = (void*)zFilename;
4779#endif
drhda0e7682008-07-30 15:27:54 +00004780 }
danielk1977e339d652008-06-28 11:23:00 +00004781
drh7ed97b92010-01-20 13:07:21 +00004782 if( pLockingStyle == &posixIoMethods
4783#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4784 || pLockingStyle == &nfsIoMethods
4785#endif
4786 ){
drh7708e972008-11-29 00:56:52 +00004787 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004788 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004789 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004790 /* If an error occured in findInodeInfo(), close the file descriptor
4791 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004792 ** in two scenarios:
4793 **
4794 ** (a) A call to fstat() failed.
4795 ** (b) A malloc failed.
4796 **
4797 ** Scenario (b) may only occur if the process is holding no other
4798 ** file descriptors open on the same file. If there were other file
4799 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004800 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004801 ** handle h - as it is guaranteed that no posix locks will be released
4802 ** by doing so.
4803 **
4804 ** If scenario (a) caused the error then things are not so safe. The
4805 ** implicit assumption here is that if fstat() fails, things are in
4806 ** such bad shape that dropping a lock or two doesn't matter much.
4807 */
drh0e9365c2011-03-02 02:08:13 +00004808 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004809 h = -1;
4810 }
drh7708e972008-11-29 00:56:52 +00004811 unixLeaveMutex();
4812 }
danielk1977e339d652008-06-28 11:23:00 +00004813
drhd2cb50b2009-01-09 21:41:17 +00004814#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004815 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004816 /* AFP locking uses the file path so it needs to be included in
4817 ** the afpLockingContext.
4818 */
4819 afpLockingContext *pCtx;
4820 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4821 if( pCtx==0 ){
4822 rc = SQLITE_NOMEM;
4823 }else{
4824 /* NB: zFilename exists and remains valid until the file is closed
4825 ** according to requirement F11141. So we do not need to make a
4826 ** copy of the filename. */
4827 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004828 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004829 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004830 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004831 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004832 if( rc!=SQLITE_OK ){
4833 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004834 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004835 h = -1;
4836 }
drh7708e972008-11-29 00:56:52 +00004837 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004838 }
drh7708e972008-11-29 00:56:52 +00004839 }
4840#endif
danielk1977e339d652008-06-28 11:23:00 +00004841
drh7708e972008-11-29 00:56:52 +00004842 else if( pLockingStyle == &dotlockIoMethods ){
4843 /* Dotfile locking uses the file path so it needs to be included in
4844 ** the dotlockLockingContext
4845 */
4846 char *zLockFile;
4847 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004848 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004849 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004850 zLockFile = (char *)sqlite3_malloc(nFilename);
4851 if( zLockFile==0 ){
4852 rc = SQLITE_NOMEM;
4853 }else{
4854 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004855 }
drh7708e972008-11-29 00:56:52 +00004856 pNew->lockingContext = zLockFile;
4857 }
danielk1977e339d652008-06-28 11:23:00 +00004858
drh6c7d5c52008-11-21 20:32:33 +00004859#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004860 else if( pLockingStyle == &semIoMethods ){
4861 /* Named semaphore locking uses the file path so it needs to be
4862 ** included in the semLockingContext
4863 */
4864 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004865 rc = findInodeInfo(pNew, &pNew->pInode);
4866 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4867 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004868 int n;
drh2238dcc2009-08-27 17:56:20 +00004869 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004870 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004871 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004872 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004873 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4874 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004875 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004876 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004877 }
chw97185482008-11-17 08:05:31 +00004878 }
drh7708e972008-11-29 00:56:52 +00004879 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004880 }
drh7708e972008-11-29 00:56:52 +00004881#endif
aswift5b1a2562008-08-22 00:22:35 +00004882
4883 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004884#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004885 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004886 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004887 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004888 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004889 isDelete = 0;
4890 }
drhc02a43a2012-01-10 23:18:38 +00004891 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004892#endif
danielk1977e339d652008-06-28 11:23:00 +00004893 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004894 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004895 }else{
drh7708e972008-11-29 00:56:52 +00004896 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004897 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004898 }
danielk1977e339d652008-06-28 11:23:00 +00004899 return rc;
drh054889e2005-11-30 03:20:31 +00004900}
drh9c06c952005-11-26 00:25:00 +00004901
danielk1977ad94b582007-08-20 06:44:22 +00004902/*
drh8b3cf822010-06-01 21:02:51 +00004903** Return the name of a directory in which to put temporary files.
4904** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004905*/
drh7234c6d2010-06-19 15:10:09 +00004906static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004907 static const char *azDirs[] = {
4908 0,
aswiftaebf4132008-11-21 00:10:35 +00004909 0,
danielk197717b90b52008-06-06 11:11:25 +00004910 "/var/tmp",
4911 "/usr/tmp",
4912 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004913 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004914 };
drh8b3cf822010-06-01 21:02:51 +00004915 unsigned int i;
4916 struct stat buf;
4917 const char *zDir = 0;
4918
4919 azDirs[0] = sqlite3_temp_directory;
4920 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004921 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004922 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004923 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004924 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004925 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004926 break;
4927 }
4928 return zDir;
4929}
4930
4931/*
4932** Create a temporary file name in zBuf. zBuf must be allocated
4933** by the calling process and must be big enough to hold at least
4934** pVfs->mxPathname bytes.
4935*/
4936static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004937 static const unsigned char zChars[] =
4938 "abcdefghijklmnopqrstuvwxyz"
4939 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4940 "0123456789";
drh41022642008-11-21 00:24:42 +00004941 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004942 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004943
4944 /* It's odd to simulate an io-error here, but really this is just
4945 ** using the io-error infrastructure to test that SQLite handles this
4946 ** function failing.
4947 */
4948 SimulateIOError( return SQLITE_IOERR );
4949
drh7234c6d2010-06-19 15:10:09 +00004950 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004951 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004952
4953 /* Check that the output buffer is large enough for the temporary file
4954 ** name. If it is not, return SQLITE_ERROR.
4955 */
drhc02a43a2012-01-10 23:18:38 +00004956 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004957 return SQLITE_ERROR;
4958 }
4959
4960 do{
drhc02a43a2012-01-10 23:18:38 +00004961 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004962 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004963 sqlite3_randomness(15, &zBuf[j]);
4964 for(i=0; i<15; i++, j++){
4965 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4966 }
4967 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004968 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004969 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004970 return SQLITE_OK;
4971}
4972
drhd2cb50b2009-01-09 21:41:17 +00004973#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004974/*
4975** Routine to transform a unixFile into a proxy-locking unixFile.
4976** Implementation in the proxy-lock division, but used by unixOpen()
4977** if SQLITE_PREFER_PROXY_LOCKING is defined.
4978*/
4979static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004980#endif
drhc66d5b62008-12-03 22:48:32 +00004981
dan08da86a2009-08-21 17:18:03 +00004982/*
4983** Search for an unused file descriptor that was opened on the database
4984** file (not a journal or master-journal file) identified by pathname
4985** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4986** argument to this function.
4987**
4988** Such a file descriptor may exist if a database connection was closed
4989** but the associated file descriptor could not be closed because some
4990** other file descriptor open on the same file is holding a file-lock.
4991** Refer to comments in the unixClose() function and the lengthy comment
4992** describing "Posix Advisory Locking" at the start of this file for
4993** further details. Also, ticket #4018.
4994**
4995** If a suitable file descriptor is found, then it is returned. If no
4996** such file descriptor is located, -1 is returned.
4997*/
dane946c392009-08-22 11:39:46 +00004998static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
4999 UnixUnusedFd *pUnused = 0;
5000
5001 /* Do not search for an unused file descriptor on vxworks. Not because
5002 ** vxworks would not benefit from the change (it might, we're not sure),
5003 ** but because no way to test it is currently available. It is better
5004 ** not to risk breaking vxworks support for the sake of such an obscure
5005 ** feature. */
5006#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005007 struct stat sStat; /* Results of stat() call */
5008
5009 /* A stat() call may fail for various reasons. If this happens, it is
5010 ** almost certain that an open() call on the same path will also fail.
5011 ** For this reason, if an error occurs in the stat() call here, it is
5012 ** ignored and -1 is returned. The caller will try to open a new file
5013 ** descriptor on the same path, fail, and return an error to SQLite.
5014 **
5015 ** Even if a subsequent open() call does succeed, the consequences of
5016 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005017 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005018 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005019
5020 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005021 pInode = inodeList;
5022 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5023 || pInode->fileId.ino!=sStat.st_ino) ){
5024 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005025 }
drh8af6c222010-05-14 12:43:01 +00005026 if( pInode ){
dane946c392009-08-22 11:39:46 +00005027 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005028 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005029 pUnused = *pp;
5030 if( pUnused ){
5031 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005032 }
5033 }
5034 unixLeaveMutex();
5035 }
dane946c392009-08-22 11:39:46 +00005036#endif /* if !OS_VXWORKS */
5037 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005038}
danielk197717b90b52008-06-06 11:11:25 +00005039
5040/*
danddb0ac42010-07-14 14:48:58 +00005041** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005042** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005043** and a value suitable for passing as the third argument to open(2) is
5044** written to *pMode. If an IO error occurs, an SQLite error code is
5045** returned and the value of *pMode is not modified.
5046**
drh8c815d12012-02-13 20:16:37 +00005047** In most cases cases, this routine sets *pMode to 0, which will become
5048** an indication to robust_open() to create the file using
5049** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5050** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005051** this function queries the file-system for the permissions on the
5052** corresponding database file and sets *pMode to this value. Whenever
5053** possible, WAL and journal files are created using the same permissions
5054** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005055**
5056** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5057** original filename is unavailable. But 8_3_NAMES is only used for
5058** FAT filesystems and permissions do not matter there, so just use
5059** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005060*/
5061static int findCreateFileMode(
5062 const char *zPath, /* Path of file (possibly) being created */
5063 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005064 mode_t *pMode, /* OUT: Permissions to open file with */
5065 uid_t *pUid, /* OUT: uid to set on the file */
5066 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005067){
5068 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005069 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005070 *pUid = 0;
5071 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005072 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005073 char zDb[MAX_PATHNAME+1]; /* Database file path */
5074 int nDb; /* Number of valid bytes in zDb */
5075 struct stat sStat; /* Output of stat() on database file */
5076
dana0c989d2010-11-05 18:07:37 +00005077 /* zPath is a path to a WAL or journal file. The following block derives
5078 ** the path to the associated database file from zPath. This block handles
5079 ** the following naming conventions:
5080 **
5081 ** "<path to db>-journal"
5082 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005083 ** "<path to db>-journalNN"
5084 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005085 **
drhd337c5b2011-10-20 18:23:35 +00005086 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005087 ** used by the test_multiplex.c module.
5088 */
5089 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005090#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005091 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005092 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005093#else
5094 while( zPath[nDb]!='-' ){
5095 assert( nDb>0 );
5096 assert( zPath[nDb]!='\n' );
5097 nDb--;
5098 }
5099#endif
danddb0ac42010-07-14 14:48:58 +00005100 memcpy(zDb, zPath, nDb);
5101 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005102
drh58384f12011-07-28 00:14:45 +00005103 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005104 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005105 *pUid = sStat.st_uid;
5106 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005107 }else{
5108 rc = SQLITE_IOERR_FSTAT;
5109 }
5110 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5111 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005112 }
5113 return rc;
5114}
5115
5116/*
danielk1977ad94b582007-08-20 06:44:22 +00005117** Open the file zPath.
5118**
danielk1977b4b47412007-08-17 15:53:36 +00005119** Previously, the SQLite OS layer used three functions in place of this
5120** one:
5121**
5122** sqlite3OsOpenReadWrite();
5123** sqlite3OsOpenReadOnly();
5124** sqlite3OsOpenExclusive();
5125**
5126** These calls correspond to the following combinations of flags:
5127**
5128** ReadWrite() -> (READWRITE | CREATE)
5129** ReadOnly() -> (READONLY)
5130** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5131**
5132** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5133** true, the file was configured to be automatically deleted when the
5134** file handle closed. To achieve the same effect using this new
5135** interface, add the DELETEONCLOSE flag to those specified above for
5136** OpenExclusive().
5137*/
5138static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005139 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5140 const char *zPath, /* Pathname of file to be opened */
5141 sqlite3_file *pFile, /* The file descriptor to be filled in */
5142 int flags, /* Input flags to control the opening */
5143 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005144){
dan08da86a2009-08-21 17:18:03 +00005145 unixFile *p = (unixFile *)pFile;
5146 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005147 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005148 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005149 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005150 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005151 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005152
5153 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5154 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5155 int isCreate = (flags & SQLITE_OPEN_CREATE);
5156 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5157 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005158#if SQLITE_ENABLE_LOCKING_STYLE
5159 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5160#endif
drh3d4435b2011-08-26 20:55:50 +00005161#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5162 struct statfs fsInfo;
5163#endif
danielk1977b4b47412007-08-17 15:53:36 +00005164
danielk1977fee2d252007-08-18 10:59:19 +00005165 /* If creating a master or main-file journal, this function will open
5166 ** a file-descriptor on the directory too. The first time unixSync()
5167 ** is called the directory file descriptor will be fsync()ed and close()d.
5168 */
drh0059eae2011-08-08 23:48:40 +00005169 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005170 eType==SQLITE_OPEN_MASTER_JOURNAL
5171 || eType==SQLITE_OPEN_MAIN_JOURNAL
5172 || eType==SQLITE_OPEN_WAL
5173 ));
danielk1977fee2d252007-08-18 10:59:19 +00005174
danielk197717b90b52008-06-06 11:11:25 +00005175 /* If argument zPath is a NULL pointer, this function is required to open
5176 ** a temporary file. Use this buffer to store the file name in.
5177 */
drhc02a43a2012-01-10 23:18:38 +00005178 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005179 const char *zName = zPath;
5180
danielk1977fee2d252007-08-18 10:59:19 +00005181 /* Check the following statements are true:
5182 **
5183 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5184 ** (b) if CREATE is set, then READWRITE must also be set, and
5185 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005186 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005187 */
danielk1977b4b47412007-08-17 15:53:36 +00005188 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005189 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005190 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005191 assert(isDelete==0 || isCreate);
5192
danddb0ac42010-07-14 14:48:58 +00005193 /* The main DB, main journal, WAL file and master journal are never
5194 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005195 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5196 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5197 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005198 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005199
danielk1977fee2d252007-08-18 10:59:19 +00005200 /* Assert that the upper layer has set one of the "file-type" flags. */
5201 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5202 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5203 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005204 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005205 );
5206
dan08da86a2009-08-21 17:18:03 +00005207 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005208
dan08da86a2009-08-21 17:18:03 +00005209 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005210 UnixUnusedFd *pUnused;
5211 pUnused = findReusableFd(zName, flags);
5212 if( pUnused ){
5213 fd = pUnused->fd;
5214 }else{
dan6aa657f2009-08-24 18:57:58 +00005215 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005216 if( !pUnused ){
5217 return SQLITE_NOMEM;
5218 }
5219 }
5220 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005221
5222 /* Database filenames are double-zero terminated if they are not
5223 ** URIs with parameters. Hence, they can always be passed into
5224 ** sqlite3_uri_parameter(). */
5225 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5226
dan08da86a2009-08-21 17:18:03 +00005227 }else if( !zName ){
5228 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005229 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005230 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005231 if( rc!=SQLITE_OK ){
5232 return rc;
5233 }
5234 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005235
5236 /* Generated temporary filenames are always double-zero terminated
5237 ** for use by sqlite3_uri_parameter(). */
5238 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005239 }
5240
dan08da86a2009-08-21 17:18:03 +00005241 /* Determine the value of the flags parameter passed to POSIX function
5242 ** open(). These must be calculated even if open() is not called, as
5243 ** they may be stored as part of the file handle and used by the
5244 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005245 if( isReadonly ) openFlags |= O_RDONLY;
5246 if( isReadWrite ) openFlags |= O_RDWR;
5247 if( isCreate ) openFlags |= O_CREAT;
5248 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5249 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005250
danielk1977b4b47412007-08-17 15:53:36 +00005251 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005252 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005253 uid_t uid; /* Userid for the file */
5254 gid_t gid; /* Groupid for the file */
5255 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005256 if( rc!=SQLITE_OK ){
5257 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005258 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005259 return rc;
5260 }
drhad4f1e52011-03-04 15:43:57 +00005261 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005262 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005263 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5264 /* Failed to open the file for read/write access. Try read-only. */
5265 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005266 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005267 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005268 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005269 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005270 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005271 }
5272 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005273 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005274 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005275 }
drhac7c3ac2012-02-11 19:23:48 +00005276
5277 /* If this process is running as root and if creating a new rollback
5278 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005279 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005280 */
5281 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005282 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005283 }
danielk1977b4b47412007-08-17 15:53:36 +00005284 }
dan08da86a2009-08-21 17:18:03 +00005285 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005286 if( pOutFlags ){
5287 *pOutFlags = flags;
5288 }
5289
dane946c392009-08-22 11:39:46 +00005290 if( p->pUnused ){
5291 p->pUnused->fd = fd;
5292 p->pUnused->flags = flags;
5293 }
5294
danielk1977b4b47412007-08-17 15:53:36 +00005295 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005296#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005297 zPath = zName;
5298#else
drh036ac7f2011-08-08 23:18:05 +00005299 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005300#endif
danielk1977b4b47412007-08-17 15:53:36 +00005301 }
drh41022642008-11-21 00:24:42 +00005302#if SQLITE_ENABLE_LOCKING_STYLE
5303 else{
dan08da86a2009-08-21 17:18:03 +00005304 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005305 }
5306#endif
5307
drhda0e7682008-07-30 15:27:54 +00005308 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005309
drh7ed97b92010-01-20 13:07:21 +00005310
5311#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005312 if( fstatfs(fd, &fsInfo) == -1 ){
5313 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005314 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005315 return SQLITE_IOERR_ACCESS;
5316 }
5317 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5318 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5319 }
5320#endif
drhc02a43a2012-01-10 23:18:38 +00005321
5322 /* Set up appropriate ctrlFlags */
5323 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5324 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5325 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5326 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5327 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5328
drh7ed97b92010-01-20 13:07:21 +00005329#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005330#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005331 isAutoProxy = 1;
5332#endif
5333 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005334 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5335 int useProxy = 0;
5336
dan08da86a2009-08-21 17:18:03 +00005337 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5338 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005339 if( envforce!=NULL ){
5340 useProxy = atoi(envforce)>0;
5341 }else{
aswiftaebf4132008-11-21 00:10:35 +00005342 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005343 /* In theory, the close(fd) call is sub-optimal. If the file opened
5344 ** with fd is a database file, and there are other connections open
5345 ** on that file that are currently holding advisory locks on it,
5346 ** then the call to close() will cancel those locks. In practice,
5347 ** we're assuming that statfs() doesn't fail very often. At least
5348 ** not while other file descriptors opened by the same process on
5349 ** the same file are working. */
5350 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005351 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005352 rc = SQLITE_IOERR_ACCESS;
5353 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005354 }
5355 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5356 }
5357 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005358 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005359 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005360 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005361 if( rc!=SQLITE_OK ){
5362 /* Use unixClose to clean up the resources added in fillInUnixFile
5363 ** and clear all the structure's references. Specifically,
5364 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5365 */
5366 unixClose(pFile);
5367 return rc;
5368 }
aswiftaebf4132008-11-21 00:10:35 +00005369 }
dane946c392009-08-22 11:39:46 +00005370 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005371 }
5372 }
5373#endif
5374
drhc02a43a2012-01-10 23:18:38 +00005375 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5376
dane946c392009-08-22 11:39:46 +00005377open_finished:
5378 if( rc!=SQLITE_OK ){
5379 sqlite3_free(p->pUnused);
5380 }
5381 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005382}
5383
dane946c392009-08-22 11:39:46 +00005384
danielk1977b4b47412007-08-17 15:53:36 +00005385/*
danielk1977fee2d252007-08-18 10:59:19 +00005386** Delete the file at zPath. If the dirSync argument is true, fsync()
5387** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005388*/
drh6b9d6dd2008-12-03 19:34:47 +00005389static int unixDelete(
5390 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5391 const char *zPath, /* Name of file to be deleted */
5392 int dirSync /* If true, fsync() directory after deleting file */
5393){
danielk1977fee2d252007-08-18 10:59:19 +00005394 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005395 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005396 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005397 if( osUnlink(zPath)==(-1) ){
5398 if( errno==ENOENT ){
5399 rc = SQLITE_IOERR_DELETE_NOENT;
5400 }else{
drhb4308162012-11-09 21:40:02 +00005401 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005402 }
drhb4308162012-11-09 21:40:02 +00005403 return rc;
drh5d4feff2010-07-14 01:45:22 +00005404 }
danielk1977d39fa702008-10-16 13:27:40 +00005405#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005406 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005407 int fd;
drh90315a22011-08-10 01:52:12 +00005408 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005409 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005410#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005411 if( fsync(fd)==-1 )
5412#else
5413 if( fsync(fd) )
5414#endif
5415 {
dane18d4952011-02-21 11:46:24 +00005416 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005417 }
drh0e9365c2011-03-02 02:08:13 +00005418 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005419 }else if( rc==SQLITE_CANTOPEN ){
5420 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005421 }
5422 }
danielk1977d138dd82008-10-15 16:02:48 +00005423#endif
danielk1977fee2d252007-08-18 10:59:19 +00005424 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005425}
5426
danielk197790949c22007-08-17 16:50:38 +00005427/*
5428** Test the existance of or access permissions of file zPath. The
5429** test performed depends on the value of flags:
5430**
5431** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5432** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5433** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5434**
5435** Otherwise return 0.
5436*/
danielk1977861f7452008-06-05 11:39:11 +00005437static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005438 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5439 const char *zPath, /* Path of the file to examine */
5440 int flags, /* What do we want to learn about the zPath file? */
5441 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005442){
rse25c0d1a2007-09-20 08:38:14 +00005443 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005444 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005445 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005446 switch( flags ){
5447 case SQLITE_ACCESS_EXISTS:
5448 amode = F_OK;
5449 break;
5450 case SQLITE_ACCESS_READWRITE:
5451 amode = W_OK|R_OK;
5452 break;
drh50d3f902007-08-27 21:10:36 +00005453 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005454 amode = R_OK;
5455 break;
5456
5457 default:
5458 assert(!"Invalid flags argument");
5459 }
drh99ab3b12011-03-02 15:09:07 +00005460 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005461 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5462 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005463 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005464 *pResOut = 0;
5465 }
5466 }
danielk1977861f7452008-06-05 11:39:11 +00005467 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005468}
5469
danielk1977b4b47412007-08-17 15:53:36 +00005470
5471/*
5472** Turn a relative pathname into a full pathname. The relative path
5473** is stored as a nul-terminated string in the buffer pointed to by
5474** zPath.
5475**
5476** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5477** (in this case, MAX_PATHNAME bytes). The full-path is written to
5478** this buffer before returning.
5479*/
danielk1977adfb9b02007-09-17 07:02:56 +00005480static int unixFullPathname(
5481 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5482 const char *zPath, /* Possibly relative input path */
5483 int nOut, /* Size of output buffer in bytes */
5484 char *zOut /* Output buffer */
5485){
danielk1977843e65f2007-09-01 16:16:15 +00005486
5487 /* It's odd to simulate an io-error here, but really this is just
5488 ** using the io-error infrastructure to test that SQLite handles this
5489 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005490 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005491 */
5492 SimulateIOError( return SQLITE_ERROR );
5493
drh153c62c2007-08-24 03:51:33 +00005494 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005495 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005496
drh3c7f2dc2007-12-06 13:26:20 +00005497 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005498 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005499 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005500 }else{
5501 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005502 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005503 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005504 }
drhea678832008-12-10 19:26:22 +00005505 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005506 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005507 }
5508 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005509}
5510
drh0ccebe72005-06-07 22:22:50 +00005511
drh761df872006-12-21 01:29:22 +00005512#ifndef SQLITE_OMIT_LOAD_EXTENSION
5513/*
5514** Interfaces for opening a shared library, finding entry points
5515** within the shared library, and closing the shared library.
5516*/
5517#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005518static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5519 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005520 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5521}
danielk197795c8a542007-09-01 06:51:27 +00005522
5523/*
5524** SQLite calls this function immediately after a call to unixDlSym() or
5525** unixDlOpen() fails (returns a null pointer). If a more detailed error
5526** message is available, it is written to zBufOut. If no error message
5527** is available, zBufOut is left unmodified and SQLite uses a default
5528** error message.
5529*/
danielk1977397d65f2008-11-19 11:35:39 +00005530static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005531 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005532 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005533 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005534 zErr = dlerror();
5535 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005536 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005537 }
drh6c7d5c52008-11-21 20:32:33 +00005538 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005539}
drh1875f7a2008-12-08 18:19:17 +00005540static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5541 /*
5542 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5543 ** cast into a pointer to a function. And yet the library dlsym() routine
5544 ** returns a void* which is really a pointer to a function. So how do we
5545 ** use dlsym() with -pedantic-errors?
5546 **
5547 ** Variable x below is defined to be a pointer to a function taking
5548 ** parameters void* and const char* and returning a pointer to a function.
5549 ** We initialize x by assigning it a pointer to the dlsym() function.
5550 ** (That assignment requires a cast.) Then we call the function that
5551 ** x points to.
5552 **
5553 ** This work-around is unlikely to work correctly on any system where
5554 ** you really cannot cast a function pointer into void*. But then, on the
5555 ** other hand, dlsym() will not work on such a system either, so we have
5556 ** not really lost anything.
5557 */
5558 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005559 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005560 x = (void(*(*)(void*,const char*))(void))dlsym;
5561 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005562}
danielk1977397d65f2008-11-19 11:35:39 +00005563static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5564 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005565 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005566}
danielk1977b4b47412007-08-17 15:53:36 +00005567#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5568 #define unixDlOpen 0
5569 #define unixDlError 0
5570 #define unixDlSym 0
5571 #define unixDlClose 0
5572#endif
5573
5574/*
danielk197790949c22007-08-17 16:50:38 +00005575** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005576*/
danielk1977397d65f2008-11-19 11:35:39 +00005577static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5578 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005579 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005580
drhbbd42a62004-05-22 17:41:58 +00005581 /* We have to initialize zBuf to prevent valgrind from reporting
5582 ** errors. The reports issued by valgrind are incorrect - we would
5583 ** prefer that the randomness be increased by making use of the
5584 ** uninitialized space in zBuf - but valgrind errors tend to worry
5585 ** some users. Rather than argue, it seems easier just to initialize
5586 ** the whole array and silence valgrind, even if that means less randomness
5587 ** in the random seed.
5588 **
5589 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005590 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005591 ** tests repeatable.
5592 */
danielk1977b4b47412007-08-17 15:53:36 +00005593 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005594#if !defined(SQLITE_TEST)
5595 {
drhc18b4042012-02-10 03:10:27 +00005596 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005597 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005598 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005599 time_t t;
5600 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005601 memcpy(zBuf, &t, sizeof(t));
5602 pid = getpid();
5603 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005604 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005605 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005606 }else{
drhc18b4042012-02-10 03:10:27 +00005607 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005608 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005609 }
drhbbd42a62004-05-22 17:41:58 +00005610 }
5611#endif
drh72cbd072008-10-14 17:58:38 +00005612 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005613}
5614
danielk1977b4b47412007-08-17 15:53:36 +00005615
drhbbd42a62004-05-22 17:41:58 +00005616/*
5617** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005618** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005619** The return value is the number of microseconds of sleep actually
5620** requested from the underlying operating system, a number which
5621** might be greater than or equal to the argument, but not less
5622** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005623*/
danielk1977397d65f2008-11-19 11:35:39 +00005624static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005625#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005626 struct timespec sp;
5627
5628 sp.tv_sec = microseconds / 1000000;
5629 sp.tv_nsec = (microseconds % 1000000) * 1000;
5630 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005631 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005632 return microseconds;
5633#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005634 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005635 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005636 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005637#else
danielk1977b4b47412007-08-17 15:53:36 +00005638 int seconds = (microseconds+999999)/1000000;
5639 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005640 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005641 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005642#endif
drh88f474a2006-01-02 20:00:12 +00005643}
5644
5645/*
drh6b9d6dd2008-12-03 19:34:47 +00005646** The following variable, if set to a non-zero value, is interpreted as
5647** the number of seconds since 1970 and is used to set the result of
5648** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005649*/
5650#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005651int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005652#endif
5653
5654/*
drhb7e8ea22010-05-03 14:32:30 +00005655** Find the current time (in Universal Coordinated Time). Write into *piNow
5656** the current time and date as a Julian Day number times 86_400_000. In
5657** other words, write into *piNow the number of milliseconds since the Julian
5658** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5659** proleptic Gregorian calendar.
5660**
drh31702252011-10-12 23:13:43 +00005661** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5662** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005663*/
5664static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5665 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005666 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005667#if defined(NO_GETTOD)
5668 time_t t;
5669 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005670 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005671#elif OS_VXWORKS
5672 struct timespec sNow;
5673 clock_gettime(CLOCK_REALTIME, &sNow);
5674 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5675#else
5676 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005677 if( gettimeofday(&sNow, 0)==0 ){
5678 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5679 }else{
5680 rc = SQLITE_ERROR;
5681 }
drhb7e8ea22010-05-03 14:32:30 +00005682#endif
5683
5684#ifdef SQLITE_TEST
5685 if( sqlite3_current_time ){
5686 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5687 }
5688#endif
5689 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005690 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005691}
5692
5693/*
drhbbd42a62004-05-22 17:41:58 +00005694** Find the current time (in Universal Coordinated Time). Write the
5695** current time and date as a Julian Day number into *prNow and
5696** return 0. Return 1 if the time and date cannot be found.
5697*/
danielk1977397d65f2008-11-19 11:35:39 +00005698static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005699 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005700 int rc;
drhff828942010-06-26 21:34:06 +00005701 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005702 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005703 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005704 return rc;
drhbbd42a62004-05-22 17:41:58 +00005705}
danielk1977b4b47412007-08-17 15:53:36 +00005706
drh6b9d6dd2008-12-03 19:34:47 +00005707/*
5708** We added the xGetLastError() method with the intention of providing
5709** better low-level error messages when operating-system problems come up
5710** during SQLite operation. But so far, none of that has been implemented
5711** in the core. So this routine is never called. For now, it is merely
5712** a place-holder.
5713*/
danielk1977397d65f2008-11-19 11:35:39 +00005714static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5715 UNUSED_PARAMETER(NotUsed);
5716 UNUSED_PARAMETER(NotUsed2);
5717 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005718 return 0;
5719}
5720
drhf2424c52010-04-26 00:04:55 +00005721
5722/*
drh734c9862008-11-28 15:37:20 +00005723************************ End of sqlite3_vfs methods ***************************
5724******************************************************************************/
5725
drh715ff302008-12-03 22:32:44 +00005726/******************************************************************************
5727************************** Begin Proxy Locking ********************************
5728**
5729** Proxy locking is a "uber-locking-method" in this sense: It uses the
5730** other locking methods on secondary lock files. Proxy locking is a
5731** meta-layer over top of the primitive locking implemented above. For
5732** this reason, the division that implements of proxy locking is deferred
5733** until late in the file (here) after all of the other I/O methods have
5734** been defined - so that the primitive locking methods are available
5735** as services to help with the implementation of proxy locking.
5736**
5737****
5738**
5739** The default locking schemes in SQLite use byte-range locks on the
5740** database file to coordinate safe, concurrent access by multiple readers
5741** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5742** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5743** as POSIX read & write locks over fixed set of locations (via fsctl),
5744** on AFP and SMB only exclusive byte-range locks are available via fsctl
5745** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5746** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5747** address in the shared range is taken for a SHARED lock, the entire
5748** shared range is taken for an EXCLUSIVE lock):
5749**
drhf2f105d2012-08-20 15:53:54 +00005750** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005751** RESERVED_BYTE 0x40000001
5752** SHARED_RANGE 0x40000002 -> 0x40000200
5753**
5754** This works well on the local file system, but shows a nearly 100x
5755** slowdown in read performance on AFP because the AFP client disables
5756** the read cache when byte-range locks are present. Enabling the read
5757** cache exposes a cache coherency problem that is present on all OS X
5758** supported network file systems. NFS and AFP both observe the
5759** close-to-open semantics for ensuring cache coherency
5760** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5761** address the requirements for concurrent database access by multiple
5762** readers and writers
5763** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5764**
5765** To address the performance and cache coherency issues, proxy file locking
5766** changes the way database access is controlled by limiting access to a
5767** single host at a time and moving file locks off of the database file
5768** and onto a proxy file on the local file system.
5769**
5770**
5771** Using proxy locks
5772** -----------------
5773**
5774** C APIs
5775**
5776** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5777** <proxy_path> | ":auto:");
5778** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5779**
5780**
5781** SQL pragmas
5782**
5783** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5784** PRAGMA [database.]lock_proxy_file
5785**
5786** Specifying ":auto:" means that if there is a conch file with a matching
5787** host ID in it, the proxy path in the conch file will be used, otherwise
5788** a proxy path based on the user's temp dir
5789** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5790** actual proxy file name is generated from the name and path of the
5791** database file. For example:
5792**
5793** For database path "/Users/me/foo.db"
5794** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5795**
5796** Once a lock proxy is configured for a database connection, it can not
5797** be removed, however it may be switched to a different proxy path via
5798** the above APIs (assuming the conch file is not being held by another
5799** connection or process).
5800**
5801**
5802** How proxy locking works
5803** -----------------------
5804**
5805** Proxy file locking relies primarily on two new supporting files:
5806**
5807** * conch file to limit access to the database file to a single host
5808** at a time
5809**
5810** * proxy file to act as a proxy for the advisory locks normally
5811** taken on the database
5812**
5813** The conch file - to use a proxy file, sqlite must first "hold the conch"
5814** by taking an sqlite-style shared lock on the conch file, reading the
5815** contents and comparing the host's unique host ID (see below) and lock
5816** proxy path against the values stored in the conch. The conch file is
5817** stored in the same directory as the database file and the file name
5818** is patterned after the database file name as ".<databasename>-conch".
5819** If the conch file does not exist, or it's contents do not match the
5820** host ID and/or proxy path, then the lock is escalated to an exclusive
5821** lock and the conch file contents is updated with the host ID and proxy
5822** path and the lock is downgraded to a shared lock again. If the conch
5823** is held by another process (with a shared lock), the exclusive lock
5824** will fail and SQLITE_BUSY is returned.
5825**
5826** The proxy file - a single-byte file used for all advisory file locks
5827** normally taken on the database file. This allows for safe sharing
5828** of the database file for multiple readers and writers on the same
5829** host (the conch ensures that they all use the same local lock file).
5830**
drh715ff302008-12-03 22:32:44 +00005831** Requesting the lock proxy does not immediately take the conch, it is
5832** only taken when the first request to lock database file is made.
5833** This matches the semantics of the traditional locking behavior, where
5834** opening a connection to a database file does not take a lock on it.
5835** The shared lock and an open file descriptor are maintained until
5836** the connection to the database is closed.
5837**
5838** The proxy file and the lock file are never deleted so they only need
5839** to be created the first time they are used.
5840**
5841** Configuration options
5842** ---------------------
5843**
5844** SQLITE_PREFER_PROXY_LOCKING
5845**
5846** Database files accessed on non-local file systems are
5847** automatically configured for proxy locking, lock files are
5848** named automatically using the same logic as
5849** PRAGMA lock_proxy_file=":auto:"
5850**
5851** SQLITE_PROXY_DEBUG
5852**
5853** Enables the logging of error messages during host id file
5854** retrieval and creation
5855**
drh715ff302008-12-03 22:32:44 +00005856** LOCKPROXYDIR
5857**
5858** Overrides the default directory used for lock proxy files that
5859** are named automatically via the ":auto:" setting
5860**
5861** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5862**
5863** Permissions to use when creating a directory for storing the
5864** lock proxy files, only used when LOCKPROXYDIR is not set.
5865**
5866**
5867** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5868** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5869** force proxy locking to be used for every database file opened, and 0
5870** will force automatic proxy locking to be disabled for all database
5871** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5872** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5873*/
5874
5875/*
5876** Proxy locking is only available on MacOSX
5877*/
drhd2cb50b2009-01-09 21:41:17 +00005878#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005879
drh715ff302008-12-03 22:32:44 +00005880/*
5881** The proxyLockingContext has the path and file structures for the remote
5882** and local proxy files in it
5883*/
5884typedef struct proxyLockingContext proxyLockingContext;
5885struct proxyLockingContext {
5886 unixFile *conchFile; /* Open conch file */
5887 char *conchFilePath; /* Name of the conch file */
5888 unixFile *lockProxy; /* Open proxy lock file */
5889 char *lockProxyPath; /* Name of the proxy lock file */
5890 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005891 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005892 void *oldLockingContext; /* Original lockingcontext to restore on close */
5893 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5894};
5895
drh7ed97b92010-01-20 13:07:21 +00005896/*
5897** The proxy lock file path for the database at dbPath is written into lPath,
5898** which must point to valid, writable memory large enough for a maxLen length
5899** file path.
drh715ff302008-12-03 22:32:44 +00005900*/
drh715ff302008-12-03 22:32:44 +00005901static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5902 int len;
5903 int dbLen;
5904 int i;
5905
5906#ifdef LOCKPROXYDIR
5907 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5908#else
5909# ifdef _CS_DARWIN_USER_TEMP_DIR
5910 {
drh7ed97b92010-01-20 13:07:21 +00005911 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005912 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5913 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005914 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005915 }
drh7ed97b92010-01-20 13:07:21 +00005916 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005917 }
5918# else
5919 len = strlcpy(lPath, "/tmp/", maxLen);
5920# endif
5921#endif
5922
5923 if( lPath[len-1]!='/' ){
5924 len = strlcat(lPath, "/", maxLen);
5925 }
5926
5927 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005928 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005929 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005930 char c = dbPath[i];
5931 lPath[i+len] = (c=='/')?'_':c;
5932 }
5933 lPath[i+len]='\0';
5934 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005935 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005936 return SQLITE_OK;
5937}
5938
drh7ed97b92010-01-20 13:07:21 +00005939/*
5940 ** Creates the lock file and any missing directories in lockPath
5941 */
5942static int proxyCreateLockPath(const char *lockPath){
5943 int i, len;
5944 char buf[MAXPATHLEN];
5945 int start = 0;
5946
5947 assert(lockPath!=NULL);
5948 /* try to create all the intermediate directories */
5949 len = (int)strlen(lockPath);
5950 buf[0] = lockPath[0];
5951 for( i=1; i<len; i++ ){
5952 if( lockPath[i] == '/' && (i - start > 0) ){
5953 /* only mkdir if leaf dir != "." or "/" or ".." */
5954 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5955 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5956 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005957 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005958 int err=errno;
5959 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005960 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005961 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005962 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005963 return err;
5964 }
5965 }
5966 }
5967 start=i+1;
5968 }
5969 buf[i] = lockPath[i];
5970 }
drh308c2a52010-05-14 11:30:18 +00005971 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005972 return 0;
5973}
5974
drh715ff302008-12-03 22:32:44 +00005975/*
5976** Create a new VFS file descriptor (stored in memory obtained from
5977** sqlite3_malloc) and open the file named "path" in the file descriptor.
5978**
5979** The caller is responsible not only for closing the file descriptor
5980** but also for freeing the memory associated with the file descriptor.
5981*/
drh7ed97b92010-01-20 13:07:21 +00005982static int proxyCreateUnixFile(
5983 const char *path, /* path for the new unixFile */
5984 unixFile **ppFile, /* unixFile created and returned by ref */
5985 int islockfile /* if non zero missing dirs will be created */
5986) {
5987 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005988 unixFile *pNew;
5989 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005990 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005991 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005992 int terrno = 0;
5993 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00005994
drh7ed97b92010-01-20 13:07:21 +00005995 /* 1. first try to open/create the file
5996 ** 2. if that fails, and this is a lock file (not-conch), try creating
5997 ** the parent directories and then try again.
5998 ** 3. if that fails, try to open the file read-only
5999 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6000 */
6001 pUnused = findReusableFd(path, openFlags);
6002 if( pUnused ){
6003 fd = pUnused->fd;
6004 }else{
6005 pUnused = sqlite3_malloc(sizeof(*pUnused));
6006 if( !pUnused ){
6007 return SQLITE_NOMEM;
6008 }
6009 }
6010 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006011 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006012 terrno = errno;
6013 if( fd<0 && errno==ENOENT && islockfile ){
6014 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006015 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006016 }
6017 }
6018 }
6019 if( fd<0 ){
6020 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006021 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006022 terrno = errno;
6023 }
6024 if( fd<0 ){
6025 if( islockfile ){
6026 return SQLITE_BUSY;
6027 }
6028 switch (terrno) {
6029 case EACCES:
6030 return SQLITE_PERM;
6031 case EIO:
6032 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6033 default:
drh9978c972010-02-23 17:36:32 +00006034 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006035 }
6036 }
6037
6038 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6039 if( pNew==NULL ){
6040 rc = SQLITE_NOMEM;
6041 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006042 }
6043 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006044 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006045 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006046 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006047 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006048 pUnused->fd = fd;
6049 pUnused->flags = openFlags;
6050 pNew->pUnused = pUnused;
6051
drhc02a43a2012-01-10 23:18:38 +00006052 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006053 if( rc==SQLITE_OK ){
6054 *ppFile = pNew;
6055 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006056 }
drh7ed97b92010-01-20 13:07:21 +00006057end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006058 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006059 sqlite3_free(pNew);
6060 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006061 return rc;
6062}
6063
drh7ed97b92010-01-20 13:07:21 +00006064#ifdef SQLITE_TEST
6065/* simulate multiple hosts by creating unique hostid file paths */
6066int sqlite3_hostid_num = 0;
6067#endif
6068
6069#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6070
drh0ab216a2010-07-02 17:10:40 +00006071/* Not always defined in the headers as it ought to be */
6072extern int gethostuuid(uuid_t id, const struct timespec *wait);
6073
drh7ed97b92010-01-20 13:07:21 +00006074/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6075** bytes of writable memory.
6076*/
6077static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006078 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6079 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006080#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6081 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006082 {
6083 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6084 if( gethostuuid(pHostID, &timeout) ){
6085 int err = errno;
6086 if( pError ){
6087 *pError = err;
6088 }
6089 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006090 }
drh7ed97b92010-01-20 13:07:21 +00006091 }
drh3d4435b2011-08-26 20:55:50 +00006092#else
6093 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006094#endif
drh7ed97b92010-01-20 13:07:21 +00006095#ifdef SQLITE_TEST
6096 /* simulate multiple hosts by creating unique hostid file paths */
6097 if( sqlite3_hostid_num != 0){
6098 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6099 }
6100#endif
6101
6102 return SQLITE_OK;
6103}
6104
6105/* The conch file contains the header, host id and lock file path
6106 */
6107#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6108#define PROXY_HEADERLEN 1 /* conch file header length */
6109#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6110#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6111
6112/*
6113** Takes an open conch file, copies the contents to a new path and then moves
6114** it back. The newly created file's file descriptor is assigned to the
6115** conch file structure and finally the original conch file descriptor is
6116** closed. Returns zero if successful.
6117*/
6118static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6119 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6120 unixFile *conchFile = pCtx->conchFile;
6121 char tPath[MAXPATHLEN];
6122 char buf[PROXY_MAXCONCHLEN];
6123 char *cPath = pCtx->conchFilePath;
6124 size_t readLen = 0;
6125 size_t pathLen = 0;
6126 char errmsg[64] = "";
6127 int fd = -1;
6128 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006129 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006130
6131 /* create a new path by replace the trailing '-conch' with '-break' */
6132 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6133 if( pathLen>MAXPATHLEN || pathLen<6 ||
6134 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006135 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006136 goto end_breaklock;
6137 }
6138 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006139 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006140 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006141 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006142 goto end_breaklock;
6143 }
6144 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006145 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006146 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006147 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006148 goto end_breaklock;
6149 }
drhe562be52011-03-02 18:01:10 +00006150 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006151 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006152 goto end_breaklock;
6153 }
6154 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006155 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006156 goto end_breaklock;
6157 }
6158 rc = 0;
6159 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006160 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006161 conchFile->h = fd;
6162 conchFile->openFlags = O_RDWR | O_CREAT;
6163
6164end_breaklock:
6165 if( rc ){
6166 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006167 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006168 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006169 }
6170 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6171 }
6172 return rc;
6173}
6174
6175/* Take the requested lock on the conch file and break a stale lock if the
6176** host id matches.
6177*/
6178static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6179 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6180 unixFile *conchFile = pCtx->conchFile;
6181 int rc = SQLITE_OK;
6182 int nTries = 0;
6183 struct timespec conchModTime;
6184
drh3d4435b2011-08-26 20:55:50 +00006185 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006186 do {
6187 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6188 nTries ++;
6189 if( rc==SQLITE_BUSY ){
6190 /* If the lock failed (busy):
6191 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6192 * 2nd try: fail if the mod time changed or host id is different, wait
6193 * 10 sec and try again
6194 * 3rd try: break the lock unless the mod time has changed.
6195 */
6196 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006197 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006198 pFile->lastErrno = errno;
6199 return SQLITE_IOERR_LOCK;
6200 }
6201
6202 if( nTries==1 ){
6203 conchModTime = buf.st_mtimespec;
6204 usleep(500000); /* wait 0.5 sec and try the lock again*/
6205 continue;
6206 }
6207
6208 assert( nTries>1 );
6209 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6210 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6211 return SQLITE_BUSY;
6212 }
6213
6214 if( nTries==2 ){
6215 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006216 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006217 if( len<0 ){
6218 pFile->lastErrno = errno;
6219 return SQLITE_IOERR_LOCK;
6220 }
6221 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6222 /* don't break the lock if the host id doesn't match */
6223 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6224 return SQLITE_BUSY;
6225 }
6226 }else{
6227 /* don't break the lock on short read or a version mismatch */
6228 return SQLITE_BUSY;
6229 }
6230 usleep(10000000); /* wait 10 sec and try the lock again */
6231 continue;
6232 }
6233
6234 assert( nTries==3 );
6235 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6236 rc = SQLITE_OK;
6237 if( lockType==EXCLUSIVE_LOCK ){
6238 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6239 }
6240 if( !rc ){
6241 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6242 }
6243 }
6244 }
6245 } while( rc==SQLITE_BUSY && nTries<3 );
6246
6247 return rc;
6248}
6249
6250/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006251** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6252** lockPath means that the lockPath in the conch file will be used if the
6253** host IDs match, or a new lock path will be generated automatically
6254** and written to the conch file.
6255*/
6256static int proxyTakeConch(unixFile *pFile){
6257 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6258
drh7ed97b92010-01-20 13:07:21 +00006259 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006260 return SQLITE_OK;
6261 }else{
6262 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006263 uuid_t myHostID;
6264 int pError = 0;
6265 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006266 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006267 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006268 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006269 int createConch = 0;
6270 int hostIdMatch = 0;
6271 int readLen = 0;
6272 int tryOldLockPath = 0;
6273 int forceNewLockPath = 0;
6274
drh308c2a52010-05-14 11:30:18 +00006275 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6276 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006277
drh7ed97b92010-01-20 13:07:21 +00006278 rc = proxyGetHostID(myHostID, &pError);
6279 if( (rc&0xff)==SQLITE_IOERR ){
6280 pFile->lastErrno = pError;
6281 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006282 }
drh7ed97b92010-01-20 13:07:21 +00006283 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006284 if( rc!=SQLITE_OK ){
6285 goto end_takeconch;
6286 }
drh7ed97b92010-01-20 13:07:21 +00006287 /* read the existing conch file */
6288 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6289 if( readLen<0 ){
6290 /* I/O error: lastErrno set by seekAndRead */
6291 pFile->lastErrno = conchFile->lastErrno;
6292 rc = SQLITE_IOERR_READ;
6293 goto end_takeconch;
6294 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6295 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6296 /* a short read or version format mismatch means we need to create a new
6297 ** conch file.
6298 */
6299 createConch = 1;
6300 }
6301 /* if the host id matches and the lock path already exists in the conch
6302 ** we'll try to use the path there, if we can't open that path, we'll
6303 ** retry with a new auto-generated path
6304 */
6305 do { /* in case we need to try again for an :auto: named lock file */
6306
6307 if( !createConch && !forceNewLockPath ){
6308 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6309 PROXY_HOSTIDLEN);
6310 /* if the conch has data compare the contents */
6311 if( !pCtx->lockProxyPath ){
6312 /* for auto-named local lock file, just check the host ID and we'll
6313 ** use the local lock file path that's already in there
6314 */
6315 if( hostIdMatch ){
6316 size_t pathLen = (readLen - PROXY_PATHINDEX);
6317
6318 if( pathLen>=MAXPATHLEN ){
6319 pathLen=MAXPATHLEN-1;
6320 }
6321 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6322 lockPath[pathLen] = 0;
6323 tempLockPath = lockPath;
6324 tryOldLockPath = 1;
6325 /* create a copy of the lock path if the conch is taken */
6326 goto end_takeconch;
6327 }
6328 }else if( hostIdMatch
6329 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6330 readLen-PROXY_PATHINDEX)
6331 ){
6332 /* conch host and lock path match */
6333 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006334 }
drh7ed97b92010-01-20 13:07:21 +00006335 }
6336
6337 /* if the conch isn't writable and doesn't match, we can't take it */
6338 if( (conchFile->openFlags&O_RDWR) == 0 ){
6339 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006340 goto end_takeconch;
6341 }
drh7ed97b92010-01-20 13:07:21 +00006342
6343 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006344 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006345 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6346 tempLockPath = lockPath;
6347 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006348 }
drh7ed97b92010-01-20 13:07:21 +00006349
6350 /* update conch with host and path (this will fail if other process
6351 ** has a shared lock already), if the host id matches, use the big
6352 ** stick.
drh715ff302008-12-03 22:32:44 +00006353 */
drh7ed97b92010-01-20 13:07:21 +00006354 futimes(conchFile->h, NULL);
6355 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006356 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006357 /* We are trying for an exclusive lock but another thread in this
6358 ** same process is still holding a shared lock. */
6359 rc = SQLITE_BUSY;
6360 } else {
6361 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006362 }
drh715ff302008-12-03 22:32:44 +00006363 }else{
drh7ed97b92010-01-20 13:07:21 +00006364 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006365 }
drh7ed97b92010-01-20 13:07:21 +00006366 if( rc==SQLITE_OK ){
6367 char writeBuffer[PROXY_MAXCONCHLEN];
6368 int writeSize = 0;
6369
6370 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6371 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6372 if( pCtx->lockProxyPath!=NULL ){
6373 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6374 }else{
6375 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6376 }
6377 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006378 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006379 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6380 fsync(conchFile->h);
6381 /* If we created a new conch file (not just updated the contents of a
6382 ** valid conch file), try to match the permissions of the database
6383 */
6384 if( rc==SQLITE_OK && createConch ){
6385 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006386 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006387 if( err==0 ){
6388 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6389 S_IROTH|S_IWOTH);
6390 /* try to match the database file R/W permissions, ignore failure */
6391#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006392 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006393#else
drhff812312011-02-23 13:33:46 +00006394 do{
drhe562be52011-03-02 18:01:10 +00006395 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006396 }while( rc==(-1) && errno==EINTR );
6397 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006398 int code = errno;
6399 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6400 cmode, code, strerror(code));
6401 } else {
6402 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6403 }
6404 }else{
6405 int code = errno;
6406 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6407 err, code, strerror(code));
6408#endif
6409 }
drh715ff302008-12-03 22:32:44 +00006410 }
6411 }
drh7ed97b92010-01-20 13:07:21 +00006412 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6413
6414 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006415 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006416 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006417 int fd;
drh7ed97b92010-01-20 13:07:21 +00006418 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006419 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006420 }
6421 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006422 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006423 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006424 if( fd>=0 ){
6425 pFile->h = fd;
6426 }else{
drh9978c972010-02-23 17:36:32 +00006427 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006428 during locking */
6429 }
6430 }
6431 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6432 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6433 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6434 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6435 /* we couldn't create the proxy lock file with the old lock file path
6436 ** so try again via auto-naming
6437 */
6438 forceNewLockPath = 1;
6439 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006440 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006441 }
6442 }
6443 if( rc==SQLITE_OK ){
6444 /* Need to make a copy of path if we extracted the value
6445 ** from the conch file or the path was allocated on the stack
6446 */
6447 if( tempLockPath ){
6448 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6449 if( !pCtx->lockProxyPath ){
6450 rc = SQLITE_NOMEM;
6451 }
6452 }
6453 }
6454 if( rc==SQLITE_OK ){
6455 pCtx->conchHeld = 1;
6456
6457 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6458 afpLockingContext *afpCtx;
6459 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6460 afpCtx->dbPath = pCtx->lockProxyPath;
6461 }
6462 } else {
6463 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6464 }
drh308c2a52010-05-14 11:30:18 +00006465 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6466 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006467 return rc;
drh308c2a52010-05-14 11:30:18 +00006468 } while (1); /* in case we need to retry the :auto: lock file -
6469 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006470 }
6471}
6472
6473/*
6474** If pFile holds a lock on a conch file, then release that lock.
6475*/
6476static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006477 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006478 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6479 unixFile *conchFile; /* Name of the conch file */
6480
6481 pCtx = (proxyLockingContext *)pFile->lockingContext;
6482 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006483 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006484 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006485 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006486 if( pCtx->conchHeld>0 ){
6487 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6488 }
drh715ff302008-12-03 22:32:44 +00006489 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006490 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6491 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006492 return rc;
6493}
6494
6495/*
6496** Given the name of a database file, compute the name of its conch file.
6497** Store the conch filename in memory obtained from sqlite3_malloc().
6498** Make *pConchPath point to the new name. Return SQLITE_OK on success
6499** or SQLITE_NOMEM if unable to obtain memory.
6500**
6501** The caller is responsible for ensuring that the allocated memory
6502** space is eventually freed.
6503**
6504** *pConchPath is set to NULL if a memory allocation error occurs.
6505*/
6506static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6507 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006508 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006509 char *conchPath; /* buffer in which to construct conch name */
6510
6511 /* Allocate space for the conch filename and initialize the name to
6512 ** the name of the original database file. */
6513 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6514 if( conchPath==0 ){
6515 return SQLITE_NOMEM;
6516 }
6517 memcpy(conchPath, dbPath, len+1);
6518
6519 /* now insert a "." before the last / character */
6520 for( i=(len-1); i>=0; i-- ){
6521 if( conchPath[i]=='/' ){
6522 i++;
6523 break;
6524 }
6525 }
6526 conchPath[i]='.';
6527 while ( i<len ){
6528 conchPath[i+1]=dbPath[i];
6529 i++;
6530 }
6531
6532 /* append the "-conch" suffix to the file */
6533 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006534 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006535
6536 return SQLITE_OK;
6537}
6538
6539
6540/* Takes a fully configured proxy locking-style unix file and switches
6541** the local lock file path
6542*/
6543static int switchLockProxyPath(unixFile *pFile, const char *path) {
6544 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6545 char *oldPath = pCtx->lockProxyPath;
6546 int rc = SQLITE_OK;
6547
drh308c2a52010-05-14 11:30:18 +00006548 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006549 return SQLITE_BUSY;
6550 }
6551
6552 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6553 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6554 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6555 return SQLITE_OK;
6556 }else{
6557 unixFile *lockProxy = pCtx->lockProxy;
6558 pCtx->lockProxy=NULL;
6559 pCtx->conchHeld = 0;
6560 if( lockProxy!=NULL ){
6561 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6562 if( rc ) return rc;
6563 sqlite3_free(lockProxy);
6564 }
6565 sqlite3_free(oldPath);
6566 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6567 }
6568
6569 return rc;
6570}
6571
6572/*
6573** pFile is a file that has been opened by a prior xOpen call. dbPath
6574** is a string buffer at least MAXPATHLEN+1 characters in size.
6575**
6576** This routine find the filename associated with pFile and writes it
6577** int dbPath.
6578*/
6579static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006580#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006581 if( pFile->pMethod == &afpIoMethods ){
6582 /* afp style keeps a reference to the db path in the filePath field
6583 ** of the struct */
drhea678832008-12-10 19:26:22 +00006584 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006585 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6586 } else
drh715ff302008-12-03 22:32:44 +00006587#endif
6588 if( pFile->pMethod == &dotlockIoMethods ){
6589 /* dot lock style uses the locking context to store the dot lock
6590 ** file path */
6591 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6592 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6593 }else{
6594 /* all other styles use the locking context to store the db file path */
6595 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006596 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006597 }
6598 return SQLITE_OK;
6599}
6600
6601/*
6602** Takes an already filled in unix file and alters it so all file locking
6603** will be performed on the local proxy lock file. The following fields
6604** are preserved in the locking context so that they can be restored and
6605** the unix structure properly cleaned up at close time:
6606** ->lockingContext
6607** ->pMethod
6608*/
6609static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6610 proxyLockingContext *pCtx;
6611 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6612 char *lockPath=NULL;
6613 int rc = SQLITE_OK;
6614
drh308c2a52010-05-14 11:30:18 +00006615 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006616 return SQLITE_BUSY;
6617 }
6618 proxyGetDbPathForUnixFile(pFile, dbPath);
6619 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6620 lockPath=NULL;
6621 }else{
6622 lockPath=(char *)path;
6623 }
6624
drh308c2a52010-05-14 11:30:18 +00006625 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6626 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006627
6628 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6629 if( pCtx==0 ){
6630 return SQLITE_NOMEM;
6631 }
6632 memset(pCtx, 0, sizeof(*pCtx));
6633
6634 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6635 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006636 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6637 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6638 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6639 ** (c) the file system is read-only, then enable no-locking access.
6640 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6641 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6642 */
6643 struct statfs fsInfo;
6644 struct stat conchInfo;
6645 int goLockless = 0;
6646
drh99ab3b12011-03-02 15:09:07 +00006647 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006648 int err = errno;
6649 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6650 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6651 }
6652 }
6653 if( goLockless ){
6654 pCtx->conchHeld = -1; /* read only FS/ lockless */
6655 rc = SQLITE_OK;
6656 }
6657 }
drh715ff302008-12-03 22:32:44 +00006658 }
6659 if( rc==SQLITE_OK && lockPath ){
6660 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6661 }
6662
6663 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006664 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6665 if( pCtx->dbPath==NULL ){
6666 rc = SQLITE_NOMEM;
6667 }
6668 }
6669 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006670 /* all memory is allocated, proxys are created and assigned,
6671 ** switch the locking context and pMethod then return.
6672 */
drh715ff302008-12-03 22:32:44 +00006673 pCtx->oldLockingContext = pFile->lockingContext;
6674 pFile->lockingContext = pCtx;
6675 pCtx->pOldMethod = pFile->pMethod;
6676 pFile->pMethod = &proxyIoMethods;
6677 }else{
6678 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006679 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006680 sqlite3_free(pCtx->conchFile);
6681 }
drhd56b1212010-08-11 06:14:15 +00006682 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006683 sqlite3_free(pCtx->conchFilePath);
6684 sqlite3_free(pCtx);
6685 }
drh308c2a52010-05-14 11:30:18 +00006686 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6687 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006688 return rc;
6689}
6690
6691
6692/*
6693** This routine handles sqlite3_file_control() calls that are specific
6694** to proxy locking.
6695*/
6696static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6697 switch( op ){
6698 case SQLITE_GET_LOCKPROXYFILE: {
6699 unixFile *pFile = (unixFile*)id;
6700 if( pFile->pMethod == &proxyIoMethods ){
6701 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6702 proxyTakeConch(pFile);
6703 if( pCtx->lockProxyPath ){
6704 *(const char **)pArg = pCtx->lockProxyPath;
6705 }else{
6706 *(const char **)pArg = ":auto: (not held)";
6707 }
6708 } else {
6709 *(const char **)pArg = NULL;
6710 }
6711 return SQLITE_OK;
6712 }
6713 case SQLITE_SET_LOCKPROXYFILE: {
6714 unixFile *pFile = (unixFile*)id;
6715 int rc = SQLITE_OK;
6716 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6717 if( pArg==NULL || (const char *)pArg==0 ){
6718 if( isProxyStyle ){
6719 /* turn off proxy locking - not supported */
6720 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6721 }else{
6722 /* turn off proxy locking - already off - NOOP */
6723 rc = SQLITE_OK;
6724 }
6725 }else{
6726 const char *proxyPath = (const char *)pArg;
6727 if( isProxyStyle ){
6728 proxyLockingContext *pCtx =
6729 (proxyLockingContext*)pFile->lockingContext;
6730 if( !strcmp(pArg, ":auto:")
6731 || (pCtx->lockProxyPath &&
6732 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6733 ){
6734 rc = SQLITE_OK;
6735 }else{
6736 rc = switchLockProxyPath(pFile, proxyPath);
6737 }
6738 }else{
6739 /* turn on proxy file locking */
6740 rc = proxyTransformUnixFile(pFile, proxyPath);
6741 }
6742 }
6743 return rc;
6744 }
6745 default: {
6746 assert( 0 ); /* The call assures that only valid opcodes are sent */
6747 }
6748 }
6749 /*NOTREACHED*/
6750 return SQLITE_ERROR;
6751}
6752
6753/*
6754** Within this division (the proxying locking implementation) the procedures
6755** above this point are all utilities. The lock-related methods of the
6756** proxy-locking sqlite3_io_method object follow.
6757*/
6758
6759
6760/*
6761** This routine checks if there is a RESERVED lock held on the specified
6762** file by this or any other process. If such a lock is held, set *pResOut
6763** to a non-zero value otherwise *pResOut is set to zero. The return value
6764** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6765*/
6766static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6767 unixFile *pFile = (unixFile*)id;
6768 int rc = proxyTakeConch(pFile);
6769 if( rc==SQLITE_OK ){
6770 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006771 if( pCtx->conchHeld>0 ){
6772 unixFile *proxy = pCtx->lockProxy;
6773 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6774 }else{ /* conchHeld < 0 is lockless */
6775 pResOut=0;
6776 }
drh715ff302008-12-03 22:32:44 +00006777 }
6778 return rc;
6779}
6780
6781/*
drh308c2a52010-05-14 11:30:18 +00006782** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006783** of the following:
6784**
6785** (1) SHARED_LOCK
6786** (2) RESERVED_LOCK
6787** (3) PENDING_LOCK
6788** (4) EXCLUSIVE_LOCK
6789**
6790** Sometimes when requesting one lock state, additional lock states
6791** are inserted in between. The locking might fail on one of the later
6792** transitions leaving the lock state different from what it started but
6793** still short of its goal. The following chart shows the allowed
6794** transitions and the inserted intermediate states:
6795**
6796** UNLOCKED -> SHARED
6797** SHARED -> RESERVED
6798** SHARED -> (PENDING) -> EXCLUSIVE
6799** RESERVED -> (PENDING) -> EXCLUSIVE
6800** PENDING -> EXCLUSIVE
6801**
6802** This routine will only increase a lock. Use the sqlite3OsUnlock()
6803** routine to lower a locking level.
6804*/
drh308c2a52010-05-14 11:30:18 +00006805static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006806 unixFile *pFile = (unixFile*)id;
6807 int rc = proxyTakeConch(pFile);
6808 if( rc==SQLITE_OK ){
6809 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006810 if( pCtx->conchHeld>0 ){
6811 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006812 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6813 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006814 }else{
6815 /* conchHeld < 0 is lockless */
6816 }
drh715ff302008-12-03 22:32:44 +00006817 }
6818 return rc;
6819}
6820
6821
6822/*
drh308c2a52010-05-14 11:30:18 +00006823** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006824** must be either NO_LOCK or SHARED_LOCK.
6825**
6826** If the locking level of the file descriptor is already at or below
6827** the requested locking level, this routine is a no-op.
6828*/
drh308c2a52010-05-14 11:30:18 +00006829static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006830 unixFile *pFile = (unixFile*)id;
6831 int rc = proxyTakeConch(pFile);
6832 if( rc==SQLITE_OK ){
6833 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006834 if( pCtx->conchHeld>0 ){
6835 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006836 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6837 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006838 }else{
6839 /* conchHeld < 0 is lockless */
6840 }
drh715ff302008-12-03 22:32:44 +00006841 }
6842 return rc;
6843}
6844
6845/*
6846** Close a file that uses proxy locks.
6847*/
6848static int proxyClose(sqlite3_file *id) {
6849 if( id ){
6850 unixFile *pFile = (unixFile*)id;
6851 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6852 unixFile *lockProxy = pCtx->lockProxy;
6853 unixFile *conchFile = pCtx->conchFile;
6854 int rc = SQLITE_OK;
6855
6856 if( lockProxy ){
6857 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6858 if( rc ) return rc;
6859 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6860 if( rc ) return rc;
6861 sqlite3_free(lockProxy);
6862 pCtx->lockProxy = 0;
6863 }
6864 if( conchFile ){
6865 if( pCtx->conchHeld ){
6866 rc = proxyReleaseConch(pFile);
6867 if( rc ) return rc;
6868 }
6869 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6870 if( rc ) return rc;
6871 sqlite3_free(conchFile);
6872 }
drhd56b1212010-08-11 06:14:15 +00006873 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006874 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006875 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006876 /* restore the original locking context and pMethod then close it */
6877 pFile->lockingContext = pCtx->oldLockingContext;
6878 pFile->pMethod = pCtx->pOldMethod;
6879 sqlite3_free(pCtx);
6880 return pFile->pMethod->xClose(id);
6881 }
6882 return SQLITE_OK;
6883}
6884
6885
6886
drhd2cb50b2009-01-09 21:41:17 +00006887#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006888/*
6889** The proxy locking style is intended for use with AFP filesystems.
6890** And since AFP is only supported on MacOSX, the proxy locking is also
6891** restricted to MacOSX.
6892**
6893**
6894******************* End of the proxy lock implementation **********************
6895******************************************************************************/
6896
drh734c9862008-11-28 15:37:20 +00006897/*
danielk1977e339d652008-06-28 11:23:00 +00006898** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006899**
6900** This routine registers all VFS implementations for unix-like operating
6901** systems. This routine, and the sqlite3_os_end() routine that follows,
6902** should be the only routines in this file that are visible from other
6903** files.
drh6b9d6dd2008-12-03 19:34:47 +00006904**
6905** This routine is called once during SQLite initialization and by a
6906** single thread. The memory allocation and mutex subsystems have not
6907** necessarily been initialized when this routine is called, and so they
6908** should not be used.
drh153c62c2007-08-24 03:51:33 +00006909*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006910int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006911 /*
6912 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006913 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6914 ** to the "finder" function. (pAppData is a pointer to a pointer because
6915 ** silly C90 rules prohibit a void* from being cast to a function pointer
6916 ** and so we have to go through the intermediate pointer to avoid problems
6917 ** when compiling with -pedantic-errors on GCC.)
6918 **
6919 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006920 ** finder-function. The finder-function returns a pointer to the
6921 ** sqlite_io_methods object that implements the desired locking
6922 ** behaviors. See the division above that contains the IOMETHODS
6923 ** macro for addition information on finder-functions.
6924 **
6925 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6926 ** object. But the "autolockIoFinder" available on MacOSX does a little
6927 ** more than that; it looks at the filesystem type that hosts the
6928 ** database file and tries to choose an locking method appropriate for
6929 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006930 */
drh7708e972008-11-29 00:56:52 +00006931 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006932 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006933 sizeof(unixFile), /* szOsFile */ \
6934 MAX_PATHNAME, /* mxPathname */ \
6935 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006936 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006937 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006938 unixOpen, /* xOpen */ \
6939 unixDelete, /* xDelete */ \
6940 unixAccess, /* xAccess */ \
6941 unixFullPathname, /* xFullPathname */ \
6942 unixDlOpen, /* xDlOpen */ \
6943 unixDlError, /* xDlError */ \
6944 unixDlSym, /* xDlSym */ \
6945 unixDlClose, /* xDlClose */ \
6946 unixRandomness, /* xRandomness */ \
6947 unixSleep, /* xSleep */ \
6948 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006949 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006950 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006951 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006952 unixGetSystemCall, /* xGetSystemCall */ \
6953 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006954 }
6955
drh6b9d6dd2008-12-03 19:34:47 +00006956 /*
6957 ** All default VFSes for unix are contained in the following array.
6958 **
6959 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6960 ** by the SQLite core when the VFS is registered. So the following
6961 ** array cannot be const.
6962 */
danielk1977e339d652008-06-28 11:23:00 +00006963 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006964#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006965 UNIXVFS("unix", autolockIoFinder ),
6966#else
6967 UNIXVFS("unix", posixIoFinder ),
6968#endif
6969 UNIXVFS("unix-none", nolockIoFinder ),
6970 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006971 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006972#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006973 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006974#endif
6975#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006976 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006977#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006978 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006979#endif
chw78a13182009-04-07 05:35:03 +00006980#endif
drhd2cb50b2009-01-09 21:41:17 +00006981#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006982 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006983 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006984 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006985#endif
drh153c62c2007-08-24 03:51:33 +00006986 };
drh6b9d6dd2008-12-03 19:34:47 +00006987 unsigned int i; /* Loop counter */
6988
drh2aa5a002011-04-13 13:42:25 +00006989 /* Double-check that the aSyscall[] array has been constructed
6990 ** correctly. See ticket [bb3a86e890c8e96ab] */
drhe1186ab2013-01-04 20:45:13 +00006991 assert( ArraySize(aSyscall)==21 );
drh2aa5a002011-04-13 13:42:25 +00006992
drh6b9d6dd2008-12-03 19:34:47 +00006993 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00006994 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00006995 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00006996 }
danielk1977c0fa4c52008-06-25 17:19:00 +00006997 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00006998}
danielk1977e339d652008-06-28 11:23:00 +00006999
7000/*
drh6b9d6dd2008-12-03 19:34:47 +00007001** Shutdown the operating system interface.
7002**
7003** Some operating systems might need to do some cleanup in this routine,
7004** to release dynamically allocated objects. But not on unix.
7005** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007006*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007007int sqlite3_os_end(void){
7008 return SQLITE_OK;
7009}
drhdce8bdb2007-08-16 13:01:44 +00007010
danielk197729bafea2008-06-26 10:41:19 +00007011#endif /* SQLITE_OS_UNIX */