blob: 315f15018887f93c2b8e01684d608ccd6e028bc6 [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
drha6c47492011-04-11 18:35:09 +0000415#if SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000416 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000417#else
418 { "fchmod", (sqlite3_syscall_ptr)0, 0 },
drha6c47492011-04-11 18:35:09 +0000419#endif
drh2aa5a002011-04-13 13:42:25 +0000420#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000421
422#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000423 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000424#else
drh58ad5802011-03-23 22:02:23 +0000425 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000426#endif
dan0fd7d862011-03-29 10:04:23 +0000427#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000428
drh036ac7f2011-08-08 23:18:05 +0000429 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
430#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
431
drh90315a22011-08-10 01:52:12 +0000432 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
433#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
434
drh9ef6bc42011-11-04 02:24:02 +0000435 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
436#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
437
438 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
439#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
440
drhed466822012-05-31 13:10:49 +0000441 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000442#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000443
drh8c815d12012-02-13 20:16:37 +0000444 { "umask", (sqlite3_syscall_ptr)umask, 0 },
445#define osUmask ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
446
drhe562be52011-03-02 18:01:10 +0000447}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000448
449/*
450** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000451** "unix" VFSes. Return SQLITE_OK opon successfully updating the
452** system call pointer, or SQLITE_NOTFOUND if there is no configurable
453** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000454*/
455static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000456 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
457 const char *zName, /* Name of system call to override */
458 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000459){
drh58ad5802011-03-23 22:02:23 +0000460 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000461 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000462
463 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000464 if( zName==0 ){
465 /* If no zName is given, restore all system calls to their default
466 ** settings and return NULL
467 */
dan51438a72011-04-02 17:00:47 +0000468 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000469 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
470 if( aSyscall[i].pDefault ){
471 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000472 }
473 }
474 }else{
475 /* If zName is specified, operate on only the one system call
476 ** specified.
477 */
478 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
479 if( strcmp(zName, aSyscall[i].zName)==0 ){
480 if( aSyscall[i].pDefault==0 ){
481 aSyscall[i].pDefault = aSyscall[i].pCurrent;
482 }
drh1df30962011-03-02 19:06:42 +0000483 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000484 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
485 aSyscall[i].pCurrent = pNewFunc;
486 break;
487 }
488 }
489 }
490 return rc;
491}
492
drh1df30962011-03-02 19:06:42 +0000493/*
494** Return the value of a system call. Return NULL if zName is not a
495** recognized system call name. NULL is also returned if the system call
496** is currently undefined.
497*/
drh58ad5802011-03-23 22:02:23 +0000498static sqlite3_syscall_ptr unixGetSystemCall(
499 sqlite3_vfs *pNotUsed,
500 const char *zName
501){
502 unsigned int i;
503
504 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000505 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
506 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
507 }
508 return 0;
509}
510
511/*
512** Return the name of the first system call after zName. If zName==NULL
513** then return the name of the first system call. Return NULL if zName
514** is the last system call or if zName is not the name of a valid
515** system call.
516*/
517static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000518 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000519
520 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000521 if( zName ){
522 for(i=0; i<ArraySize(aSyscall)-1; i++){
523 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000524 }
525 }
dan0fd7d862011-03-29 10:04:23 +0000526 for(i++; i<ArraySize(aSyscall); i++){
527 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000528 }
529 return 0;
530}
531
drhad4f1e52011-03-04 15:43:57 +0000532/*
drh8c815d12012-02-13 20:16:37 +0000533** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000534** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000535**
536** If the file creation mode "m" is 0 then set it to the default for
537** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
538** 0644) as modified by the system umask. If m is not 0, then
539** make the file creation mode be exactly m ignoring the umask.
540**
541** The m parameter will be non-zero only when creating -wal, -journal,
542** and -shm files. We want those files to have *exactly* the same
543** permissions as their original database, unadulterated by the umask.
544** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
545** transaction crashes and leaves behind hot journals, then any
546** process that is able to write to the database will also be able to
547** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000548*/
drh8c815d12012-02-13 20:16:37 +0000549static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000550 int fd;
drh8c815d12012-02-13 20:16:37 +0000551 mode_t m2;
drhef595982012-02-13 20:28:15 +0000552 mode_t origM = 0;
drh8c815d12012-02-13 20:16:37 +0000553 if( m==0 ){
554 m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
555 }else{
556 m2 = m;
557 origM = osUmask(0);
558 }
drh5adc60b2012-04-14 13:25:11 +0000559 do{
560#if defined(O_CLOEXEC)
561 fd = osOpen(z,f|O_CLOEXEC,m2);
562#else
563 fd = osOpen(z,f,m2);
564#endif
565 }while( fd<0 && errno==EINTR );
drh8c815d12012-02-13 20:16:37 +0000566 if( m ){
567 osUmask(origM);
568 }
drh5adc60b2012-04-14 13:25:11 +0000569#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
570 if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
571#endif
572 return fd;
drhad4f1e52011-03-04 15:43:57 +0000573}
danielk197713adf8a2004-06-03 16:08:41 +0000574
drh107886a2008-11-21 22:21:50 +0000575/*
dan9359c7b2009-08-21 08:29:10 +0000576** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000577** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000578** vxworksFileId objects used by this file, all of which may be
579** shared by multiple threads.
580**
581** Function unixMutexHeld() is used to assert() that the global mutex
582** is held when required. This function is only used as part of assert()
583** statements. e.g.
584**
585** unixEnterMutex()
586** assert( unixMutexHeld() );
587** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000588*/
589static void unixEnterMutex(void){
590 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
591}
592static void unixLeaveMutex(void){
593 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
594}
dan9359c7b2009-08-21 08:29:10 +0000595#ifdef SQLITE_DEBUG
596static int unixMutexHeld(void) {
597 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
598}
599#endif
drh107886a2008-11-21 22:21:50 +0000600
drh734c9862008-11-28 15:37:20 +0000601
drh30ddce62011-10-15 00:16:30 +0000602#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000603/*
604** Helper function for printing out trace information from debugging
605** binaries. This returns the string represetation of the supplied
606** integer lock-type.
607*/
drh308c2a52010-05-14 11:30:18 +0000608static const char *azFileLock(int eFileLock){
609 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000610 case NO_LOCK: return "NONE";
611 case SHARED_LOCK: return "SHARED";
612 case RESERVED_LOCK: return "RESERVED";
613 case PENDING_LOCK: return "PENDING";
614 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000615 }
616 return "ERROR";
617}
618#endif
619
620#ifdef SQLITE_LOCK_TRACE
621/*
622** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000623**
drh734c9862008-11-28 15:37:20 +0000624** This routine is used for troubleshooting locks on multithreaded
625** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
626** command-line option on the compiler. This code is normally
627** turned off.
628*/
629static int lockTrace(int fd, int op, struct flock *p){
630 char *zOpName, *zType;
631 int s;
632 int savedErrno;
633 if( op==F_GETLK ){
634 zOpName = "GETLK";
635 }else if( op==F_SETLK ){
636 zOpName = "SETLK";
637 }else{
drh99ab3b12011-03-02 15:09:07 +0000638 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000639 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
640 return s;
641 }
642 if( p->l_type==F_RDLCK ){
643 zType = "RDLCK";
644 }else if( p->l_type==F_WRLCK ){
645 zType = "WRLCK";
646 }else if( p->l_type==F_UNLCK ){
647 zType = "UNLCK";
648 }else{
649 assert( 0 );
650 }
651 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000652 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000653 savedErrno = errno;
654 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
655 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
656 (int)p->l_pid, s);
657 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
658 struct flock l2;
659 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000660 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000661 if( l2.l_type==F_RDLCK ){
662 zType = "RDLCK";
663 }else if( l2.l_type==F_WRLCK ){
664 zType = "WRLCK";
665 }else if( l2.l_type==F_UNLCK ){
666 zType = "UNLCK";
667 }else{
668 assert( 0 );
669 }
670 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
671 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
672 }
673 errno = savedErrno;
674 return s;
675}
drh99ab3b12011-03-02 15:09:07 +0000676#undef osFcntl
677#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000678#endif /* SQLITE_LOCK_TRACE */
679
drhff812312011-02-23 13:33:46 +0000680/*
681** Retry ftruncate() calls that fail due to EINTR
682*/
drhff812312011-02-23 13:33:46 +0000683static int robust_ftruncate(int h, sqlite3_int64 sz){
684 int rc;
drh99ab3b12011-03-02 15:09:07 +0000685 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000686 return rc;
687}
drh734c9862008-11-28 15:37:20 +0000688
689/*
690** This routine translates a standard POSIX errno code into something
691** useful to the clients of the sqlite3 functions. Specifically, it is
692** intended to translate a variety of "try again" errors into SQLITE_BUSY
693** and a variety of "please close the file descriptor NOW" errors into
694** SQLITE_IOERR
695**
696** Errors during initialization of locks, or file system support for locks,
697** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
698*/
699static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
700 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000701#if 0
702 /* At one point this code was not commented out. In theory, this branch
703 ** should never be hit, as this function should only be called after
704 ** a locking-related function (i.e. fcntl()) has returned non-zero with
705 ** the value of errno as the first argument. Since a system call has failed,
706 ** errno should be non-zero.
707 **
708 ** Despite this, if errno really is zero, we still don't want to return
709 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
710 ** propagated back to the caller. Commenting this branch out means errno==0
711 ** will be handled by the "default:" case below.
712 */
drh734c9862008-11-28 15:37:20 +0000713 case 0:
714 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000715#endif
716
drh734c9862008-11-28 15:37:20 +0000717 case EAGAIN:
718 case ETIMEDOUT:
719 case EBUSY:
720 case EINTR:
721 case ENOLCK:
722 /* random NFS retry error, unless during file system support
723 * introspection, in which it actually means what it says */
724 return SQLITE_BUSY;
725
726 case EACCES:
727 /* EACCES is like EAGAIN during locking operations, but not any other time*/
728 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000729 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
730 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
731 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000732 return SQLITE_BUSY;
733 }
734 /* else fall through */
735 case EPERM:
736 return SQLITE_PERM;
737
danea83bc62011-04-01 11:56:32 +0000738 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
739 ** this module never makes such a call. And the code in SQLite itself
740 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
741 ** this case is also commented out. If the system does set errno to EDEADLK,
742 ** the default SQLITE_IOERR_XXX code will be returned. */
743#if 0
drh734c9862008-11-28 15:37:20 +0000744 case EDEADLK:
745 return SQLITE_IOERR_BLOCKED;
danea83bc62011-04-01 11:56:32 +0000746#endif
drh734c9862008-11-28 15:37:20 +0000747
748#if EOPNOTSUPP!=ENOTSUP
749 case EOPNOTSUPP:
750 /* something went terribly awry, unless during file system support
751 * introspection, in which it actually means what it says */
752#endif
753#ifdef ENOTSUP
754 case ENOTSUP:
755 /* invalid fd, unless during file system support introspection, in which
756 * it actually means what it says */
757#endif
758 case EIO:
759 case EBADF:
760 case EINVAL:
761 case ENOTCONN:
762 case ENODEV:
763 case ENXIO:
764 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000765#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000766 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000767#endif
drh734c9862008-11-28 15:37:20 +0000768 case ENOSYS:
769 /* these should force the client to close the file and reconnect */
770
771 default:
772 return sqliteIOErr;
773 }
774}
775
776
777
778/******************************************************************************
779****************** Begin Unique File ID Utility Used By VxWorks ***************
780**
781** On most versions of unix, we can get a unique ID for a file by concatenating
782** the device number and the inode number. But this does not work on VxWorks.
783** On VxWorks, a unique file id must be based on the canonical filename.
784**
785** A pointer to an instance of the following structure can be used as a
786** unique file ID in VxWorks. Each instance of this structure contains
787** a copy of the canonical filename. There is also a reference count.
788** The structure is reclaimed when the number of pointers to it drops to
789** zero.
790**
791** There are never very many files open at one time and lookups are not
792** a performance-critical path, so it is sufficient to put these
793** structures on a linked list.
794*/
795struct vxworksFileId {
796 struct vxworksFileId *pNext; /* Next in a list of them all */
797 int nRef; /* Number of references to this one */
798 int nName; /* Length of the zCanonicalName[] string */
799 char *zCanonicalName; /* Canonical filename */
800};
801
802#if OS_VXWORKS
803/*
drh9b35ea62008-11-29 02:20:26 +0000804** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000805** variable:
806*/
807static struct vxworksFileId *vxworksFileList = 0;
808
809/*
810** Simplify a filename into its canonical form
811** by making the following changes:
812**
813** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000814** * convert /./ into just /
815** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000816**
817** Changes are made in-place. Return the new name length.
818**
819** The original filename is in z[0..n-1]. Return the number of
820** characters in the simplified name.
821*/
822static int vxworksSimplifyName(char *z, int n){
823 int i, j;
824 while( n>1 && z[n-1]=='/' ){ n--; }
825 for(i=j=0; i<n; i++){
826 if( z[i]=='/' ){
827 if( z[i+1]=='/' ) continue;
828 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
829 i += 1;
830 continue;
831 }
832 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
833 while( j>0 && z[j-1]!='/' ){ j--; }
834 if( j>0 ){ j--; }
835 i += 2;
836 continue;
837 }
838 }
839 z[j++] = z[i];
840 }
841 z[j] = 0;
842 return j;
843}
844
845/*
846** Find a unique file ID for the given absolute pathname. Return
847** a pointer to the vxworksFileId object. This pointer is the unique
848** file ID.
849**
850** The nRef field of the vxworksFileId object is incremented before
851** the object is returned. A new vxworksFileId object is created
852** and added to the global list if necessary.
853**
854** If a memory allocation error occurs, return NULL.
855*/
856static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
857 struct vxworksFileId *pNew; /* search key and new file ID */
858 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
859 int n; /* Length of zAbsoluteName string */
860
861 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000862 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000863 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
864 if( pNew==0 ) return 0;
865 pNew->zCanonicalName = (char*)&pNew[1];
866 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
867 n = vxworksSimplifyName(pNew->zCanonicalName, n);
868
869 /* Search for an existing entry that matching the canonical name.
870 ** If found, increment the reference count and return a pointer to
871 ** the existing file ID.
872 */
873 unixEnterMutex();
874 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
875 if( pCandidate->nName==n
876 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
877 ){
878 sqlite3_free(pNew);
879 pCandidate->nRef++;
880 unixLeaveMutex();
881 return pCandidate;
882 }
883 }
884
885 /* No match was found. We will make a new file ID */
886 pNew->nRef = 1;
887 pNew->nName = n;
888 pNew->pNext = vxworksFileList;
889 vxworksFileList = pNew;
890 unixLeaveMutex();
891 return pNew;
892}
893
894/*
895** Decrement the reference count on a vxworksFileId object. Free
896** the object when the reference count reaches zero.
897*/
898static void vxworksReleaseFileId(struct vxworksFileId *pId){
899 unixEnterMutex();
900 assert( pId->nRef>0 );
901 pId->nRef--;
902 if( pId->nRef==0 ){
903 struct vxworksFileId **pp;
904 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
905 assert( *pp==pId );
906 *pp = pId->pNext;
907 sqlite3_free(pId);
908 }
909 unixLeaveMutex();
910}
911#endif /* OS_VXWORKS */
912/*************** End of Unique File ID Utility Used By VxWorks ****************
913******************************************************************************/
914
915
916/******************************************************************************
917*************************** Posix Advisory Locking ****************************
918**
drh9b35ea62008-11-29 02:20:26 +0000919** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000920** section 6.5.2.2 lines 483 through 490 specify that when a process
921** sets or clears a lock, that operation overrides any prior locks set
922** by the same process. It does not explicitly say so, but this implies
923** that it overrides locks set by the same process using a different
924** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000925**
926** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000927** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
928**
929** Suppose ./file1 and ./file2 are really the same file (because
930** one is a hard or symbolic link to the other) then if you set
931** an exclusive lock on fd1, then try to get an exclusive lock
932** on fd2, it works. I would have expected the second lock to
933** fail since there was already a lock on the file due to fd1.
934** But not so. Since both locks came from the same process, the
935** second overrides the first, even though they were on different
936** file descriptors opened on different file names.
937**
drh734c9862008-11-28 15:37:20 +0000938** This means that we cannot use POSIX locks to synchronize file access
939** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000940** to synchronize access for threads in separate processes, but not
941** threads within the same process.
942**
943** To work around the problem, SQLite has to manage file locks internally
944** on its own. Whenever a new database is opened, we have to find the
945** specific inode of the database file (the inode is determined by the
946** st_dev and st_ino fields of the stat structure that fstat() fills in)
947** and check for locks already existing on that inode. When locks are
948** created or removed, we have to look at our own internal record of the
949** locks to see if another thread has previously set a lock on that same
950** inode.
951**
drh9b35ea62008-11-29 02:20:26 +0000952** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
953** For VxWorks, we have to use the alternative unique ID system based on
954** canonical filename and implemented in the previous division.)
955**
danielk1977ad94b582007-08-20 06:44:22 +0000956** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000957** descriptor. It is now a structure that holds the integer file
958** descriptor and a pointer to a structure that describes the internal
959** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000960** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000961** point to the same locking structure. The locking structure keeps
962** a reference count (so we will know when to delete it) and a "cnt"
963** field that tells us its internal lock status. cnt==0 means the
964** file is unlocked. cnt==-1 means the file has an exclusive lock.
965** cnt>0 means there are cnt shared locks on the file.
966**
967** Any attempt to lock or unlock a file first checks the locking
968** structure. The fcntl() system call is only invoked to set a
969** POSIX lock if the internal lock structure transitions between
970** a locked and an unlocked state.
971**
drh734c9862008-11-28 15:37:20 +0000972** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000973**
974** If you close a file descriptor that points to a file that has locks,
975** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000976** released. To work around this problem, each unixInodeInfo object
977** maintains a count of the number of pending locks on tha inode.
978** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000979** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000980** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000981** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +0000982** be closed and that list is walked (and cleared) when the last lock
983** clears.
984**
drh9b35ea62008-11-29 02:20:26 +0000985** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +0000986**
drh9b35ea62008-11-29 02:20:26 +0000987** Many older versions of linux use the LinuxThreads library which is
988** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +0000989** A cannot be modified or overridden by a different thread B.
990** Only thread A can modify the lock. Locking behavior is correct
991** if the appliation uses the newer Native Posix Thread Library (NPTL)
992** on linux - with NPTL a lock created by thread A can override locks
993** in thread B. But there is no way to know at compile-time which
994** threading library is being used. So there is no way to know at
995** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +0000996** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +0000997** current process.
drh5fdae772004-06-29 03:29:00 +0000998**
drh8af6c222010-05-14 12:43:01 +0000999** SQLite used to support LinuxThreads. But support for LinuxThreads
1000** was dropped beginning with version 3.7.0. SQLite will still work with
1001** LinuxThreads provided that (1) there is no more than one connection
1002** per database file in the same process and (2) database connections
1003** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001004*/
1005
1006/*
1007** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001008** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001009*/
1010struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001011 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001012#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001013 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001014#else
drh107886a2008-11-21 22:21:50 +00001015 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001016#endif
1017};
1018
1019/*
drhbbd42a62004-05-22 17:41:58 +00001020** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001021** inode. Or, on LinuxThreads, there is one of these structures for
1022** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001023**
danielk1977ad94b582007-08-20 06:44:22 +00001024** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001025** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001026** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001027*/
drh8af6c222010-05-14 12:43:01 +00001028struct unixInodeInfo {
1029 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001030 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001031 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1032 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001033 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001034 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1035 int nLock; /* Number of outstanding file locks */
1036 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1037 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1038 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001039#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001040 unsigned long long sharedByte; /* for AFP simulated shared lock */
1041#endif
drh6c7d5c52008-11-21 20:32:33 +00001042#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001043 sem_t *pSem; /* Named POSIX semaphore */
1044 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001045#endif
drhbbd42a62004-05-22 17:41:58 +00001046};
1047
drhda0e7682008-07-30 15:27:54 +00001048/*
drh8af6c222010-05-14 12:43:01 +00001049** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001050*/
drhd91c68f2010-05-14 14:52:25 +00001051static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001052
drh5fdae772004-06-29 03:29:00 +00001053/*
dane18d4952011-02-21 11:46:24 +00001054**
1055** This function - unixLogError_x(), is only ever called via the macro
1056** unixLogError().
1057**
1058** It is invoked after an error occurs in an OS function and errno has been
1059** set. It logs a message using sqlite3_log() containing the current value of
1060** errno and, if possible, the human-readable equivalent from strerror() or
1061** strerror_r().
1062**
1063** The first argument passed to the macro should be the error code that
1064** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1065** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001066** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001067** if any.
1068*/
drh0e9365c2011-03-02 02:08:13 +00001069#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1070static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001071 int errcode, /* SQLite error code */
1072 const char *zFunc, /* Name of OS function that failed */
1073 const char *zPath, /* File path associated with error */
1074 int iLine /* Source line number where error occurred */
1075){
1076 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001077 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001078
1079 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1080 ** the strerror() function to obtain the human-readable error message
1081 ** equivalent to errno. Otherwise, use strerror_r().
1082 */
1083#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1084 char aErr[80];
1085 memset(aErr, 0, sizeof(aErr));
1086 zErr = aErr;
1087
1088 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001089 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001090 ** returns a pointer to a buffer containing the error message. That pointer
1091 ** may point to aErr[], or it may point to some static storage somewhere.
1092 ** Otherwise, assume that the system provides the POSIX version of
1093 ** strerror_r(), which always writes an error message into aErr[].
1094 **
1095 ** If the code incorrectly assumes that it is the POSIX version that is
1096 ** available, the error message will often be an empty string. Not a
1097 ** huge problem. Incorrectly concluding that the GNU version is available
1098 ** could lead to a segfault though.
1099 */
1100#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1101 zErr =
1102# endif
drh0e9365c2011-03-02 02:08:13 +00001103 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001104
1105#elif SQLITE_THREADSAFE
1106 /* This is a threadsafe build, but strerror_r() is not available. */
1107 zErr = "";
1108#else
1109 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001110 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001111#endif
1112
1113 assert( errcode!=SQLITE_OK );
drh0e9365c2011-03-02 02:08:13 +00001114 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001115 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001116 "os_unix.c:%d: (%d) %s(%s) - %s",
1117 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001118 );
1119
1120 return errcode;
1121}
1122
drh0e9365c2011-03-02 02:08:13 +00001123/*
1124** Close a file descriptor.
1125**
1126** We assume that close() almost always works, since it is only in a
1127** very sick application or on a very sick platform that it might fail.
1128** If it does fail, simply leak the file descriptor, but do log the
1129** error.
1130**
1131** Note that it is not safe to retry close() after EINTR since the
1132** file descriptor might have already been reused by another thread.
1133** So we don't even try to recover from an EINTR. Just log the error
1134** and move on.
1135*/
1136static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001137 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001138 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1139 pFile ? pFile->zPath : 0, lineno);
1140 }
1141}
dane18d4952011-02-21 11:46:24 +00001142
1143/*
danb0ac3e32010-06-16 10:55:42 +00001144** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001145*/
drh0e9365c2011-03-02 02:08:13 +00001146static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001147 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001148 UnixUnusedFd *p;
1149 UnixUnusedFd *pNext;
1150 for(p=pInode->pUnused; p; p=pNext){
1151 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001152 robust_close(pFile, p->fd, __LINE__);
1153 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001154 }
drh0e9365c2011-03-02 02:08:13 +00001155 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001156}
1157
1158/*
drh8af6c222010-05-14 12:43:01 +00001159** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001160**
1161** The mutex entered using the unixEnterMutex() function must be held
1162** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001163*/
danb0ac3e32010-06-16 10:55:42 +00001164static void releaseInodeInfo(unixFile *pFile){
1165 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001166 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001167 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001168 pInode->nRef--;
1169 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001170 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001171 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001172 if( pInode->pPrev ){
1173 assert( pInode->pPrev->pNext==pInode );
1174 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001175 }else{
drh8af6c222010-05-14 12:43:01 +00001176 assert( inodeList==pInode );
1177 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001178 }
drh8af6c222010-05-14 12:43:01 +00001179 if( pInode->pNext ){
1180 assert( pInode->pNext->pPrev==pInode );
1181 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001182 }
drh8af6c222010-05-14 12:43:01 +00001183 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001184 }
drhbbd42a62004-05-22 17:41:58 +00001185 }
1186}
1187
1188/*
drh8af6c222010-05-14 12:43:01 +00001189** Given a file descriptor, locate the unixInodeInfo object that
1190** describes that file descriptor. Create a new one if necessary. The
1191** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001192**
dan9359c7b2009-08-21 08:29:10 +00001193** The mutex entered using the unixEnterMutex() function must be held
1194** when this function is called.
1195**
drh6c7d5c52008-11-21 20:32:33 +00001196** Return an appropriate error code.
1197*/
drh8af6c222010-05-14 12:43:01 +00001198static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001199 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001200 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001201){
1202 int rc; /* System call return code */
1203 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001204 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1205 struct stat statbuf; /* Low-level file information */
1206 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001207
dan9359c7b2009-08-21 08:29:10 +00001208 assert( unixMutexHeld() );
1209
drh6c7d5c52008-11-21 20:32:33 +00001210 /* Get low-level information about the file that we can used to
1211 ** create a unique name for the file.
1212 */
1213 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001214 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001215 if( rc!=0 ){
1216 pFile->lastErrno = errno;
1217#ifdef EOVERFLOW
1218 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1219#endif
1220 return SQLITE_IOERR;
1221 }
1222
drheb0d74f2009-02-03 15:27:02 +00001223#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001224 /* On OS X on an msdos filesystem, the inode number is reported
1225 ** incorrectly for zero-size files. See ticket #3260. To work
1226 ** around this problem (we consider it a bug in OS X, not SQLite)
1227 ** we always increase the file size to 1 by writing a single byte
1228 ** prior to accessing the inode number. The one byte written is
1229 ** an ASCII 'S' character which also happens to be the first byte
1230 ** in the header of every SQLite database. In this way, if there
1231 ** is a race condition such that another thread has already populated
1232 ** the first page of the database, no damage is done.
1233 */
drh7ed97b92010-01-20 13:07:21 +00001234 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001235 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001236 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001237 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001238 return SQLITE_IOERR;
1239 }
drh99ab3b12011-03-02 15:09:07 +00001240 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001241 if( rc!=0 ){
1242 pFile->lastErrno = errno;
1243 return SQLITE_IOERR;
1244 }
1245 }
drheb0d74f2009-02-03 15:27:02 +00001246#endif
drh6c7d5c52008-11-21 20:32:33 +00001247
drh8af6c222010-05-14 12:43:01 +00001248 memset(&fileId, 0, sizeof(fileId));
1249 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001250#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001251 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001252#else
drh8af6c222010-05-14 12:43:01 +00001253 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001254#endif
drh8af6c222010-05-14 12:43:01 +00001255 pInode = inodeList;
1256 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1257 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001258 }
drh8af6c222010-05-14 12:43:01 +00001259 if( pInode==0 ){
1260 pInode = sqlite3_malloc( sizeof(*pInode) );
1261 if( pInode==0 ){
1262 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001263 }
drh8af6c222010-05-14 12:43:01 +00001264 memset(pInode, 0, sizeof(*pInode));
1265 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1266 pInode->nRef = 1;
1267 pInode->pNext = inodeList;
1268 pInode->pPrev = 0;
1269 if( inodeList ) inodeList->pPrev = pInode;
1270 inodeList = pInode;
1271 }else{
1272 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001273 }
drh8af6c222010-05-14 12:43:01 +00001274 *ppInode = pInode;
1275 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001276}
drh6c7d5c52008-11-21 20:32:33 +00001277
aswift5b1a2562008-08-22 00:22:35 +00001278
1279/*
danielk197713adf8a2004-06-03 16:08:41 +00001280** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001281** file by this or any other process. If such a lock is held, set *pResOut
1282** to a non-zero value otherwise *pResOut is set to zero. The return value
1283** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001284*/
danielk1977861f7452008-06-05 11:39:11 +00001285static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001286 int rc = SQLITE_OK;
1287 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001288 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001289
danielk1977861f7452008-06-05 11:39:11 +00001290 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1291
drh054889e2005-11-30 03:20:31 +00001292 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001293 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001294
1295 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001296 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001297 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001298 }
1299
drh2ac3ee92004-06-07 16:27:46 +00001300 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001301 */
danielk197709480a92009-02-09 05:32:32 +00001302#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001303 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001304 struct flock lock;
1305 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001306 lock.l_start = RESERVED_BYTE;
1307 lock.l_len = 1;
1308 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001309 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1310 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1311 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001312 } else if( lock.l_type!=F_UNLCK ){
1313 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001314 }
1315 }
danielk197709480a92009-02-09 05:32:32 +00001316#endif
danielk197713adf8a2004-06-03 16:08:41 +00001317
drh6c7d5c52008-11-21 20:32:33 +00001318 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001319 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001320
aswift5b1a2562008-08-22 00:22:35 +00001321 *pResOut = reserved;
1322 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001323}
1324
1325/*
drha7e61d82011-03-12 17:02:57 +00001326** Attempt to set a system-lock on the file pFile. The lock is
1327** described by pLock.
1328**
drh77197112011-03-15 19:08:48 +00001329** If the pFile was opened read/write from unix-excl, then the only lock
1330** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001331** the first time any lock is attempted. All subsequent system locking
1332** operations become no-ops. Locking operations still happen internally,
1333** in order to coordinate access between separate database connections
1334** within this process, but all of that is handled in memory and the
1335** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001336**
1337** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1338** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1339** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001340**
1341** Zero is returned if the call completes successfully, or -1 if a call
1342** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001343*/
1344static int unixFileLock(unixFile *pFile, struct flock *pLock){
1345 int rc;
drh3cb93392011-03-12 18:10:44 +00001346 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001347 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001348 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001349 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1350 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1351 ){
drh3cb93392011-03-12 18:10:44 +00001352 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001353 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001354 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001355 lock.l_whence = SEEK_SET;
1356 lock.l_start = SHARED_FIRST;
1357 lock.l_len = SHARED_SIZE;
1358 lock.l_type = F_WRLCK;
1359 rc = osFcntl(pFile->h, F_SETLK, &lock);
1360 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001361 pInode->bProcessLock = 1;
1362 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001363 }else{
1364 rc = 0;
1365 }
1366 }else{
1367 rc = osFcntl(pFile->h, F_SETLK, pLock);
1368 }
1369 return rc;
1370}
1371
1372/*
drh308c2a52010-05-14 11:30:18 +00001373** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001374** of the following:
1375**
drh2ac3ee92004-06-07 16:27:46 +00001376** (1) SHARED_LOCK
1377** (2) RESERVED_LOCK
1378** (3) PENDING_LOCK
1379** (4) EXCLUSIVE_LOCK
1380**
drhb3e04342004-06-08 00:47:47 +00001381** Sometimes when requesting one lock state, additional lock states
1382** are inserted in between. The locking might fail on one of the later
1383** transitions leaving the lock state different from what it started but
1384** still short of its goal. The following chart shows the allowed
1385** transitions and the inserted intermediate states:
1386**
1387** UNLOCKED -> SHARED
1388** SHARED -> RESERVED
1389** SHARED -> (PENDING) -> EXCLUSIVE
1390** RESERVED -> (PENDING) -> EXCLUSIVE
1391** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001392**
drha6abd042004-06-09 17:37:22 +00001393** This routine will only increase a lock. Use the sqlite3OsUnlock()
1394** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001395*/
drh308c2a52010-05-14 11:30:18 +00001396static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001397 /* The following describes the implementation of the various locks and
1398 ** lock transitions in terms of the POSIX advisory shared and exclusive
1399 ** lock primitives (called read-locks and write-locks below, to avoid
1400 ** confusion with SQLite lock names). The algorithms are complicated
1401 ** slightly in order to be compatible with windows systems simultaneously
1402 ** accessing the same database file, in case that is ever required.
1403 **
1404 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1405 ** byte', each single bytes at well known offsets, and the 'shared byte
1406 ** range', a range of 510 bytes at a well known offset.
1407 **
1408 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1409 ** byte'. If this is successful, a random byte from the 'shared byte
1410 ** range' is read-locked and the lock on the 'pending byte' released.
1411 **
danielk197790ba3bd2004-06-25 08:32:25 +00001412 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1413 ** A RESERVED lock is implemented by grabbing a write-lock on the
1414 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001415 **
1416 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001417 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1418 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1419 ** obtained, but existing SHARED locks are allowed to persist. A process
1420 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1421 ** This property is used by the algorithm for rolling back a journal file
1422 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001423 **
danielk197790ba3bd2004-06-25 08:32:25 +00001424 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1425 ** implemented by obtaining a write-lock on the entire 'shared byte
1426 ** range'. Since all other locks require a read-lock on one of the bytes
1427 ** within this range, this ensures that no other locks are held on the
1428 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001429 **
1430 ** The reason a single byte cannot be used instead of the 'shared byte
1431 ** range' is that some versions of windows do not support read-locks. By
1432 ** locking a random byte from a range, concurrent SHARED locks may exist
1433 ** even if the locking primitive used is always a write-lock.
1434 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001435 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001436 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001437 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001438 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001439 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001440
drh054889e2005-11-30 03:20:31 +00001441 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001442 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1443 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001444 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001445
1446 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001447 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001448 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001449 */
drh308c2a52010-05-14 11:30:18 +00001450 if( pFile->eFileLock>=eFileLock ){
1451 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1452 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001453 return SQLITE_OK;
1454 }
1455
drh0c2694b2009-09-03 16:23:44 +00001456 /* Make sure the locking sequence is correct.
1457 ** (1) We never move from unlocked to anything higher than shared lock.
1458 ** (2) SQLite never explicitly requests a pendig lock.
1459 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001460 */
drh308c2a52010-05-14 11:30:18 +00001461 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1462 assert( eFileLock!=PENDING_LOCK );
1463 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001464
drh8af6c222010-05-14 12:43:01 +00001465 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001466 */
drh6c7d5c52008-11-21 20:32:33 +00001467 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001468 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001469
danielk1977ad94b582007-08-20 06:44:22 +00001470 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001471 ** handle that precludes the requested lock, return BUSY.
1472 */
drh8af6c222010-05-14 12:43:01 +00001473 if( (pFile->eFileLock!=pInode->eFileLock &&
1474 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001475 ){
1476 rc = SQLITE_BUSY;
1477 goto end_lock;
1478 }
1479
1480 /* If a SHARED lock is requested, and some thread using this PID already
1481 ** has a SHARED or RESERVED lock, then increment reference counts and
1482 ** return SQLITE_OK.
1483 */
drh308c2a52010-05-14 11:30:18 +00001484 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001485 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001486 assert( eFileLock==SHARED_LOCK );
1487 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001488 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001489 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001490 pInode->nShared++;
1491 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001492 goto end_lock;
1493 }
1494
danielk19779a1d0ab2004-06-01 14:09:28 +00001495
drh3cde3bb2004-06-12 02:17:14 +00001496 /* A PENDING lock is needed before acquiring a SHARED lock and before
1497 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1498 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001499 */
drh0c2694b2009-09-03 16:23:44 +00001500 lock.l_len = 1L;
1501 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001502 if( eFileLock==SHARED_LOCK
1503 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001504 ){
drh308c2a52010-05-14 11:30:18 +00001505 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001506 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001507 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001508 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001509 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001510 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001511 pFile->lastErrno = tErrno;
1512 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001513 goto end_lock;
1514 }
drh3cde3bb2004-06-12 02:17:14 +00001515 }
1516
1517
1518 /* If control gets to this point, then actually go ahead and make
1519 ** operating system calls for the specified lock.
1520 */
drh308c2a52010-05-14 11:30:18 +00001521 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001522 assert( pInode->nShared==0 );
1523 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001524 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001525
drh2ac3ee92004-06-07 16:27:46 +00001526 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001527 lock.l_start = SHARED_FIRST;
1528 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001529 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001530 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001531 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001532 }
dan661d71a2011-03-30 19:08:03 +00001533
drh2ac3ee92004-06-07 16:27:46 +00001534 /* Drop the temporary PENDING lock */
1535 lock.l_start = PENDING_BYTE;
1536 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001537 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001538 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1539 /* This could happen with a network mount */
1540 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001541 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001542 }
dan661d71a2011-03-30 19:08:03 +00001543
1544 if( rc ){
1545 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001546 pFile->lastErrno = tErrno;
1547 }
dan661d71a2011-03-30 19:08:03 +00001548 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001549 }else{
drh308c2a52010-05-14 11:30:18 +00001550 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001551 pInode->nLock++;
1552 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001553 }
drh8af6c222010-05-14 12:43:01 +00001554 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001555 /* We are trying for an exclusive lock but another thread in this
1556 ** same process is still holding a shared lock. */
1557 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001558 }else{
drh3cde3bb2004-06-12 02:17:14 +00001559 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 ** assumed that there is a SHARED or greater lock on the file
1561 ** already.
1562 */
drh308c2a52010-05-14 11:30:18 +00001563 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001564 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001565
1566 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1567 if( eFileLock==RESERVED_LOCK ){
1568 lock.l_start = RESERVED_BYTE;
1569 lock.l_len = 1L;
1570 }else{
1571 lock.l_start = SHARED_FIRST;
1572 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001573 }
dan661d71a2011-03-30 19:08:03 +00001574
1575 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001576 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001577 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001578 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001579 pFile->lastErrno = tErrno;
1580 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001581 }
drhbbd42a62004-05-22 17:41:58 +00001582 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001583
drh8f941bc2009-01-14 23:03:40 +00001584
drhd3d8c042012-05-29 17:02:40 +00001585#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001586 /* Set up the transaction-counter change checking flags when
1587 ** transitioning from a SHARED to a RESERVED lock. The change
1588 ** from SHARED to RESERVED marks the beginning of a normal
1589 ** write operation (not a hot journal rollback).
1590 */
1591 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001592 && pFile->eFileLock<=SHARED_LOCK
1593 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001594 ){
1595 pFile->transCntrChng = 0;
1596 pFile->dbUpdate = 0;
1597 pFile->inNormalWrite = 1;
1598 }
1599#endif
1600
1601
danielk1977ecb2a962004-06-02 06:30:16 +00001602 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001603 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001604 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001605 }else if( eFileLock==EXCLUSIVE_LOCK ){
1606 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001607 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001608 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001609
1610end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001611 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001612 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1613 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001614 return rc;
1615}
1616
1617/*
dan08da86a2009-08-21 17:18:03 +00001618** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001619** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001620*/
1621static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001622 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001623 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001624 p->pNext = pInode->pUnused;
1625 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001626 pFile->h = -1;
1627 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001628}
1629
1630/*
drh308c2a52010-05-14 11:30:18 +00001631** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001632** must be either NO_LOCK or SHARED_LOCK.
1633**
1634** If the locking level of the file descriptor is already at or below
1635** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001636**
1637** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1638** the byte range is divided into 2 parts and the first part is unlocked then
1639** set to a read lock, then the other part is simply unlocked. This works
1640** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1641** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001642*/
drha7e61d82011-03-12 17:02:57 +00001643static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001644 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001645 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001646 struct flock lock;
1647 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001648
drh054889e2005-11-30 03:20:31 +00001649 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001650 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001651 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001652 getpid()));
drha6abd042004-06-09 17:37:22 +00001653
drh308c2a52010-05-14 11:30:18 +00001654 assert( eFileLock<=SHARED_LOCK );
1655 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001656 return SQLITE_OK;
1657 }
drh6c7d5c52008-11-21 20:32:33 +00001658 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001659 pInode = pFile->pInode;
1660 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001661 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001662 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001663
drhd3d8c042012-05-29 17:02:40 +00001664#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001665 /* When reducing a lock such that other processes can start
1666 ** reading the database file again, make sure that the
1667 ** transaction counter was updated if any part of the database
1668 ** file changed. If the transaction counter is not updated,
1669 ** other connections to the same file might not realize that
1670 ** the file has changed and hence might not know to flush their
1671 ** cache. The use of a stale cache can lead to database corruption.
1672 */
drh8f941bc2009-01-14 23:03:40 +00001673 pFile->inNormalWrite = 0;
1674#endif
1675
drh7ed97b92010-01-20 13:07:21 +00001676 /* downgrading to a shared lock on NFS involves clearing the write lock
1677 ** before establishing the readlock - to avoid a race condition we downgrade
1678 ** the lock in 2 blocks, so that part of the range will be covered by a
1679 ** write lock until the rest is covered by a read lock:
1680 ** 1: [WWWWW]
1681 ** 2: [....W]
1682 ** 3: [RRRRW]
1683 ** 4: [RRRR.]
1684 */
drh308c2a52010-05-14 11:30:18 +00001685 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001686
1687#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001688 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001689 assert( handleNFSUnlock==0 );
1690#endif
1691#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001692 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001693 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001694 off_t divSize = SHARED_SIZE - 1;
1695
1696 lock.l_type = F_UNLCK;
1697 lock.l_whence = SEEK_SET;
1698 lock.l_start = SHARED_FIRST;
1699 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001700 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001701 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001702 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001703 if( IS_LOCK_ERROR(rc) ){
1704 pFile->lastErrno = tErrno;
1705 }
1706 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001707 }
drh7ed97b92010-01-20 13:07:21 +00001708 lock.l_type = F_RDLCK;
1709 lock.l_whence = SEEK_SET;
1710 lock.l_start = SHARED_FIRST;
1711 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001712 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001713 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001714 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1715 if( IS_LOCK_ERROR(rc) ){
1716 pFile->lastErrno = tErrno;
1717 }
1718 goto end_unlock;
1719 }
1720 lock.l_type = F_UNLCK;
1721 lock.l_whence = SEEK_SET;
1722 lock.l_start = SHARED_FIRST+divSize;
1723 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001724 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001725 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001726 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001727 if( IS_LOCK_ERROR(rc) ){
1728 pFile->lastErrno = tErrno;
1729 }
1730 goto end_unlock;
1731 }
drh30f776f2011-02-25 03:25:07 +00001732 }else
1733#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1734 {
drh7ed97b92010-01-20 13:07:21 +00001735 lock.l_type = F_RDLCK;
1736 lock.l_whence = SEEK_SET;
1737 lock.l_start = SHARED_FIRST;
1738 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001739 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001740 /* In theory, the call to unixFileLock() cannot fail because another
1741 ** process is holding an incompatible lock. If it does, this
1742 ** indicates that the other process is not following the locking
1743 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1744 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1745 ** an assert to fail). */
1746 rc = SQLITE_IOERR_RDLOCK;
1747 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001748 goto end_unlock;
1749 }
drh9c105bb2004-10-02 20:38:28 +00001750 }
1751 }
drhbbd42a62004-05-22 17:41:58 +00001752 lock.l_type = F_UNLCK;
1753 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001754 lock.l_start = PENDING_BYTE;
1755 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001756 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001757 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001758 }else{
danea83bc62011-04-01 11:56:32 +00001759 rc = SQLITE_IOERR_UNLOCK;
1760 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001761 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001762 }
drhbbd42a62004-05-22 17:41:58 +00001763 }
drh308c2a52010-05-14 11:30:18 +00001764 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001765 /* Decrement the shared lock counter. Release the lock using an
1766 ** OS call only when all threads in this same process have released
1767 ** the lock.
1768 */
drh8af6c222010-05-14 12:43:01 +00001769 pInode->nShared--;
1770 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001771 lock.l_type = F_UNLCK;
1772 lock.l_whence = SEEK_SET;
1773 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001774 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001775 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001776 }else{
danea83bc62011-04-01 11:56:32 +00001777 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001778 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001779 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001780 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001781 }
drha6abd042004-06-09 17:37:22 +00001782 }
1783
drhbbd42a62004-05-22 17:41:58 +00001784 /* Decrement the count of locks against this same file. When the
1785 ** count reaches zero, close any other file descriptors whose close
1786 ** was deferred because of outstanding locks.
1787 */
drh8af6c222010-05-14 12:43:01 +00001788 pInode->nLock--;
1789 assert( pInode->nLock>=0 );
1790 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001791 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001792 }
1793 }
drhf2f105d2012-08-20 15:53:54 +00001794
aswift5b1a2562008-08-22 00:22:35 +00001795end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001796 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001797 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001798 return rc;
drhbbd42a62004-05-22 17:41:58 +00001799}
1800
1801/*
drh308c2a52010-05-14 11:30:18 +00001802** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001803** must be either NO_LOCK or SHARED_LOCK.
1804**
1805** If the locking level of the file descriptor is already at or below
1806** the requested locking level, this routine is a no-op.
1807*/
drh308c2a52010-05-14 11:30:18 +00001808static int unixUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00001809 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001810}
1811
1812/*
danielk1977e339d652008-06-28 11:23:00 +00001813** This function performs the parts of the "close file" operation
1814** common to all locking schemes. It closes the directory and file
1815** handles, if they are valid, and sets all fields of the unixFile
1816** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001817**
1818** It is *not* necessary to hold the mutex when this routine is called,
1819** even on VxWorks. A mutex will be acquired on VxWorks by the
1820** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001821*/
1822static int closeUnixFile(sqlite3_file *id){
1823 unixFile *pFile = (unixFile*)id;
dan661d71a2011-03-30 19:08:03 +00001824 if( pFile->h>=0 ){
1825 robust_close(pFile, pFile->h, __LINE__);
1826 pFile->h = -1;
1827 }
1828#if OS_VXWORKS
1829 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001830 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001831 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001832 }
1833 vxworksReleaseFileId(pFile->pId);
1834 pFile->pId = 0;
1835 }
1836#endif
1837 OSTRACE(("CLOSE %-3d\n", pFile->h));
1838 OpenCounter(-1);
1839 sqlite3_free(pFile->pUnused);
1840 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001841 return SQLITE_OK;
1842}
1843
1844/*
danielk1977e3026632004-06-22 11:29:02 +00001845** Close a file.
1846*/
danielk197762079062007-08-15 17:08:46 +00001847static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001848 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001849 unixFile *pFile = (unixFile *)id;
1850 unixUnlock(id, NO_LOCK);
1851 unixEnterMutex();
1852
1853 /* unixFile.pInode is always valid here. Otherwise, a different close
1854 ** routine (e.g. nolockClose()) would be called instead.
1855 */
1856 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1857 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1858 /* If there are outstanding locks, do not actually close the file just
1859 ** yet because that would clear those locks. Instead, add the file
1860 ** descriptor to pInode->pUnused list. It will be automatically closed
1861 ** when the last lock is cleared.
1862 */
1863 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001864 }
dan661d71a2011-03-30 19:08:03 +00001865 releaseInodeInfo(pFile);
1866 rc = closeUnixFile(id);
1867 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001868 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001869}
1870
drh734c9862008-11-28 15:37:20 +00001871/************** End of the posix advisory lock implementation *****************
1872******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001873
drh734c9862008-11-28 15:37:20 +00001874/******************************************************************************
1875****************************** No-op Locking **********************************
1876**
1877** Of the various locking implementations available, this is by far the
1878** simplest: locking is ignored. No attempt is made to lock the database
1879** file for reading or writing.
1880**
1881** This locking mode is appropriate for use on read-only databases
1882** (ex: databases that are burned into CD-ROM, for example.) It can
1883** also be used if the application employs some external mechanism to
1884** prevent simultaneous access of the same database by two or more
1885** database connections. But there is a serious risk of database
1886** corruption if this locking mode is used in situations where multiple
1887** database connections are accessing the same database file at the same
1888** time and one or more of those connections are writing.
1889*/
drhbfe66312006-10-03 17:40:40 +00001890
drh734c9862008-11-28 15:37:20 +00001891static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1892 UNUSED_PARAMETER(NotUsed);
1893 *pResOut = 0;
1894 return SQLITE_OK;
1895}
drh734c9862008-11-28 15:37:20 +00001896static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1897 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1898 return SQLITE_OK;
1899}
drh734c9862008-11-28 15:37:20 +00001900static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1901 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1902 return SQLITE_OK;
1903}
1904
1905/*
drh9b35ea62008-11-29 02:20:26 +00001906** Close the file.
drh734c9862008-11-28 15:37:20 +00001907*/
1908static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001909 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00001910}
1911
1912/******************* End of the no-op lock implementation *********************
1913******************************************************************************/
1914
1915/******************************************************************************
1916************************* Begin dot-file Locking ******************************
1917**
drh0c2694b2009-09-03 16:23:44 +00001918** The dotfile locking implementation uses the existance of separate lock
drh9ef6bc42011-11-04 02:24:02 +00001919** files (really a directory) to control access to the database. This works
1920** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00001921**
1922** (1) There is zero concurrency. A single reader blocks all other
1923** connections from reading or writing the database.
1924**
1925** (2) An application crash or power loss can leave stale lock files
1926** sitting around that need to be cleared manually.
1927**
1928** Nevertheless, a dotlock is an appropriate locking mode for use if no
1929** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00001930**
drh9ef6bc42011-11-04 02:24:02 +00001931** Dotfile locking works by creating a subdirectory in the same directory as
1932** the database and with the same name but with a ".lock" extension added.
1933** The existance of a lock directory implies an EXCLUSIVE lock. All other
1934** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00001935*/
1936
1937/*
1938** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00001939** lock directory.
drh734c9862008-11-28 15:37:20 +00001940*/
1941#define DOTLOCK_SUFFIX ".lock"
1942
drh7708e972008-11-29 00:56:52 +00001943/*
1944** This routine checks if there is a RESERVED lock held on the specified
1945** file by this or any other process. If such a lock is held, set *pResOut
1946** to a non-zero value otherwise *pResOut is set to zero. The return value
1947** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1948**
1949** In dotfile locking, either a lock exists or it does not. So in this
1950** variation of CheckReservedLock(), *pResOut is set to true if any lock
1951** is held on the file and false if the file is unlocked.
1952*/
drh734c9862008-11-28 15:37:20 +00001953static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1954 int rc = SQLITE_OK;
1955 int reserved = 0;
1956 unixFile *pFile = (unixFile*)id;
1957
1958 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1959
1960 assert( pFile );
1961
1962 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00001963 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00001964 /* Either this connection or some other connection in the same process
1965 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00001966 reserved = 1;
drh7708e972008-11-29 00:56:52 +00001967 }else{
1968 /* The lock is held if and only if the lockfile exists */
1969 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00001970 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00001971 }
drh308c2a52010-05-14 11:30:18 +00001972 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00001973 *pResOut = reserved;
1974 return rc;
1975}
1976
drh7708e972008-11-29 00:56:52 +00001977/*
drh308c2a52010-05-14 11:30:18 +00001978** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00001979** of the following:
1980**
1981** (1) SHARED_LOCK
1982** (2) RESERVED_LOCK
1983** (3) PENDING_LOCK
1984** (4) EXCLUSIVE_LOCK
1985**
1986** Sometimes when requesting one lock state, additional lock states
1987** are inserted in between. The locking might fail on one of the later
1988** transitions leaving the lock state different from what it started but
1989** still short of its goal. The following chart shows the allowed
1990** transitions and the inserted intermediate states:
1991**
1992** UNLOCKED -> SHARED
1993** SHARED -> RESERVED
1994** SHARED -> (PENDING) -> EXCLUSIVE
1995** RESERVED -> (PENDING) -> EXCLUSIVE
1996** PENDING -> EXCLUSIVE
1997**
1998** This routine will only increase a lock. Use the sqlite3OsUnlock()
1999** routine to lower a locking level.
2000**
2001** With dotfile locking, we really only support state (4): EXCLUSIVE.
2002** But we track the other locking levels internally.
2003*/
drh308c2a52010-05-14 11:30:18 +00002004static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002005 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002006 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002007 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002008
drh7708e972008-11-29 00:56:52 +00002009
2010 /* If we have any lock, then the lock file already exists. All we have
2011 ** to do is adjust our internal record of the lock level.
2012 */
drh308c2a52010-05-14 11:30:18 +00002013 if( pFile->eFileLock > NO_LOCK ){
2014 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002015 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002016#ifdef HAVE_UTIME
2017 utime(zLockFile, NULL);
2018#else
drh734c9862008-11-28 15:37:20 +00002019 utimes(zLockFile, NULL);
2020#endif
drh7708e972008-11-29 00:56:52 +00002021 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002022 }
2023
2024 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002025 rc = osMkdir(zLockFile, 0777);
2026 if( rc<0 ){
2027 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002028 int tErrno = errno;
2029 if( EEXIST == tErrno ){
2030 rc = SQLITE_BUSY;
2031 } else {
2032 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2033 if( IS_LOCK_ERROR(rc) ){
2034 pFile->lastErrno = tErrno;
2035 }
2036 }
drh7708e972008-11-29 00:56:52 +00002037 return rc;
drh734c9862008-11-28 15:37:20 +00002038 }
drh734c9862008-11-28 15:37:20 +00002039
2040 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002041 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002042 return rc;
2043}
2044
drh7708e972008-11-29 00:56:52 +00002045/*
drh308c2a52010-05-14 11:30:18 +00002046** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002047** must be either NO_LOCK or SHARED_LOCK.
2048**
2049** If the locking level of the file descriptor is already at or below
2050** the requested locking level, this routine is a no-op.
2051**
2052** When the locking level reaches NO_LOCK, delete the lock file.
2053*/
drh308c2a52010-05-14 11:30:18 +00002054static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002055 unixFile *pFile = (unixFile*)id;
2056 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002057 int rc;
drh734c9862008-11-28 15:37:20 +00002058
2059 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002060 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002061 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002062 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002063
2064 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002065 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002066 return SQLITE_OK;
2067 }
drh7708e972008-11-29 00:56:52 +00002068
2069 /* To downgrade to shared, simply update our internal notion of the
2070 ** lock state. No need to mess with the file on disk.
2071 */
drh308c2a52010-05-14 11:30:18 +00002072 if( eFileLock==SHARED_LOCK ){
2073 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002074 return SQLITE_OK;
2075 }
2076
drh7708e972008-11-29 00:56:52 +00002077 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002078 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002079 rc = osRmdir(zLockFile);
2080 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2081 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002082 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002083 rc = 0;
drh734c9862008-11-28 15:37:20 +00002084 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002085 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002086 }
2087 if( IS_LOCK_ERROR(rc) ){
2088 pFile->lastErrno = tErrno;
2089 }
2090 return rc;
2091 }
drh308c2a52010-05-14 11:30:18 +00002092 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002093 return SQLITE_OK;
2094}
2095
2096/*
drh9b35ea62008-11-29 02:20:26 +00002097** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002098*/
2099static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002100 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002101 if( id ){
2102 unixFile *pFile = (unixFile*)id;
2103 dotlockUnlock(id, NO_LOCK);
2104 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002105 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002106 }
drh734c9862008-11-28 15:37:20 +00002107 return rc;
2108}
2109/****************** End of the dot-file lock implementation *******************
2110******************************************************************************/
2111
2112/******************************************************************************
2113************************** Begin flock Locking ********************************
2114**
2115** Use the flock() system call to do file locking.
2116**
drh6b9d6dd2008-12-03 19:34:47 +00002117** flock() locking is like dot-file locking in that the various
2118** fine-grain locking levels supported by SQLite are collapsed into
2119** a single exclusive lock. In other words, SHARED, RESERVED, and
2120** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2121** still works when you do this, but concurrency is reduced since
2122** only a single process can be reading the database at a time.
2123**
drh734c9862008-11-28 15:37:20 +00002124** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2125** compiling for VXWORKS.
2126*/
2127#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002128
drh6b9d6dd2008-12-03 19:34:47 +00002129/*
drhff812312011-02-23 13:33:46 +00002130** Retry flock() calls that fail with EINTR
2131*/
2132#ifdef EINTR
2133static int robust_flock(int fd, int op){
2134 int rc;
2135 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2136 return rc;
2137}
2138#else
drh5c819272011-02-23 14:00:12 +00002139# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002140#endif
2141
2142
2143/*
drh6b9d6dd2008-12-03 19:34:47 +00002144** This routine checks if there is a RESERVED lock held on the specified
2145** file by this or any other process. If such a lock is held, set *pResOut
2146** to a non-zero value otherwise *pResOut is set to zero. The return value
2147** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2148*/
drh734c9862008-11-28 15:37:20 +00002149static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2150 int rc = SQLITE_OK;
2151 int reserved = 0;
2152 unixFile *pFile = (unixFile*)id;
2153
2154 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2155
2156 assert( pFile );
2157
2158 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002159 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002160 reserved = 1;
2161 }
2162
2163 /* Otherwise see if some other process holds it. */
2164 if( !reserved ){
2165 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002166 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002167 if( !lrc ){
2168 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002169 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002170 if ( lrc ) {
2171 int tErrno = errno;
2172 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002173 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002174 if( IS_LOCK_ERROR(lrc) ){
2175 pFile->lastErrno = tErrno;
2176 rc = lrc;
2177 }
2178 }
2179 } else {
2180 int tErrno = errno;
2181 reserved = 1;
2182 /* someone else might have it reserved */
2183 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2184 if( IS_LOCK_ERROR(lrc) ){
2185 pFile->lastErrno = tErrno;
2186 rc = lrc;
2187 }
2188 }
2189 }
drh308c2a52010-05-14 11:30:18 +00002190 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002191
2192#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2193 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2194 rc = SQLITE_OK;
2195 reserved=1;
2196 }
2197#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2198 *pResOut = reserved;
2199 return rc;
2200}
2201
drh6b9d6dd2008-12-03 19:34:47 +00002202/*
drh308c2a52010-05-14 11:30:18 +00002203** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002204** of the following:
2205**
2206** (1) SHARED_LOCK
2207** (2) RESERVED_LOCK
2208** (3) PENDING_LOCK
2209** (4) EXCLUSIVE_LOCK
2210**
2211** Sometimes when requesting one lock state, additional lock states
2212** are inserted in between. The locking might fail on one of the later
2213** transitions leaving the lock state different from what it started but
2214** still short of its goal. The following chart shows the allowed
2215** transitions and the inserted intermediate states:
2216**
2217** UNLOCKED -> SHARED
2218** SHARED -> RESERVED
2219** SHARED -> (PENDING) -> EXCLUSIVE
2220** RESERVED -> (PENDING) -> EXCLUSIVE
2221** PENDING -> EXCLUSIVE
2222**
2223** flock() only really support EXCLUSIVE locks. We track intermediate
2224** lock states in the sqlite3_file structure, but all locks SHARED or
2225** above are really EXCLUSIVE locks and exclude all other processes from
2226** access the file.
2227**
2228** This routine will only increase a lock. Use the sqlite3OsUnlock()
2229** routine to lower a locking level.
2230*/
drh308c2a52010-05-14 11:30:18 +00002231static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002232 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002233 unixFile *pFile = (unixFile*)id;
2234
2235 assert( pFile );
2236
2237 /* if we already have a lock, it is exclusive.
2238 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002239 if (pFile->eFileLock > NO_LOCK) {
2240 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002241 return SQLITE_OK;
2242 }
2243
2244 /* grab an exclusive lock */
2245
drhff812312011-02-23 13:33:46 +00002246 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002247 int tErrno = errno;
2248 /* didn't get, must be busy */
2249 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2250 if( IS_LOCK_ERROR(rc) ){
2251 pFile->lastErrno = tErrno;
2252 }
2253 } else {
2254 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002255 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002256 }
drh308c2a52010-05-14 11:30:18 +00002257 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2258 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002259#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2260 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2261 rc = SQLITE_BUSY;
2262 }
2263#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2264 return rc;
2265}
2266
drh6b9d6dd2008-12-03 19:34:47 +00002267
2268/*
drh308c2a52010-05-14 11:30:18 +00002269** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002270** must be either NO_LOCK or SHARED_LOCK.
2271**
2272** If the locking level of the file descriptor is already at or below
2273** the requested locking level, this routine is a no-op.
2274*/
drh308c2a52010-05-14 11:30:18 +00002275static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002276 unixFile *pFile = (unixFile*)id;
2277
2278 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002279 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2280 pFile->eFileLock, getpid()));
2281 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002282
2283 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002284 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002285 return SQLITE_OK;
2286 }
2287
2288 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002289 if (eFileLock==SHARED_LOCK) {
2290 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002291 return SQLITE_OK;
2292 }
2293
2294 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002295 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002296#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002297 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002298#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002299 return SQLITE_IOERR_UNLOCK;
2300 }else{
drh308c2a52010-05-14 11:30:18 +00002301 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002302 return SQLITE_OK;
2303 }
2304}
2305
2306/*
2307** Close a file.
2308*/
2309static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002310 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002311 if( id ){
2312 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002313 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002314 }
drh5a05be12012-10-09 18:51:44 +00002315 return rc;
drh734c9862008-11-28 15:37:20 +00002316}
2317
2318#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2319
2320/******************* End of the flock lock implementation *********************
2321******************************************************************************/
2322
2323/******************************************************************************
2324************************ Begin Named Semaphore Locking ************************
2325**
2326** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002327**
2328** Semaphore locking is like dot-lock and flock in that it really only
2329** supports EXCLUSIVE locking. Only a single process can read or write
2330** the database file at a time. This reduces potential concurrency, but
2331** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002332*/
2333#if OS_VXWORKS
2334
drh6b9d6dd2008-12-03 19:34:47 +00002335/*
2336** This routine checks if there is a RESERVED lock held on the specified
2337** file by this or any other process. If such a lock is held, set *pResOut
2338** to a non-zero value otherwise *pResOut is set to zero. The return value
2339** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2340*/
drh734c9862008-11-28 15:37:20 +00002341static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2342 int rc = SQLITE_OK;
2343 int reserved = 0;
2344 unixFile *pFile = (unixFile*)id;
2345
2346 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2347
2348 assert( pFile );
2349
2350 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002351 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002352 reserved = 1;
2353 }
2354
2355 /* Otherwise see if some other process holds it. */
2356 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002357 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002358 struct stat statBuf;
2359
2360 if( sem_trywait(pSem)==-1 ){
2361 int tErrno = errno;
2362 if( EAGAIN != tErrno ){
2363 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2364 pFile->lastErrno = tErrno;
2365 } else {
2366 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002367 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002368 }
2369 }else{
2370 /* we could have it if we want it */
2371 sem_post(pSem);
2372 }
2373 }
drh308c2a52010-05-14 11:30:18 +00002374 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002375
2376 *pResOut = reserved;
2377 return rc;
2378}
2379
drh6b9d6dd2008-12-03 19:34:47 +00002380/*
drh308c2a52010-05-14 11:30:18 +00002381** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002382** of the following:
2383**
2384** (1) SHARED_LOCK
2385** (2) RESERVED_LOCK
2386** (3) PENDING_LOCK
2387** (4) EXCLUSIVE_LOCK
2388**
2389** Sometimes when requesting one lock state, additional lock states
2390** are inserted in between. The locking might fail on one of the later
2391** transitions leaving the lock state different from what it started but
2392** still short of its goal. The following chart shows the allowed
2393** transitions and the inserted intermediate states:
2394**
2395** UNLOCKED -> SHARED
2396** SHARED -> RESERVED
2397** SHARED -> (PENDING) -> EXCLUSIVE
2398** RESERVED -> (PENDING) -> EXCLUSIVE
2399** PENDING -> EXCLUSIVE
2400**
2401** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2402** lock states in the sqlite3_file structure, but all locks SHARED or
2403** above are really EXCLUSIVE locks and exclude all other processes from
2404** access the file.
2405**
2406** This routine will only increase a lock. Use the sqlite3OsUnlock()
2407** routine to lower a locking level.
2408*/
drh308c2a52010-05-14 11:30:18 +00002409static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002410 unixFile *pFile = (unixFile*)id;
2411 int fd;
drh8af6c222010-05-14 12:43:01 +00002412 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002413 int rc = SQLITE_OK;
2414
2415 /* if we already have a lock, it is exclusive.
2416 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002417 if (pFile->eFileLock > NO_LOCK) {
2418 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002419 rc = SQLITE_OK;
2420 goto sem_end_lock;
2421 }
2422
2423 /* lock semaphore now but bail out when already locked. */
2424 if( sem_trywait(pSem)==-1 ){
2425 rc = SQLITE_BUSY;
2426 goto sem_end_lock;
2427 }
2428
2429 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002430 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002431
2432 sem_end_lock:
2433 return rc;
2434}
2435
drh6b9d6dd2008-12-03 19:34:47 +00002436/*
drh308c2a52010-05-14 11:30:18 +00002437** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002438** must be either NO_LOCK or SHARED_LOCK.
2439**
2440** If the locking level of the file descriptor is already at or below
2441** the requested locking level, this routine is a no-op.
2442*/
drh308c2a52010-05-14 11:30:18 +00002443static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002444 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002445 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002446
2447 assert( pFile );
2448 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002449 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002450 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002451 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002452
2453 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002454 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002455 return SQLITE_OK;
2456 }
2457
2458 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002459 if (eFileLock==SHARED_LOCK) {
2460 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002461 return SQLITE_OK;
2462 }
2463
2464 /* no, really unlock. */
2465 if ( sem_post(pSem)==-1 ) {
2466 int rc, tErrno = errno;
2467 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2468 if( IS_LOCK_ERROR(rc) ){
2469 pFile->lastErrno = tErrno;
2470 }
2471 return rc;
2472 }
drh308c2a52010-05-14 11:30:18 +00002473 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002474 return SQLITE_OK;
2475}
2476
2477/*
2478 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002479 */
drh734c9862008-11-28 15:37:20 +00002480static int semClose(sqlite3_file *id) {
2481 if( id ){
2482 unixFile *pFile = (unixFile*)id;
2483 semUnlock(id, NO_LOCK);
2484 assert( pFile );
2485 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002486 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002487 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002488 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002489 }
2490 return SQLITE_OK;
2491}
2492
2493#endif /* OS_VXWORKS */
2494/*
2495** Named semaphore locking is only available on VxWorks.
2496**
2497*************** End of the named semaphore lock implementation ****************
2498******************************************************************************/
2499
2500
2501/******************************************************************************
2502*************************** Begin AFP Locking *********************************
2503**
2504** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2505** on Apple Macintosh computers - both OS9 and OSX.
2506**
2507** Third-party implementations of AFP are available. But this code here
2508** only works on OSX.
2509*/
2510
drhd2cb50b2009-01-09 21:41:17 +00002511#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002512/*
2513** The afpLockingContext structure contains all afp lock specific state
2514*/
drhbfe66312006-10-03 17:40:40 +00002515typedef struct afpLockingContext afpLockingContext;
2516struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002517 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002518 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002519};
2520
2521struct ByteRangeLockPB2
2522{
2523 unsigned long long offset; /* offset to first byte to lock */
2524 unsigned long long length; /* nbr of bytes to lock */
2525 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2526 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2527 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2528 int fd; /* file desc to assoc this lock with */
2529};
2530
drhfd131da2007-08-07 17:13:03 +00002531#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002532
drh6b9d6dd2008-12-03 19:34:47 +00002533/*
2534** This is a utility for setting or clearing a bit-range lock on an
2535** AFP filesystem.
2536**
2537** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2538*/
2539static int afpSetLock(
2540 const char *path, /* Name of the file to be locked or unlocked */
2541 unixFile *pFile, /* Open file descriptor on path */
2542 unsigned long long offset, /* First byte to be locked */
2543 unsigned long long length, /* Number of bytes to lock */
2544 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002545){
drh6b9d6dd2008-12-03 19:34:47 +00002546 struct ByteRangeLockPB2 pb;
2547 int err;
drhbfe66312006-10-03 17:40:40 +00002548
2549 pb.unLockFlag = setLockFlag ? 0 : 1;
2550 pb.startEndFlag = 0;
2551 pb.offset = offset;
2552 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002553 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002554
drh308c2a52010-05-14 11:30:18 +00002555 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002556 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002557 offset, length));
drhbfe66312006-10-03 17:40:40 +00002558 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2559 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002560 int rc;
2561 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002562 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2563 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002564#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2565 rc = SQLITE_BUSY;
2566#else
drh734c9862008-11-28 15:37:20 +00002567 rc = sqliteErrorFromPosixError(tErrno,
2568 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002569#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002570 if( IS_LOCK_ERROR(rc) ){
2571 pFile->lastErrno = tErrno;
2572 }
2573 return rc;
drhbfe66312006-10-03 17:40:40 +00002574 } else {
aswift5b1a2562008-08-22 00:22:35 +00002575 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002576 }
2577}
2578
drh6b9d6dd2008-12-03 19:34:47 +00002579/*
2580** This routine checks if there is a RESERVED lock held on the specified
2581** file by this or any other process. If such a lock is held, set *pResOut
2582** to a non-zero value otherwise *pResOut is set to zero. The return value
2583** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2584*/
danielk1977e339d652008-06-28 11:23:00 +00002585static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002586 int rc = SQLITE_OK;
2587 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002588 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002589 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002590
aswift5b1a2562008-08-22 00:22:35 +00002591 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2592
2593 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002594 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002595 if( context->reserved ){
2596 *pResOut = 1;
2597 return SQLITE_OK;
2598 }
drh8af6c222010-05-14 12:43:01 +00002599 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002600
2601 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002602 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002603 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002604 }
2605
2606 /* Otherwise see if some other process holds it.
2607 */
aswift5b1a2562008-08-22 00:22:35 +00002608 if( !reserved ){
2609 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002610 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002611 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002612 /* if we succeeded in taking the reserved lock, unlock it to restore
2613 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002614 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002615 } else {
2616 /* if we failed to get the lock then someone else must have it */
2617 reserved = 1;
2618 }
2619 if( IS_LOCK_ERROR(lrc) ){
2620 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002621 }
2622 }
drhbfe66312006-10-03 17:40:40 +00002623
drh7ed97b92010-01-20 13:07:21 +00002624 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002625 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002626
2627 *pResOut = reserved;
2628 return rc;
drhbfe66312006-10-03 17:40:40 +00002629}
2630
drh6b9d6dd2008-12-03 19:34:47 +00002631/*
drh308c2a52010-05-14 11:30:18 +00002632** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002633** of the following:
2634**
2635** (1) SHARED_LOCK
2636** (2) RESERVED_LOCK
2637** (3) PENDING_LOCK
2638** (4) EXCLUSIVE_LOCK
2639**
2640** Sometimes when requesting one lock state, additional lock states
2641** are inserted in between. The locking might fail on one of the later
2642** transitions leaving the lock state different from what it started but
2643** still short of its goal. The following chart shows the allowed
2644** transitions and the inserted intermediate states:
2645**
2646** UNLOCKED -> SHARED
2647** SHARED -> RESERVED
2648** SHARED -> (PENDING) -> EXCLUSIVE
2649** RESERVED -> (PENDING) -> EXCLUSIVE
2650** PENDING -> EXCLUSIVE
2651**
2652** This routine will only increase a lock. Use the sqlite3OsUnlock()
2653** routine to lower a locking level.
2654*/
drh308c2a52010-05-14 11:30:18 +00002655static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002656 int rc = SQLITE_OK;
2657 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002658 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002659 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002660
2661 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002662 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2663 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002664 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002665
drhbfe66312006-10-03 17:40:40 +00002666 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002667 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002668 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002669 */
drh308c2a52010-05-14 11:30:18 +00002670 if( pFile->eFileLock>=eFileLock ){
2671 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2672 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002673 return SQLITE_OK;
2674 }
2675
2676 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002677 ** (1) We never move from unlocked to anything higher than shared lock.
2678 ** (2) SQLite never explicitly requests a pendig lock.
2679 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002680 */
drh308c2a52010-05-14 11:30:18 +00002681 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2682 assert( eFileLock!=PENDING_LOCK );
2683 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002684
drh8af6c222010-05-14 12:43:01 +00002685 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002686 */
drh6c7d5c52008-11-21 20:32:33 +00002687 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002688 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002689
2690 /* If some thread using this PID has a lock via a different unixFile*
2691 ** handle that precludes the requested lock, return BUSY.
2692 */
drh8af6c222010-05-14 12:43:01 +00002693 if( (pFile->eFileLock!=pInode->eFileLock &&
2694 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002695 ){
2696 rc = SQLITE_BUSY;
2697 goto afp_end_lock;
2698 }
2699
2700 /* If a SHARED lock is requested, and some thread using this PID already
2701 ** has a SHARED or RESERVED lock, then increment reference counts and
2702 ** return SQLITE_OK.
2703 */
drh308c2a52010-05-14 11:30:18 +00002704 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002705 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002706 assert( eFileLock==SHARED_LOCK );
2707 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002708 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002709 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002710 pInode->nShared++;
2711 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002712 goto afp_end_lock;
2713 }
drhbfe66312006-10-03 17:40:40 +00002714
2715 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002716 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2717 ** be released.
2718 */
drh308c2a52010-05-14 11:30:18 +00002719 if( eFileLock==SHARED_LOCK
2720 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002721 ){
2722 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002723 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002724 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002725 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002726 goto afp_end_lock;
2727 }
2728 }
2729
2730 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002731 ** operating system calls for the specified lock.
2732 */
drh308c2a52010-05-14 11:30:18 +00002733 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002734 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002735 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002736
drh8af6c222010-05-14 12:43:01 +00002737 assert( pInode->nShared==0 );
2738 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002739
2740 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002741 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002742 /* note that the quality of the randomness doesn't matter that much */
2743 lk = random();
drh8af6c222010-05-14 12:43:01 +00002744 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002745 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002746 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002747 if( IS_LOCK_ERROR(lrc1) ){
2748 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002749 }
aswift5b1a2562008-08-22 00:22:35 +00002750 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002751 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002752
aswift5b1a2562008-08-22 00:22:35 +00002753 if( IS_LOCK_ERROR(lrc1) ) {
2754 pFile->lastErrno = lrc1Errno;
2755 rc = lrc1;
2756 goto afp_end_lock;
2757 } else if( IS_LOCK_ERROR(lrc2) ){
2758 rc = lrc2;
2759 goto afp_end_lock;
2760 } else if( lrc1 != SQLITE_OK ) {
2761 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002762 } else {
drh308c2a52010-05-14 11:30:18 +00002763 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002764 pInode->nLock++;
2765 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002766 }
drh8af6c222010-05-14 12:43:01 +00002767 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002768 /* We are trying for an exclusive lock but another thread in this
2769 ** same process is still holding a shared lock. */
2770 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002771 }else{
2772 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2773 ** assumed that there is a SHARED or greater lock on the file
2774 ** already.
2775 */
2776 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002777 assert( 0!=pFile->eFileLock );
2778 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002779 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002780 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002781 if( !failed ){
2782 context->reserved = 1;
2783 }
drhbfe66312006-10-03 17:40:40 +00002784 }
drh308c2a52010-05-14 11:30:18 +00002785 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002786 /* Acquire an EXCLUSIVE lock */
2787
2788 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002789 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002790 */
drh6b9d6dd2008-12-03 19:34:47 +00002791 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002792 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002793 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002794 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002795 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002796 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002797 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002798 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002799 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2800 ** a critical I/O error
2801 */
2802 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2803 SQLITE_IOERR_LOCK;
2804 goto afp_end_lock;
2805 }
2806 }else{
aswift5b1a2562008-08-22 00:22:35 +00002807 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002808 }
2809 }
aswift5b1a2562008-08-22 00:22:35 +00002810 if( failed ){
2811 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002812 }
2813 }
2814
2815 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002816 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002817 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002818 }else if( eFileLock==EXCLUSIVE_LOCK ){
2819 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002820 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002821 }
2822
2823afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002824 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002825 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2826 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002827 return rc;
2828}
2829
2830/*
drh308c2a52010-05-14 11:30:18 +00002831** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002832** must be either NO_LOCK or SHARED_LOCK.
2833**
2834** If the locking level of the file descriptor is already at or below
2835** the requested locking level, this routine is a no-op.
2836*/
drh308c2a52010-05-14 11:30:18 +00002837static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002838 int rc = SQLITE_OK;
2839 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002840 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002841 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2842 int skipShared = 0;
2843#ifdef SQLITE_TEST
2844 int h = pFile->h;
2845#endif
drhbfe66312006-10-03 17:40:40 +00002846
2847 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002848 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002849 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002850 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002851
drh308c2a52010-05-14 11:30:18 +00002852 assert( eFileLock<=SHARED_LOCK );
2853 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002854 return SQLITE_OK;
2855 }
drh6c7d5c52008-11-21 20:32:33 +00002856 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002857 pInode = pFile->pInode;
2858 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002859 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002860 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002861 SimulateIOErrorBenign(1);
2862 SimulateIOError( h=(-1) )
2863 SimulateIOErrorBenign(0);
2864
drhd3d8c042012-05-29 17:02:40 +00002865#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002866 /* When reducing a lock such that other processes can start
2867 ** reading the database file again, make sure that the
2868 ** transaction counter was updated if any part of the database
2869 ** file changed. If the transaction counter is not updated,
2870 ** other connections to the same file might not realize that
2871 ** the file has changed and hence might not know to flush their
2872 ** cache. The use of a stale cache can lead to database corruption.
2873 */
2874 assert( pFile->inNormalWrite==0
2875 || pFile->dbUpdate==0
2876 || pFile->transCntrChng==1 );
2877 pFile->inNormalWrite = 0;
2878#endif
aswiftaebf4132008-11-21 00:10:35 +00002879
drh308c2a52010-05-14 11:30:18 +00002880 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002881 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002882 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002883 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002884 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002885 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2886 } else {
2887 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002888 }
2889 }
drh308c2a52010-05-14 11:30:18 +00002890 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002891 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002892 }
drh308c2a52010-05-14 11:30:18 +00002893 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002894 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2895 if( !rc ){
2896 context->reserved = 0;
2897 }
aswiftaebf4132008-11-21 00:10:35 +00002898 }
drh8af6c222010-05-14 12:43:01 +00002899 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2900 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002901 }
aswiftaebf4132008-11-21 00:10:35 +00002902 }
drh308c2a52010-05-14 11:30:18 +00002903 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002904
drh7ed97b92010-01-20 13:07:21 +00002905 /* Decrement the shared lock counter. Release the lock using an
2906 ** OS call only when all threads in this same process have released
2907 ** the lock.
2908 */
drh8af6c222010-05-14 12:43:01 +00002909 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2910 pInode->nShared--;
2911 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00002912 SimulateIOErrorBenign(1);
2913 SimulateIOError( h=(-1) )
2914 SimulateIOErrorBenign(0);
2915 if( !skipShared ){
2916 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2917 }
2918 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00002919 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002920 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002921 }
2922 }
2923 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00002924 pInode->nLock--;
2925 assert( pInode->nLock>=0 );
2926 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00002927 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00002928 }
2929 }
drhbfe66312006-10-03 17:40:40 +00002930 }
drh7ed97b92010-01-20 13:07:21 +00002931
drh6c7d5c52008-11-21 20:32:33 +00002932 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002933 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00002934 return rc;
2935}
2936
2937/*
drh339eb0b2008-03-07 15:34:11 +00002938** Close a file & cleanup AFP specific locking context
2939*/
danielk1977e339d652008-06-28 11:23:00 +00002940static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00002941 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00002942 if( id ){
2943 unixFile *pFile = (unixFile*)id;
2944 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00002945 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002946 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00002947 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00002948 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00002949 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00002950 ** the last lock is cleared.
2951 */
dan08da86a2009-08-21 17:18:03 +00002952 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00002953 }
danb0ac3e32010-06-16 10:55:42 +00002954 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00002955 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00002956 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00002957 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00002958 }
drh7ed97b92010-01-20 13:07:21 +00002959 return rc;
drhbfe66312006-10-03 17:40:40 +00002960}
2961
drhd2cb50b2009-01-09 21:41:17 +00002962#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00002963/*
2964** The code above is the AFP lock implementation. The code is specific
2965** to MacOSX and does not work on other unix platforms. No alternative
2966** is available. If you don't compile for a mac, then the "unix-afp"
2967** VFS is not available.
2968**
2969********************* End of the AFP lock implementation **********************
2970******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002971
drh7ed97b92010-01-20 13:07:21 +00002972/******************************************************************************
2973*************************** Begin NFS Locking ********************************/
2974
2975#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2976/*
drh308c2a52010-05-14 11:30:18 +00002977 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002978 ** must be either NO_LOCK or SHARED_LOCK.
2979 **
2980 ** If the locking level of the file descriptor is already at or below
2981 ** the requested locking level, this routine is a no-op.
2982 */
drh308c2a52010-05-14 11:30:18 +00002983static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00002984 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00002985}
2986
2987#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2988/*
2989** The code above is the NFS lock implementation. The code is specific
2990** to MacOSX and does not work on other unix platforms. No alternative
2991** is available.
2992**
2993********************* End of the NFS lock implementation **********************
2994******************************************************************************/
drh734c9862008-11-28 15:37:20 +00002995
2996/******************************************************************************
2997**************** Non-locking sqlite3_file methods *****************************
2998**
2999** The next division contains implementations for all methods of the
3000** sqlite3_file object other than the locking methods. The locking
3001** methods were defined in divisions above (one locking method per
3002** division). Those methods that are common to all locking modes
3003** are gather together into this division.
3004*/
drhbfe66312006-10-03 17:40:40 +00003005
3006/*
drh734c9862008-11-28 15:37:20 +00003007** Seek to the offset passed as the second argument, then read cnt
3008** bytes into pBuf. Return the number of bytes actually read.
3009**
3010** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3011** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3012** one system to another. Since SQLite does not define USE_PREAD
3013** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3014** See tickets #2741 and #2681.
3015**
3016** To avoid stomping the errno value on a failed read the lastErrno value
3017** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003018*/
drh734c9862008-11-28 15:37:20 +00003019static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3020 int got;
drh58024642011-11-07 18:16:00 +00003021 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003022#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003023 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003024#endif
drh734c9862008-11-28 15:37:20 +00003025 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003026 assert( cnt==(cnt&0x1ffff) );
3027 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003028 do{
drh734c9862008-11-28 15:37:20 +00003029#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003030 got = osPread(id->h, pBuf, cnt, offset);
3031 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003032#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003033 got = osPread64(id->h, pBuf, cnt, offset);
3034 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003035#else
drh58024642011-11-07 18:16:00 +00003036 newOffset = lseek(id->h, offset, SEEK_SET);
3037 SimulateIOError( newOffset-- );
3038 if( newOffset!=offset ){
3039 if( newOffset == -1 ){
3040 ((unixFile*)id)->lastErrno = errno;
3041 }else{
drhf2f105d2012-08-20 15:53:54 +00003042 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003043 }
3044 return -1;
drh734c9862008-11-28 15:37:20 +00003045 }
drh58024642011-11-07 18:16:00 +00003046 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003047#endif
drh58024642011-11-07 18:16:00 +00003048 if( got==cnt ) break;
3049 if( got<0 ){
3050 if( errno==EINTR ){ got = 1; continue; }
3051 prior = 0;
3052 ((unixFile*)id)->lastErrno = errno;
3053 break;
3054 }else if( got>0 ){
3055 cnt -= got;
3056 offset += got;
3057 prior += got;
3058 pBuf = (void*)(got + (char*)pBuf);
3059 }
3060 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003061 TIMER_END;
drh58024642011-11-07 18:16:00 +00003062 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3063 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3064 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003065}
3066
3067/*
drh734c9862008-11-28 15:37:20 +00003068** Read data from a file into a buffer. Return SQLITE_OK if all
3069** bytes were read successfully and SQLITE_IOERR if anything goes
3070** wrong.
drh339eb0b2008-03-07 15:34:11 +00003071*/
drh734c9862008-11-28 15:37:20 +00003072static int unixRead(
3073 sqlite3_file *id,
3074 void *pBuf,
3075 int amt,
3076 sqlite3_int64 offset
3077){
dan08da86a2009-08-21 17:18:03 +00003078 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003079 int got;
3080 assert( id );
drh08c6d442009-02-09 17:34:07 +00003081
dan08da86a2009-08-21 17:18:03 +00003082 /* If this is a database file (not a journal, master-journal or temp
3083 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003084#if 0
dane946c392009-08-22 11:39:46 +00003085 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003086 || offset>=PENDING_BYTE+512
3087 || offset+amt<=PENDING_BYTE
3088 );
dan7c246102010-04-12 19:00:29 +00003089#endif
drh08c6d442009-02-09 17:34:07 +00003090
dan08da86a2009-08-21 17:18:03 +00003091 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003092 if( got==amt ){
3093 return SQLITE_OK;
3094 }else if( got<0 ){
3095 /* lastErrno set by seekAndRead */
3096 return SQLITE_IOERR_READ;
3097 }else{
dan08da86a2009-08-21 17:18:03 +00003098 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003099 /* Unread parts of the buffer must be zero-filled */
3100 memset(&((char*)pBuf)[got], 0, amt-got);
3101 return SQLITE_IOERR_SHORT_READ;
3102 }
3103}
3104
3105/*
3106** Seek to the offset in id->offset then read cnt bytes into pBuf.
3107** Return the number of bytes actually read. Update the offset.
3108**
3109** To avoid stomping the errno value on a failed write the lastErrno value
3110** is set before returning.
3111*/
3112static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
3113 int got;
drh7ed97b92010-01-20 13:07:21 +00003114#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003115 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003116#endif
drhc1fd2cf2012-10-01 12:16:26 +00003117 assert( cnt==(cnt&0x1ffff) );
3118 cnt &= 0x1ffff;
drh734c9862008-11-28 15:37:20 +00003119 TIMER_START;
3120#if defined(USE_PREAD)
drhe562be52011-03-02 18:01:10 +00003121 do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003122#elif defined(USE_PREAD64)
drhe562be52011-03-02 18:01:10 +00003123 do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
drh734c9862008-11-28 15:37:20 +00003124#else
drhbd1e50c2011-08-19 14:54:12 +00003125 do{
3126 newOffset = lseek(id->h, offset, SEEK_SET);
3127 SimulateIOError( newOffset-- );
3128 if( newOffset!=offset ){
3129 if( newOffset == -1 ){
3130 ((unixFile*)id)->lastErrno = errno;
3131 }else{
drhf2f105d2012-08-20 15:53:54 +00003132 ((unixFile*)id)->lastErrno = 0;
drhbd1e50c2011-08-19 14:54:12 +00003133 }
3134 return -1;
drh734c9862008-11-28 15:37:20 +00003135 }
drhbd1e50c2011-08-19 14:54:12 +00003136 got = osWrite(id->h, pBuf, cnt);
3137 }while( got<0 && errno==EINTR );
drh734c9862008-11-28 15:37:20 +00003138#endif
3139 TIMER_END;
3140 if( got<0 ){
3141 ((unixFile*)id)->lastErrno = errno;
3142 }
3143
drh308c2a52010-05-14 11:30:18 +00003144 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
drh734c9862008-11-28 15:37:20 +00003145 return got;
3146}
3147
3148
3149/*
3150** Write data from a buffer into a file. Return SQLITE_OK on success
3151** or some other error code on failure.
3152*/
3153static int unixWrite(
3154 sqlite3_file *id,
3155 const void *pBuf,
3156 int amt,
3157 sqlite3_int64 offset
3158){
dan08da86a2009-08-21 17:18:03 +00003159 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003160 int wrote = 0;
3161 assert( id );
3162 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003163
dan08da86a2009-08-21 17:18:03 +00003164 /* If this is a database file (not a journal, master-journal or temp
3165 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003166#if 0
dane946c392009-08-22 11:39:46 +00003167 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003168 || offset>=PENDING_BYTE+512
3169 || offset+amt<=PENDING_BYTE
3170 );
dan7c246102010-04-12 19:00:29 +00003171#endif
drh08c6d442009-02-09 17:34:07 +00003172
drhd3d8c042012-05-29 17:02:40 +00003173#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003174 /* If we are doing a normal write to a database file (as opposed to
3175 ** doing a hot-journal rollback or a write to some file other than a
3176 ** normal database file) then record the fact that the database
3177 ** has changed. If the transaction counter is modified, record that
3178 ** fact too.
3179 */
dan08da86a2009-08-21 17:18:03 +00003180 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003181 pFile->dbUpdate = 1; /* The database has been modified */
3182 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003183 int rc;
drh8f941bc2009-01-14 23:03:40 +00003184 char oldCntr[4];
3185 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003186 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003187 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003188 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003189 pFile->transCntrChng = 1; /* The transaction counter has changed */
3190 }
3191 }
3192 }
3193#endif
3194
dan08da86a2009-08-21 17:18:03 +00003195 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003196 amt -= wrote;
3197 offset += wrote;
3198 pBuf = &((char*)pBuf)[wrote];
3199 }
3200 SimulateIOError(( wrote=(-1), amt=1 ));
3201 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003202
drh734c9862008-11-28 15:37:20 +00003203 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003204 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003205 /* lastErrno set by seekAndWrite */
3206 return SQLITE_IOERR_WRITE;
3207 }else{
dan08da86a2009-08-21 17:18:03 +00003208 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003209 return SQLITE_FULL;
3210 }
3211 }
dan6e09d692010-07-27 18:34:15 +00003212
drh734c9862008-11-28 15:37:20 +00003213 return SQLITE_OK;
3214}
3215
3216#ifdef SQLITE_TEST
3217/*
3218** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003219** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003220*/
3221int sqlite3_sync_count = 0;
3222int sqlite3_fullsync_count = 0;
3223#endif
3224
3225/*
drh89240432009-03-25 01:06:01 +00003226** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003227** Others do no. To be safe, we will stick with the (slightly slower)
3228** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003229** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003230*/
drh20f8e132011-08-31 21:01:55 +00003231#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003232# define fdatasync fsync
3233#endif
3234
3235/*
3236** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3237** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3238** only available on Mac OS X. But that could change.
3239*/
3240#ifdef F_FULLFSYNC
3241# define HAVE_FULLFSYNC 1
3242#else
3243# define HAVE_FULLFSYNC 0
3244#endif
3245
3246
3247/*
3248** The fsync() system call does not work as advertised on many
3249** unix systems. The following procedure is an attempt to make
3250** it work better.
3251**
3252** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3253** for testing when we want to run through the test suite quickly.
3254** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3255** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3256** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003257**
3258** SQLite sets the dataOnly flag if the size of the file is unchanged.
3259** The idea behind dataOnly is that it should only write the file content
3260** to disk, not the inode. We only set dataOnly if the file size is
3261** unchanged since the file size is part of the inode. However,
3262** Ted Ts'o tells us that fdatasync() will also write the inode if the
3263** file size has changed. The only real difference between fdatasync()
3264** and fsync(), Ted tells us, is that fdatasync() will not flush the
3265** inode if the mtime or owner or other inode attributes have changed.
3266** We only care about the file size, not the other file attributes, so
3267** as far as SQLite is concerned, an fdatasync() is always adequate.
3268** So, we always use fdatasync() if it is available, regardless of
3269** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003270*/
3271static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003272 int rc;
drh734c9862008-11-28 15:37:20 +00003273
3274 /* The following "ifdef/elif/else/" block has the same structure as
3275 ** the one below. It is replicated here solely to avoid cluttering
3276 ** up the real code with the UNUSED_PARAMETER() macros.
3277 */
3278#ifdef SQLITE_NO_SYNC
3279 UNUSED_PARAMETER(fd);
3280 UNUSED_PARAMETER(fullSync);
3281 UNUSED_PARAMETER(dataOnly);
3282#elif HAVE_FULLFSYNC
3283 UNUSED_PARAMETER(dataOnly);
3284#else
3285 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003286 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003287#endif
3288
3289 /* Record the number of times that we do a normal fsync() and
3290 ** FULLSYNC. This is used during testing to verify that this procedure
3291 ** gets called with the correct arguments.
3292 */
3293#ifdef SQLITE_TEST
3294 if( fullSync ) sqlite3_fullsync_count++;
3295 sqlite3_sync_count++;
3296#endif
3297
3298 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3299 ** no-op
3300 */
3301#ifdef SQLITE_NO_SYNC
3302 rc = SQLITE_OK;
3303#elif HAVE_FULLFSYNC
3304 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003305 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003306 }else{
3307 rc = 1;
3308 }
3309 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003310 ** It shouldn't be possible for fullfsync to fail on the local
3311 ** file system (on OSX), so failure indicates that FULLFSYNC
3312 ** isn't supported for this file system. So, attempt an fsync
3313 ** and (for now) ignore the overhead of a superfluous fcntl call.
3314 ** It'd be better to detect fullfsync support once and avoid
3315 ** the fcntl call every time sync is called.
3316 */
drh734c9862008-11-28 15:37:20 +00003317 if( rc ) rc = fsync(fd);
3318
drh7ed97b92010-01-20 13:07:21 +00003319#elif defined(__APPLE__)
3320 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3321 ** so currently we default to the macro that redefines fdatasync to fsync
3322 */
3323 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003324#else
drh0b647ff2009-03-21 14:41:04 +00003325 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003326#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003327 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003328 rc = fsync(fd);
3329 }
drh0b647ff2009-03-21 14:41:04 +00003330#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003331#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3332
3333 if( OS_VXWORKS && rc!= -1 ){
3334 rc = 0;
3335 }
chw97185482008-11-17 08:05:31 +00003336 return rc;
drhbfe66312006-10-03 17:40:40 +00003337}
3338
drh734c9862008-11-28 15:37:20 +00003339/*
drh0059eae2011-08-08 23:48:40 +00003340** Open a file descriptor to the directory containing file zFilename.
3341** If successful, *pFd is set to the opened file descriptor and
3342** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3343** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3344** value.
3345**
drh90315a22011-08-10 01:52:12 +00003346** The directory file descriptor is used for only one thing - to
3347** fsync() a directory to make sure file creation and deletion events
3348** are flushed to disk. Such fsyncs are not needed on newer
3349** journaling filesystems, but are required on older filesystems.
3350**
3351** This routine can be overridden using the xSetSysCall interface.
3352** The ability to override this routine was added in support of the
3353** chromium sandbox. Opening a directory is a security risk (we are
3354** told) so making it overrideable allows the chromium sandbox to
3355** replace this routine with a harmless no-op. To make this routine
3356** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3357** *pFd set to a negative number.
3358**
drh0059eae2011-08-08 23:48:40 +00003359** If SQLITE_OK is returned, the caller is responsible for closing
3360** the file descriptor *pFd using close().
3361*/
3362static int openDirectory(const char *zFilename, int *pFd){
3363 int ii;
3364 int fd = -1;
3365 char zDirname[MAX_PATHNAME+1];
3366
3367 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3368 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3369 if( ii>0 ){
3370 zDirname[ii] = '\0';
3371 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3372 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003373 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3374 }
3375 }
3376 *pFd = fd;
3377 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3378}
3379
3380/*
drh734c9862008-11-28 15:37:20 +00003381** Make sure all writes to a particular file are committed to disk.
3382**
3383** If dataOnly==0 then both the file itself and its metadata (file
3384** size, access time, etc) are synced. If dataOnly!=0 then only the
3385** file data is synced.
3386**
3387** Under Unix, also make sure that the directory entry for the file
3388** has been created by fsync-ing the directory that contains the file.
3389** If we do not do this and we encounter a power failure, the directory
3390** entry for the journal might not exist after we reboot. The next
3391** SQLite to access the file will not know that the journal exists (because
3392** the directory entry for the journal was never created) and the transaction
3393** will not roll back - possibly leading to database corruption.
3394*/
3395static int unixSync(sqlite3_file *id, int flags){
3396 int rc;
3397 unixFile *pFile = (unixFile*)id;
3398
3399 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3400 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3401
3402 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3403 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3404 || (flags&0x0F)==SQLITE_SYNC_FULL
3405 );
3406
3407 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3408 ** line is to test that doing so does not cause any problems.
3409 */
3410 SimulateDiskfullError( return SQLITE_FULL );
3411
3412 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003413 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003414 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3415 SimulateIOError( rc=1 );
3416 if( rc ){
3417 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003418 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003419 }
drh0059eae2011-08-08 23:48:40 +00003420
3421 /* Also fsync the directory containing the file if the DIRSYNC flag
drh90315a22011-08-10 01:52:12 +00003422 ** is set. This is a one-time occurrance. Many systems (examples: AIX)
3423 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003424 */
3425 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3426 int dirfd;
3427 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003428 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003429 rc = osOpenDirectory(pFile->zPath, &dirfd);
3430 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003431 full_fsync(dirfd, 0, 0);
3432 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003433 }else if( rc==SQLITE_CANTOPEN ){
3434 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003435 }
drh0059eae2011-08-08 23:48:40 +00003436 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003437 }
3438 return rc;
3439}
3440
3441/*
3442** Truncate an open file to a specified size
3443*/
3444static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003445 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003446 int rc;
dan6e09d692010-07-27 18:34:15 +00003447 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003448 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003449
3450 /* If the user has configured a chunk-size for this file, truncate the
3451 ** file so that it consists of an integer number of chunks (i.e. the
3452 ** actual file size after the operation may be larger than the requested
3453 ** size).
3454 */
drhb8af4b72012-04-05 20:04:39 +00003455 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003456 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3457 }
3458
drhff812312011-02-23 13:33:46 +00003459 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003460 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003461 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003462 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003463 }else{
drhd3d8c042012-05-29 17:02:40 +00003464#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003465 /* If we are doing a normal write to a database file (as opposed to
3466 ** doing a hot-journal rollback or a write to some file other than a
3467 ** normal database file) and we truncate the file to zero length,
3468 ** that effectively updates the change counter. This might happen
3469 ** when restoring a database using the backup API from a zero-length
3470 ** source.
3471 */
dan6e09d692010-07-27 18:34:15 +00003472 if( pFile->inNormalWrite && nByte==0 ){
3473 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003474 }
3475#endif
3476
drh734c9862008-11-28 15:37:20 +00003477 return SQLITE_OK;
3478 }
3479}
3480
3481/*
3482** Determine the current size of a file in bytes
3483*/
3484static int unixFileSize(sqlite3_file *id, i64 *pSize){
3485 int rc;
3486 struct stat buf;
3487 assert( id );
drh99ab3b12011-03-02 15:09:07 +00003488 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003489 SimulateIOError( rc=1 );
3490 if( rc!=0 ){
3491 ((unixFile*)id)->lastErrno = errno;
3492 return SQLITE_IOERR_FSTAT;
3493 }
3494 *pSize = buf.st_size;
3495
drh8af6c222010-05-14 12:43:01 +00003496 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003497 ** writes a single byte into that file in order to work around a bug
3498 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3499 ** layers, we need to report this file size as zero even though it is
3500 ** really 1. Ticket #3260.
3501 */
3502 if( *pSize==1 ) *pSize = 0;
3503
3504
3505 return SQLITE_OK;
3506}
3507
drhd2cb50b2009-01-09 21:41:17 +00003508#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003509/*
3510** Handler for proxy-locking file-control verbs. Defined below in the
3511** proxying locking division.
3512*/
3513static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003514#endif
drh715ff302008-12-03 22:32:44 +00003515
dan502019c2010-07-28 14:26:17 +00003516/*
3517** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003518** file-control operation. Enlarge the database to nBytes in size
3519** (rounded up to the next chunk-size). If the database is already
3520** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003521*/
3522static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003523 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003524 i64 nSize; /* Required file size */
3525 struct stat buf; /* Used to hold return values of fstat() */
3526
drh99ab3b12011-03-02 15:09:07 +00003527 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003528
3529 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3530 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003531
dan502019c2010-07-28 14:26:17 +00003532#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003533 /* The code below is handling the return value of osFallocate()
3534 ** correctly. posix_fallocate() is defined to "returns zero on success,
3535 ** or an error number on failure". See the manpage for details. */
3536 int err;
drhff812312011-02-23 13:33:46 +00003537 do{
dan661d71a2011-03-30 19:08:03 +00003538 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3539 }while( err==EINTR );
3540 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003541#else
3542 /* If the OS does not have posix_fallocate(), fake it. First use
3543 ** ftruncate() to set the file size, then write a single byte to
3544 ** the last byte in each block within the extended region. This
3545 ** is the same technique used by glibc to implement posix_fallocate()
3546 ** on systems that do not have a real fallocate() system call.
3547 */
3548 int nBlk = buf.st_blksize; /* File-system block size */
3549 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003550
drhff812312011-02-23 13:33:46 +00003551 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003552 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003553 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003554 }
3555 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003556 while( iWrite<nSize ){
3557 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3558 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003559 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003560 }
dan502019c2010-07-28 14:26:17 +00003561#endif
3562 }
3563 }
3564
3565 return SQLITE_OK;
3566}
danielk1977ad94b582007-08-20 06:44:22 +00003567
danielk1977e3026632004-06-22 11:29:02 +00003568/*
drhf12b3f62011-12-21 14:42:29 +00003569** If *pArg is inititially negative then this is a query. Set *pArg to
3570** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3571**
3572** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3573*/
3574static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3575 if( *pArg<0 ){
3576 *pArg = (pFile->ctrlFlags & mask)!=0;
3577 }else if( (*pArg)==0 ){
3578 pFile->ctrlFlags &= ~mask;
3579 }else{
3580 pFile->ctrlFlags |= mask;
3581 }
3582}
3583
drh696b33e2012-12-06 19:01:42 +00003584/* Forward declaration */
3585static int unixGetTempname(int nBuf, char *zBuf);
3586
drhf12b3f62011-12-21 14:42:29 +00003587/*
drh9e33c2c2007-08-31 18:34:59 +00003588** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003589*/
drhcc6bb3e2007-08-31 16:11:35 +00003590static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003591 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003592 switch( op ){
3593 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003594 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003595 return SQLITE_OK;
3596 }
drh7708e972008-11-29 00:56:52 +00003597 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003598 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003599 return SQLITE_OK;
3600 }
dan6e09d692010-07-27 18:34:15 +00003601 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003602 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003603 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003604 }
drh9ff27ec2010-05-19 19:26:05 +00003605 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003606 int rc;
3607 SimulateIOErrorBenign(1);
3608 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3609 SimulateIOErrorBenign(0);
3610 return rc;
drhf0b190d2011-07-26 16:03:07 +00003611 }
3612 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003613 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3614 return SQLITE_OK;
3615 }
drhcb15f352011-12-23 01:04:17 +00003616 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3617 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003618 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003619 }
drhde60fc22011-12-14 17:53:36 +00003620 case SQLITE_FCNTL_VFSNAME: {
3621 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3622 return SQLITE_OK;
3623 }
drh696b33e2012-12-06 19:01:42 +00003624 case SQLITE_FCNTL_TEMPFILENAME: {
3625 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3626 if( zTFile ){
3627 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3628 *(char**)pArg = zTFile;
3629 }
3630 return SQLITE_OK;
3631 }
drhd3d8c042012-05-29 17:02:40 +00003632#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003633 /* The pager calls this method to signal that it has done
3634 ** a rollback and that the database is therefore unchanged and
3635 ** it hence it is OK for the transaction change counter to be
3636 ** unchanged.
3637 */
3638 case SQLITE_FCNTL_DB_UNCHANGED: {
3639 ((unixFile*)id)->dbUpdate = 0;
3640 return SQLITE_OK;
3641 }
3642#endif
drhd2cb50b2009-01-09 21:41:17 +00003643#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003644 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003645 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003646 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003647 }
drhd2cb50b2009-01-09 21:41:17 +00003648#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003649 }
drh0b52b7d2011-01-26 19:46:22 +00003650 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003651}
3652
3653/*
danielk1977a3d4c882007-03-23 10:08:38 +00003654** Return the sector size in bytes of the underlying block device for
3655** the specified file. This is almost always 512 bytes, but may be
3656** larger for some devices.
3657**
3658** SQLite code assumes this function cannot fail. It also assumes that
3659** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003660** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003661** same for both.
3662*/
drh537dddf2012-10-26 13:46:24 +00003663#ifndef __QNXNTO__
3664static int unixSectorSize(sqlite3_file *NotUsed){
3665 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003666 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003667}
drh537dddf2012-10-26 13:46:24 +00003668#endif
3669
3670/*
3671** The following version of unixSectorSize() is optimized for QNX.
3672*/
3673#ifdef __QNXNTO__
3674#include <sys/dcmd_blk.h>
3675#include <sys/statvfs.h>
3676static int unixSectorSize(sqlite3_file *id){
3677 unixFile *pFile = (unixFile*)id;
3678 if( pFile->sectorSize == 0 ){
3679 struct statvfs fsInfo;
3680
3681 /* Set defaults for non-supported filesystems */
3682 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3683 pFile->deviceCharacteristics = 0;
3684 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3685 return pFile->sectorSize;
3686 }
3687
3688 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3689 pFile->sectorSize = fsInfo.f_bsize;
3690 pFile->deviceCharacteristics =
3691 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3692 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3693 ** the write succeeds */
3694 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3695 ** so it is ordered */
3696 0;
3697 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3698 pFile->sectorSize = fsInfo.f_bsize;
3699 pFile->deviceCharacteristics =
3700 /* etfs cluster size writes are atomic */
3701 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3702 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3703 ** the write succeeds */
3704 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3705 ** so it is ordered */
3706 0;
3707 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3708 pFile->sectorSize = fsInfo.f_bsize;
3709 pFile->deviceCharacteristics =
3710 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3711 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3712 ** the write succeeds */
3713 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3714 ** so it is ordered */
3715 0;
3716 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3717 pFile->sectorSize = fsInfo.f_bsize;
3718 pFile->deviceCharacteristics =
3719 /* full bitset of atomics from max sector size and smaller */
3720 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3721 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3722 ** so it is ordered */
3723 0;
3724 }else if( strstr(fsInfo.f_basetype, "dos") ){
3725 pFile->sectorSize = fsInfo.f_bsize;
3726 pFile->deviceCharacteristics =
3727 /* full bitset of atomics from max sector size and smaller */
3728 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3729 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3730 ** so it is ordered */
3731 0;
3732 }else{
3733 pFile->deviceCharacteristics =
3734 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3735 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3736 ** the write succeeds */
3737 0;
3738 }
3739 }
3740 /* Last chance verification. If the sector size isn't a multiple of 512
3741 ** then it isn't valid.*/
3742 if( pFile->sectorSize % 512 != 0 ){
3743 pFile->deviceCharacteristics = 0;
3744 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3745 }
3746 return pFile->sectorSize;
3747}
3748#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003749
danielk197790949c22007-08-17 16:50:38 +00003750/*
drhf12b3f62011-12-21 14:42:29 +00003751** Return the device characteristics for the file.
3752**
drhcb15f352011-12-23 01:04:17 +00003753** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3754** However, that choice is contraversial since technically the underlying
3755** file system does not always provide powersafe overwrites. (In other
3756** words, after a power-loss event, parts of the file that were never
3757** written might end up being altered.) However, non-PSOW behavior is very,
3758** very rare. And asserting PSOW makes a large reduction in the amount
3759** of required I/O for journaling, since a lot of padding is eliminated.
3760** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3761** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003762*/
drhf12b3f62011-12-21 14:42:29 +00003763static int unixDeviceCharacteristics(sqlite3_file *id){
3764 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003765 int rc = 0;
3766#ifdef __QNXNTO__
3767 if( p->sectorSize==0 ) unixSectorSize(id);
3768 rc = p->deviceCharacteristics;
3769#endif
drhcb15f352011-12-23 01:04:17 +00003770 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003771 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003772 }
drh537dddf2012-10-26 13:46:24 +00003773 return rc;
danielk197762079062007-08-15 17:08:46 +00003774}
3775
drhd9e5c4f2010-05-12 18:01:39 +00003776#ifndef SQLITE_OMIT_WAL
3777
3778
3779/*
drhd91c68f2010-05-14 14:52:25 +00003780** Object used to represent an shared memory buffer.
3781**
3782** When multiple threads all reference the same wal-index, each thread
3783** has its own unixShm object, but they all point to a single instance
3784** of this unixShmNode object. In other words, each wal-index is opened
3785** only once per process.
3786**
3787** Each unixShmNode object is connected to a single unixInodeInfo object.
3788** We could coalesce this object into unixInodeInfo, but that would mean
3789** every open file that does not use shared memory (in other words, most
3790** open files) would have to carry around this extra information. So
3791** the unixInodeInfo object contains a pointer to this unixShmNode object
3792** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003793**
3794** unixMutexHeld() must be true when creating or destroying
3795** this object or while reading or writing the following fields:
3796**
3797** nRef
drhd9e5c4f2010-05-12 18:01:39 +00003798**
3799** The following fields are read-only after the object is created:
3800**
3801** fid
3802** zFilename
3803**
drhd91c68f2010-05-14 14:52:25 +00003804** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00003805** unixMutexHeld() is true when reading or writing any other field
3806** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00003807*/
drhd91c68f2010-05-14 14:52:25 +00003808struct unixShmNode {
3809 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00003810 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00003811 char *zFilename; /* Name of the mmapped file */
3812 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00003813 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00003814 u16 nRegion; /* Size of array apRegion */
3815 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00003816 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00003817 int nRef; /* Number of unixShm objects pointing to this */
3818 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00003819#ifdef SQLITE_DEBUG
3820 u8 exclMask; /* Mask of exclusive locks held */
3821 u8 sharedMask; /* Mask of shared locks held */
3822 u8 nextShmId; /* Next available unixShm.id value */
3823#endif
3824};
3825
3826/*
drhd9e5c4f2010-05-12 18:01:39 +00003827** Structure used internally by this VFS to record the state of an
3828** open shared memory connection.
3829**
drhd91c68f2010-05-14 14:52:25 +00003830** The following fields are initialized when this object is created and
3831** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00003832**
drhd91c68f2010-05-14 14:52:25 +00003833** unixShm.pFile
3834** unixShm.id
3835**
3836** All other fields are read/write. The unixShm.pFile->mutex must be held
3837** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00003838*/
3839struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00003840 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3841 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00003842 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00003843 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00003844 u16 sharedMask; /* Mask of shared locks held */
3845 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00003846};
3847
3848/*
drhd9e5c4f2010-05-12 18:01:39 +00003849** Constants used for locking
3850*/
drhbd9676c2010-06-23 17:58:38 +00003851#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00003852#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00003853
drhd9e5c4f2010-05-12 18:01:39 +00003854/*
drh73b64e42010-05-30 19:55:15 +00003855** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00003856**
3857** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3858** otherwise.
3859*/
3860static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00003861 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3862 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00003863 int ofst, /* First byte of the locking range */
3864 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00003865){
3866 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00003867 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00003868
drhd91c68f2010-05-14 14:52:25 +00003869 /* Access to the unixShmNode object is serialized by the caller */
3870 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00003871
drh73b64e42010-05-30 19:55:15 +00003872 /* Shared locks never span more than one byte */
3873 assert( n==1 || lockType!=F_RDLCK );
3874
3875 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00003876 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00003877
drh3cb93392011-03-12 18:10:44 +00003878 if( pShmNode->h>=0 ){
3879 /* Initialize the locking parameters */
3880 memset(&f, 0, sizeof(f));
3881 f.l_type = lockType;
3882 f.l_whence = SEEK_SET;
3883 f.l_start = ofst;
3884 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00003885
drh3cb93392011-03-12 18:10:44 +00003886 rc = osFcntl(pShmNode->h, F_SETLK, &f);
3887 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3888 }
drhd9e5c4f2010-05-12 18:01:39 +00003889
3890 /* Update the global lock state and do debug tracing */
3891#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00003892 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00003893 OSTRACE(("SHM-LOCK "));
drh73b64e42010-05-30 19:55:15 +00003894 mask = (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00003895 if( rc==SQLITE_OK ){
3896 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003897 OSTRACE(("unlock %d ok", ofst));
3898 pShmNode->exclMask &= ~mask;
3899 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003900 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00003901 OSTRACE(("read-lock %d ok", ofst));
3902 pShmNode->exclMask &= ~mask;
3903 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00003904 }else{
3905 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003906 OSTRACE(("write-lock %d ok", ofst));
3907 pShmNode->exclMask |= mask;
3908 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00003909 }
3910 }else{
3911 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00003912 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003913 }else if( lockType==F_RDLCK ){
3914 OSTRACE(("read-lock failed"));
3915 }else{
3916 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00003917 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00003918 }
3919 }
drh20e1f082010-05-31 16:10:12 +00003920 OSTRACE((" - afterwards %03x,%03x\n",
3921 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00003922 }
drhd9e5c4f2010-05-12 18:01:39 +00003923#endif
3924
3925 return rc;
3926}
3927
drhd9e5c4f2010-05-12 18:01:39 +00003928
3929/*
drhd91c68f2010-05-14 14:52:25 +00003930** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00003931**
3932** This is not a VFS shared-memory method; it is a utility function called
3933** by VFS shared-memory methods.
3934*/
drhd91c68f2010-05-14 14:52:25 +00003935static void unixShmPurge(unixFile *pFd){
3936 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00003937 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00003938 if( p && p->nRef==0 ){
dan13a3cb82010-06-11 19:04:21 +00003939 int i;
drhd91c68f2010-05-14 14:52:25 +00003940 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00003941 sqlite3_mutex_free(p->mutex);
dan18801912010-06-14 14:07:50 +00003942 for(i=0; i<p->nRegion; i++){
drh3cb93392011-03-12 18:10:44 +00003943 if( p->h>=0 ){
3944 munmap(p->apRegion[i], p->szRegion);
3945 }else{
3946 sqlite3_free(p->apRegion[i]);
3947 }
dan13a3cb82010-06-11 19:04:21 +00003948 }
dan18801912010-06-14 14:07:50 +00003949 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00003950 if( p->h>=0 ){
3951 robust_close(pFd, p->h, __LINE__);
3952 p->h = -1;
3953 }
drhd91c68f2010-05-14 14:52:25 +00003954 p->pInode->pShmNode = 0;
3955 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00003956 }
3957}
3958
3959/*
danda9fe0c2010-07-13 18:44:03 +00003960** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00003961** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00003962**
drh7234c6d2010-06-19 15:10:09 +00003963** The file used to implement shared-memory is in the same directory
3964** as the open database file and has the same name as the open database
3965** file with the "-shm" suffix added. For example, if the database file
3966** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00003967** for shared memory will be called "/home/user1/config.db-shm".
3968**
3969** Another approach to is to use files in /dev/shm or /dev/tmp or an
3970** some other tmpfs mount. But if a file in a different directory
3971** from the database file is used, then differing access permissions
3972** or a chroot() might cause two different processes on the same
3973** database to end up using different files for shared memory -
3974** meaning that their memory would not really be shared - resulting
3975** in database corruption. Nevertheless, this tmpfs file usage
3976** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3977** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3978** option results in an incompatible build of SQLite; builds of SQLite
3979** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3980** same database file at the same time, database corruption will likely
3981** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3982** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00003983**
3984** When opening a new shared-memory file, if no other instances of that
3985** file are currently open, in this process or in other processes, then
3986** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00003987**
3988** If the original database file (pDbFd) is using the "unix-excl" VFS
3989** that means that an exclusive lock is held on the database file and
3990** that no other processes are able to read or write the database. In
3991** that case, we do not really need shared memory. No shared memory
3992** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00003993*/
danda9fe0c2010-07-13 18:44:03 +00003994static int unixOpenSharedMemory(unixFile *pDbFd){
3995 struct unixShm *p = 0; /* The connection to be opened */
3996 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3997 int rc; /* Result code */
3998 unixInodeInfo *pInode; /* The inode of fd */
3999 char *zShmFilename; /* Name of the file used for SHM */
4000 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004001
danda9fe0c2010-07-13 18:44:03 +00004002 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004003 p = sqlite3_malloc( sizeof(*p) );
4004 if( p==0 ) return SQLITE_NOMEM;
4005 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004006 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004007
danda9fe0c2010-07-13 18:44:03 +00004008 /* Check to see if a unixShmNode object already exists. Reuse an existing
4009 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004010 */
4011 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004012 pInode = pDbFd->pInode;
4013 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004014 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004015 struct stat sStat; /* fstat() info for database file */
4016
4017 /* Call fstat() to figure out the permissions on the database file. If
4018 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004019 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004020 */
drh3cb93392011-03-12 18:10:44 +00004021 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004022 rc = SQLITE_IOERR_FSTAT;
4023 goto shm_open_err;
4024 }
4025
drha4ced192010-07-15 18:32:40 +00004026#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004027 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004028#else
drh52bcde02012-01-03 14:50:45 +00004029 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004030#endif
drh7234c6d2010-06-19 15:10:09 +00004031 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004032 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004033 rc = SQLITE_NOMEM;
4034 goto shm_open_err;
4035 }
drh9cb5a0d2012-01-05 21:19:54 +00004036 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004037 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004038#ifdef SQLITE_SHM_DIRECTORY
4039 sqlite3_snprintf(nShmFilename, zShmFilename,
4040 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4041 (u32)sStat.st_ino, (u32)sStat.st_dev);
4042#else
drh7234c6d2010-06-19 15:10:09 +00004043 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004044 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004045#endif
drhd91c68f2010-05-14 14:52:25 +00004046 pShmNode->h = -1;
4047 pDbFd->pInode->pShmNode = pShmNode;
4048 pShmNode->pInode = pDbFd->pInode;
4049 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4050 if( pShmNode->mutex==0 ){
4051 rc = SQLITE_NOMEM;
4052 goto shm_open_err;
4053 }
drhd9e5c4f2010-05-12 18:01:39 +00004054
drh3cb93392011-03-12 18:10:44 +00004055 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004056 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004057 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004058 openFlags = O_RDONLY;
4059 pShmNode->isReadonly = 1;
4060 }
4061 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004062 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004063 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4064 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004065 }
drhac7c3ac2012-02-11 19:23:48 +00004066
4067 /* If this process is running as root, make sure that the SHM file
4068 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004069 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004070 */
drhed466822012-05-31 13:10:49 +00004071 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004072
4073 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004074 ** If not, truncate the file to zero length.
4075 */
4076 rc = SQLITE_OK;
4077 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4078 if( robust_ftruncate(pShmNode->h, 0) ){
4079 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004080 }
4081 }
drh66dfec8b2011-06-01 20:01:49 +00004082 if( rc==SQLITE_OK ){
4083 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4084 }
4085 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004086 }
drhd9e5c4f2010-05-12 18:01:39 +00004087 }
4088
drhd91c68f2010-05-14 14:52:25 +00004089 /* Make the new connection a child of the unixShmNode */
4090 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004091#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004092 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004093#endif
drhd91c68f2010-05-14 14:52:25 +00004094 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004095 pDbFd->pShm = p;
4096 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004097
4098 /* The reference count on pShmNode has already been incremented under
4099 ** the cover of the unixEnterMutex() mutex and the pointer from the
4100 ** new (struct unixShm) object to the pShmNode has been set. All that is
4101 ** left to do is to link the new object into the linked list starting
4102 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4103 ** mutex.
4104 */
4105 sqlite3_mutex_enter(pShmNode->mutex);
4106 p->pNext = pShmNode->pFirst;
4107 pShmNode->pFirst = p;
4108 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004109 return SQLITE_OK;
4110
4111 /* Jump here on any error */
4112shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004113 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004114 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004115 unixLeaveMutex();
4116 return rc;
4117}
4118
4119/*
danda9fe0c2010-07-13 18:44:03 +00004120** This function is called to obtain a pointer to region iRegion of the
4121** shared-memory associated with the database file fd. Shared-memory regions
4122** are numbered starting from zero. Each shared-memory region is szRegion
4123** bytes in size.
4124**
4125** If an error occurs, an error code is returned and *pp is set to NULL.
4126**
4127** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4128** region has not been allocated (by any client, including one running in a
4129** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4130** bExtend is non-zero and the requested shared-memory region has not yet
4131** been allocated, it is allocated by this function.
4132**
4133** If the shared-memory region has already been allocated or is allocated by
4134** this call as described above, then it is mapped into this processes
4135** address space (if it is not already), *pp is set to point to the mapped
4136** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004137*/
danda9fe0c2010-07-13 18:44:03 +00004138static int unixShmMap(
4139 sqlite3_file *fd, /* Handle open on database file */
4140 int iRegion, /* Region to retrieve */
4141 int szRegion, /* Size of regions */
4142 int bExtend, /* True to extend file if necessary */
4143 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004144){
danda9fe0c2010-07-13 18:44:03 +00004145 unixFile *pDbFd = (unixFile*)fd;
4146 unixShm *p;
4147 unixShmNode *pShmNode;
4148 int rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004149
danda9fe0c2010-07-13 18:44:03 +00004150 /* If the shared-memory file has not yet been opened, open it now. */
4151 if( pDbFd->pShm==0 ){
4152 rc = unixOpenSharedMemory(pDbFd);
4153 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004154 }
drhd9e5c4f2010-05-12 18:01:39 +00004155
danda9fe0c2010-07-13 18:44:03 +00004156 p = pDbFd->pShm;
4157 pShmNode = p->pShmNode;
4158 sqlite3_mutex_enter(pShmNode->mutex);
4159 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004160 assert( pShmNode->pInode==pDbFd->pInode );
4161 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4162 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004163
4164 if( pShmNode->nRegion<=iRegion ){
4165 char **apNew; /* New apRegion[] array */
4166 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
4167 struct stat sStat; /* Used by fstat() */
4168
4169 pShmNode->szRegion = szRegion;
4170
drh3cb93392011-03-12 18:10:44 +00004171 if( pShmNode->h>=0 ){
4172 /* The requested region is not mapped into this processes address space.
4173 ** Check to see if it has been allocated (i.e. if the wal-index file is
4174 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004175 */
drh3cb93392011-03-12 18:10:44 +00004176 if( osFstat(pShmNode->h, &sStat) ){
4177 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004178 goto shmpage_out;
4179 }
drh3cb93392011-03-12 18:10:44 +00004180
4181 if( sStat.st_size<nByte ){
4182 /* The requested memory region does not exist. If bExtend is set to
4183 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
4184 **
4185 ** Alternatively, if bExtend is true, use ftruncate() to allocate
4186 ** the requested memory region.
4187 */
4188 if( !bExtend ) goto shmpage_out;
drh0fbb50e2012-11-13 10:54:12 +00004189#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
4190 if( osFallocate(pShmNode->h, sStat.st_size, nByte)!=0 ){
4191 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "fallocate",
4192 pShmNode->zFilename);
4193 goto shmpage_out;
4194 }
4195#else
drh3cb93392011-03-12 18:10:44 +00004196 if( robust_ftruncate(pShmNode->h, nByte) ){
4197 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
4198 pShmNode->zFilename);
4199 goto shmpage_out;
4200 }
drh0fbb50e2012-11-13 10:54:12 +00004201#endif
drh3cb93392011-03-12 18:10:44 +00004202 }
danda9fe0c2010-07-13 18:44:03 +00004203 }
4204
4205 /* Map the requested memory region into this processes address space. */
4206 apNew = (char **)sqlite3_realloc(
4207 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
4208 );
4209 if( !apNew ){
4210 rc = SQLITE_IOERR_NOMEM;
4211 goto shmpage_out;
4212 }
4213 pShmNode->apRegion = apNew;
4214 while(pShmNode->nRegion<=iRegion){
drh3cb93392011-03-12 18:10:44 +00004215 void *pMem;
4216 if( pShmNode->h>=0 ){
drh66dfec8b2011-06-01 20:01:49 +00004217 pMem = mmap(0, szRegion,
4218 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004219 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004220 );
4221 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004222 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004223 goto shmpage_out;
4224 }
4225 }else{
4226 pMem = sqlite3_malloc(szRegion);
4227 if( pMem==0 ){
4228 rc = SQLITE_NOMEM;
4229 goto shmpage_out;
4230 }
4231 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004232 }
4233 pShmNode->apRegion[pShmNode->nRegion] = pMem;
4234 pShmNode->nRegion++;
4235 }
4236 }
4237
4238shmpage_out:
4239 if( pShmNode->nRegion>iRegion ){
4240 *pp = pShmNode->apRegion[iRegion];
4241 }else{
4242 *pp = 0;
4243 }
drh66dfec8b2011-06-01 20:01:49 +00004244 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004245 sqlite3_mutex_leave(pShmNode->mutex);
4246 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004247}
4248
4249/*
drhd9e5c4f2010-05-12 18:01:39 +00004250** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004251**
4252** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4253** different here than in posix. In xShmLock(), one can go from unlocked
4254** to shared and back or from unlocked to exclusive and back. But one may
4255** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004256*/
4257static int unixShmLock(
4258 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004259 int ofst, /* First lock to acquire or release */
4260 int n, /* Number of locks to acquire or release */
4261 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004262){
drh73b64e42010-05-30 19:55:15 +00004263 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4264 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4265 unixShm *pX; /* For looping over all siblings */
4266 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4267 int rc = SQLITE_OK; /* Result code */
4268 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004269
drhd91c68f2010-05-14 14:52:25 +00004270 assert( pShmNode==pDbFd->pInode->pShmNode );
4271 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004272 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004273 assert( n>=1 );
4274 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4275 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4276 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4277 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4278 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004279 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4280 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004281
drhc99597c2010-05-31 01:41:15 +00004282 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004283 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004284 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004285 if( flags & SQLITE_SHM_UNLOCK ){
4286 u16 allMask = 0; /* Mask of locks held by siblings */
4287
4288 /* See if any siblings hold this same lock */
4289 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4290 if( pX==p ) continue;
4291 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4292 allMask |= pX->sharedMask;
4293 }
4294
4295 /* Unlock the system-level locks */
4296 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004297 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004298 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004299 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004300 }
drh73b64e42010-05-30 19:55:15 +00004301
4302 /* Undo the local locks */
4303 if( rc==SQLITE_OK ){
4304 p->exclMask &= ~mask;
4305 p->sharedMask &= ~mask;
4306 }
4307 }else if( flags & SQLITE_SHM_SHARED ){
4308 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4309
4310 /* Find out which shared locks are already held by sibling connections.
4311 ** If any sibling already holds an exclusive lock, go ahead and return
4312 ** SQLITE_BUSY.
4313 */
4314 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004315 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004316 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004317 break;
4318 }
4319 allShared |= pX->sharedMask;
4320 }
4321
4322 /* Get shared locks at the system level, if necessary */
4323 if( rc==SQLITE_OK ){
4324 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004325 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004326 }else{
drh73b64e42010-05-30 19:55:15 +00004327 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004328 }
drhd9e5c4f2010-05-12 18:01:39 +00004329 }
drh73b64e42010-05-30 19:55:15 +00004330
4331 /* Get the local shared locks */
4332 if( rc==SQLITE_OK ){
4333 p->sharedMask |= mask;
4334 }
4335 }else{
4336 /* Make sure no sibling connections hold locks that will block this
4337 ** lock. If any do, return SQLITE_BUSY right away.
4338 */
4339 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004340 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4341 rc = SQLITE_BUSY;
4342 break;
4343 }
4344 }
4345
4346 /* Get the exclusive locks at the system level. Then if successful
4347 ** also mark the local connection as being locked.
4348 */
4349 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004350 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004351 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004352 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004353 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004354 }
drhd9e5c4f2010-05-12 18:01:39 +00004355 }
4356 }
drhd91c68f2010-05-14 14:52:25 +00004357 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004358 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4359 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004360 return rc;
4361}
4362
drh286a2882010-05-20 23:51:06 +00004363/*
4364** Implement a memory barrier or memory fence on shared memory.
4365**
4366** All loads and stores begun before the barrier must complete before
4367** any load or store begun after the barrier.
4368*/
4369static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004370 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004371){
drhff828942010-06-26 21:34:06 +00004372 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004373 unixEnterMutex();
4374 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004375}
4376
dan18801912010-06-14 14:07:50 +00004377/*
danda9fe0c2010-07-13 18:44:03 +00004378** Close a connection to shared-memory. Delete the underlying
4379** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004380**
4381** If there is no shared memory associated with the connection then this
4382** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004383*/
danda9fe0c2010-07-13 18:44:03 +00004384static int unixShmUnmap(
4385 sqlite3_file *fd, /* The underlying database file */
4386 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004387){
danda9fe0c2010-07-13 18:44:03 +00004388 unixShm *p; /* The connection to be closed */
4389 unixShmNode *pShmNode; /* The underlying shared-memory file */
4390 unixShm **pp; /* For looping over sibling connections */
4391 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004392
danda9fe0c2010-07-13 18:44:03 +00004393 pDbFd = (unixFile*)fd;
4394 p = pDbFd->pShm;
4395 if( p==0 ) return SQLITE_OK;
4396 pShmNode = p->pShmNode;
4397
4398 assert( pShmNode==pDbFd->pInode->pShmNode );
4399 assert( pShmNode->pInode==pDbFd->pInode );
4400
4401 /* Remove connection p from the set of connections associated
4402 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004403 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004404 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4405 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004406
danda9fe0c2010-07-13 18:44:03 +00004407 /* Free the connection p */
4408 sqlite3_free(p);
4409 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004410 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004411
4412 /* If pShmNode->nRef has reached 0, then close the underlying
4413 ** shared-memory file, too */
4414 unixEnterMutex();
4415 assert( pShmNode->nRef>0 );
4416 pShmNode->nRef--;
4417 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004418 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004419 unixShmPurge(pDbFd);
4420 }
4421 unixLeaveMutex();
4422
4423 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004424}
drh286a2882010-05-20 23:51:06 +00004425
danda9fe0c2010-07-13 18:44:03 +00004426
drhd9e5c4f2010-05-12 18:01:39 +00004427#else
drh6b017cc2010-06-14 18:01:46 +00004428# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004429# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004430# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004431# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004432#endif /* #ifndef SQLITE_OMIT_WAL */
4433
drh734c9862008-11-28 15:37:20 +00004434/*
4435** Here ends the implementation of all sqlite3_file methods.
4436**
4437********************** End sqlite3_file Methods *******************************
4438******************************************************************************/
4439
4440/*
drh6b9d6dd2008-12-03 19:34:47 +00004441** This division contains definitions of sqlite3_io_methods objects that
4442** implement various file locking strategies. It also contains definitions
4443** of "finder" functions. A finder-function is used to locate the appropriate
4444** sqlite3_io_methods object for a particular database file. The pAppData
4445** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4446** the correct finder-function for that VFS.
4447**
4448** Most finder functions return a pointer to a fixed sqlite3_io_methods
4449** object. The only interesting finder-function is autolockIoFinder, which
4450** looks at the filesystem type and tries to guess the best locking
4451** strategy from that.
4452**
drh1875f7a2008-12-08 18:19:17 +00004453** For finder-funtion F, two objects are created:
4454**
4455** (1) The real finder-function named "FImpt()".
4456**
dane946c392009-08-22 11:39:46 +00004457** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004458**
4459**
4460** A pointer to the F pointer is used as the pAppData value for VFS
4461** objects. We have to do this instead of letting pAppData point
4462** directly at the finder-function since C90 rules prevent a void*
4463** from be cast into a function pointer.
4464**
drh6b9d6dd2008-12-03 19:34:47 +00004465**
drh7708e972008-11-29 00:56:52 +00004466** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004467**
drh7708e972008-11-29 00:56:52 +00004468** * A constant sqlite3_io_methods object call METHOD that has locking
4469** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4470**
4471** * An I/O method finder function called FINDER that returns a pointer
4472** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004473*/
drhd9e5c4f2010-05-12 18:01:39 +00004474#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004475static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004476 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004477 CLOSE, /* xClose */ \
4478 unixRead, /* xRead */ \
4479 unixWrite, /* xWrite */ \
4480 unixTruncate, /* xTruncate */ \
4481 unixSync, /* xSync */ \
4482 unixFileSize, /* xFileSize */ \
4483 LOCK, /* xLock */ \
4484 UNLOCK, /* xUnlock */ \
4485 CKLOCK, /* xCheckReservedLock */ \
4486 unixFileControl, /* xFileControl */ \
4487 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004488 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004489 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004490 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004491 unixShmBarrier, /* xShmBarrier */ \
danda9fe0c2010-07-13 18:44:03 +00004492 unixShmUnmap /* xShmUnmap */ \
drh7708e972008-11-29 00:56:52 +00004493}; \
drh0c2694b2009-09-03 16:23:44 +00004494static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4495 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004496 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004497} \
drh0c2694b2009-09-03 16:23:44 +00004498static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004499 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004500
4501/*
4502** Here are all of the sqlite3_io_methods objects for each of the
4503** locking strategies. Functions that return pointers to these methods
4504** are also created.
4505*/
4506IOMETHODS(
4507 posixIoFinder, /* Finder function name */
4508 posixIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004509 2, /* shared memory is enabled */
drh7708e972008-11-29 00:56:52 +00004510 unixClose, /* xClose method */
4511 unixLock, /* xLock method */
4512 unixUnlock, /* xUnlock method */
4513 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004514)
drh7708e972008-11-29 00:56:52 +00004515IOMETHODS(
4516 nolockIoFinder, /* Finder function name */
4517 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004518 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004519 nolockClose, /* xClose method */
4520 nolockLock, /* xLock method */
4521 nolockUnlock, /* xUnlock method */
4522 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004523)
drh7708e972008-11-29 00:56:52 +00004524IOMETHODS(
4525 dotlockIoFinder, /* Finder function name */
4526 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004527 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004528 dotlockClose, /* xClose method */
4529 dotlockLock, /* xLock method */
4530 dotlockUnlock, /* xUnlock method */
4531 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004532)
drh7708e972008-11-29 00:56:52 +00004533
chw78a13182009-04-07 05:35:03 +00004534#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004535IOMETHODS(
4536 flockIoFinder, /* Finder function name */
4537 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004538 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004539 flockClose, /* xClose method */
4540 flockLock, /* xLock method */
4541 flockUnlock, /* xUnlock method */
4542 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004543)
drh7708e972008-11-29 00:56:52 +00004544#endif
4545
drh6c7d5c52008-11-21 20:32:33 +00004546#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004547IOMETHODS(
4548 semIoFinder, /* Finder function name */
4549 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004550 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004551 semClose, /* xClose method */
4552 semLock, /* xLock method */
4553 semUnlock, /* xUnlock method */
4554 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004555)
aswiftaebf4132008-11-21 00:10:35 +00004556#endif
drh7708e972008-11-29 00:56:52 +00004557
drhd2cb50b2009-01-09 21:41:17 +00004558#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004559IOMETHODS(
4560 afpIoFinder, /* Finder function name */
4561 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004562 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004563 afpClose, /* xClose method */
4564 afpLock, /* xLock method */
4565 afpUnlock, /* xUnlock method */
4566 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004567)
drh715ff302008-12-03 22:32:44 +00004568#endif
4569
4570/*
4571** The proxy locking method is a "super-method" in the sense that it
4572** opens secondary file descriptors for the conch and lock files and
4573** it uses proxy, dot-file, AFP, and flock() locking methods on those
4574** secondary files. For this reason, the division that implements
4575** proxy locking is located much further down in the file. But we need
4576** to go ahead and define the sqlite3_io_methods and finder function
4577** for proxy locking here. So we forward declare the I/O methods.
4578*/
drhd2cb50b2009-01-09 21:41:17 +00004579#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00004580static int proxyClose(sqlite3_file*);
4581static int proxyLock(sqlite3_file*, int);
4582static int proxyUnlock(sqlite3_file*, int);
4583static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00004584IOMETHODS(
4585 proxyIoFinder, /* Finder function name */
4586 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004587 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004588 proxyClose, /* xClose method */
4589 proxyLock, /* xLock method */
4590 proxyUnlock, /* xUnlock method */
4591 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004592)
aswiftaebf4132008-11-21 00:10:35 +00004593#endif
drh7708e972008-11-29 00:56:52 +00004594
drh7ed97b92010-01-20 13:07:21 +00004595/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
4596#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4597IOMETHODS(
4598 nfsIoFinder, /* Finder function name */
4599 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004600 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00004601 unixClose, /* xClose method */
4602 unixLock, /* xLock method */
4603 nfsUnlock, /* xUnlock method */
4604 unixCheckReservedLock /* xCheckReservedLock method */
4605)
4606#endif
drh7708e972008-11-29 00:56:52 +00004607
drhd2cb50b2009-01-09 21:41:17 +00004608#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00004609/*
drh6b9d6dd2008-12-03 19:34:47 +00004610** This "finder" function attempts to determine the best locking strategy
4611** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00004612** object that implements that strategy.
4613**
4614** This is for MacOSX only.
4615*/
drh1875f7a2008-12-08 18:19:17 +00004616static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00004617 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004618 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00004619){
4620 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00004621 const char *zFilesystem; /* Filesystem type name */
4622 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00004623 } aMap[] = {
4624 { "hfs", &posixIoMethods },
4625 { "ufs", &posixIoMethods },
4626 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004627 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00004628 { "webdav", &nolockIoMethods },
4629 { 0, 0 }
4630 };
4631 int i;
4632 struct statfs fsInfo;
4633 struct flock lockInfo;
4634
4635 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00004636 /* If filePath==NULL that means we are dealing with a transient file
4637 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00004638 return &nolockIoMethods;
4639 }
4640 if( statfs(filePath, &fsInfo) != -1 ){
4641 if( fsInfo.f_flags & MNT_RDONLY ){
4642 return &nolockIoMethods;
4643 }
4644 for(i=0; aMap[i].zFilesystem; i++){
4645 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
4646 return aMap[i].pMethods;
4647 }
4648 }
4649 }
4650
4651 /* Default case. Handles, amongst others, "nfs".
4652 ** Test byte-range lock using fcntl(). If the call succeeds,
4653 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00004654 */
drh7708e972008-11-29 00:56:52 +00004655 lockInfo.l_len = 1;
4656 lockInfo.l_start = 0;
4657 lockInfo.l_whence = SEEK_SET;
4658 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004659 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00004660 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
4661 return &nfsIoMethods;
4662 } else {
4663 return &posixIoMethods;
4664 }
drh7708e972008-11-29 00:56:52 +00004665 }else{
4666 return &dotlockIoMethods;
4667 }
4668}
drh0c2694b2009-09-03 16:23:44 +00004669static const sqlite3_io_methods
4670 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00004671
drhd2cb50b2009-01-09 21:41:17 +00004672#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00004673
chw78a13182009-04-07 05:35:03 +00004674#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
4675/*
4676** This "finder" function attempts to determine the best locking strategy
4677** for the database file "filePath". It then returns the sqlite3_io_methods
4678** object that implements that strategy.
4679**
4680** This is for VXWorks only.
4681*/
4682static const sqlite3_io_methods *autolockIoFinderImpl(
4683 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00004684 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00004685){
4686 struct flock lockInfo;
4687
4688 if( !filePath ){
4689 /* If filePath==NULL that means we are dealing with a transient file
4690 ** that does not need to be locked. */
4691 return &nolockIoMethods;
4692 }
4693
4694 /* Test if fcntl() is supported and use POSIX style locks.
4695 ** Otherwise fall back to the named semaphore method.
4696 */
4697 lockInfo.l_len = 1;
4698 lockInfo.l_start = 0;
4699 lockInfo.l_whence = SEEK_SET;
4700 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00004701 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00004702 return &posixIoMethods;
4703 }else{
4704 return &semIoMethods;
4705 }
4706}
drh0c2694b2009-09-03 16:23:44 +00004707static const sqlite3_io_methods
4708 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00004709
4710#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
4711
drh7708e972008-11-29 00:56:52 +00004712/*
4713** An abstract type for a pointer to a IO method finder function:
4714*/
drh0c2694b2009-09-03 16:23:44 +00004715typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00004716
aswiftaebf4132008-11-21 00:10:35 +00004717
drh734c9862008-11-28 15:37:20 +00004718/****************************************************************************
4719**************************** sqlite3_vfs methods ****************************
4720**
4721** This division contains the implementation of methods on the
4722** sqlite3_vfs object.
4723*/
4724
danielk1977a3d4c882007-03-23 10:08:38 +00004725/*
danielk1977e339d652008-06-28 11:23:00 +00004726** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00004727*/
4728static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00004729 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00004730 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00004731 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00004732 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00004733 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00004734){
drh7708e972008-11-29 00:56:52 +00004735 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00004736 unixFile *pNew = (unixFile *)pId;
4737 int rc = SQLITE_OK;
4738
drh8af6c222010-05-14 12:43:01 +00004739 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00004740
dan00157392010-10-05 11:33:15 +00004741 /* Usually the path zFilename should not be a relative pathname. The
4742 ** exception is when opening the proxy "conch" file in builds that
4743 ** include the special Apple locking styles.
4744 */
dan00157392010-10-05 11:33:15 +00004745#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00004746 assert( zFilename==0 || zFilename[0]=='/'
4747 || pVfs->pAppData==(void*)&autolockIoFinder );
4748#else
4749 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00004750#endif
dan00157392010-10-05 11:33:15 +00004751
drhb07028f2011-10-14 21:49:18 +00004752 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00004753 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00004754
drh308c2a52010-05-14 11:30:18 +00004755 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00004756 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00004757 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00004758 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00004759 pNew->ctrlFlags = (u8)ctrlFlags;
4760 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
4761 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00004762 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00004763 }
drha7e61d82011-03-12 17:02:57 +00004764 if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
drhf12b3f62011-12-21 14:42:29 +00004765 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00004766 }
drh339eb0b2008-03-07 15:34:11 +00004767
drh6c7d5c52008-11-21 20:32:33 +00004768#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00004769 pNew->pId = vxworksFindFileId(zFilename);
4770 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00004771 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00004772 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00004773 }
4774#endif
4775
drhc02a43a2012-01-10 23:18:38 +00004776 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00004777 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00004778 }else{
drh0c2694b2009-09-03 16:23:44 +00004779 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00004780#if SQLITE_ENABLE_LOCKING_STYLE
4781 /* Cache zFilename in the locking context (AFP and dotlock override) for
4782 ** proxyLock activation is possible (remote proxy is based on db name)
4783 ** zFilename remains valid until file is closed, to support */
4784 pNew->lockingContext = (void*)zFilename;
4785#endif
drhda0e7682008-07-30 15:27:54 +00004786 }
danielk1977e339d652008-06-28 11:23:00 +00004787
drh7ed97b92010-01-20 13:07:21 +00004788 if( pLockingStyle == &posixIoMethods
4789#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4790 || pLockingStyle == &nfsIoMethods
4791#endif
4792 ){
drh7708e972008-11-29 00:56:52 +00004793 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004794 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00004795 if( rc!=SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00004796 /* If an error occured in findInodeInfo(), close the file descriptor
4797 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00004798 ** in two scenarios:
4799 **
4800 ** (a) A call to fstat() failed.
4801 ** (b) A malloc failed.
4802 **
4803 ** Scenario (b) may only occur if the process is holding no other
4804 ** file descriptors open on the same file. If there were other file
4805 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00004806 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00004807 ** handle h - as it is guaranteed that no posix locks will be released
4808 ** by doing so.
4809 **
4810 ** If scenario (a) caused the error then things are not so safe. The
4811 ** implicit assumption here is that if fstat() fails, things are in
4812 ** such bad shape that dropping a lock or two doesn't matter much.
4813 */
drh0e9365c2011-03-02 02:08:13 +00004814 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00004815 h = -1;
4816 }
drh7708e972008-11-29 00:56:52 +00004817 unixLeaveMutex();
4818 }
danielk1977e339d652008-06-28 11:23:00 +00004819
drhd2cb50b2009-01-09 21:41:17 +00004820#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00004821 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00004822 /* AFP locking uses the file path so it needs to be included in
4823 ** the afpLockingContext.
4824 */
4825 afpLockingContext *pCtx;
4826 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
4827 if( pCtx==0 ){
4828 rc = SQLITE_NOMEM;
4829 }else{
4830 /* NB: zFilename exists and remains valid until the file is closed
4831 ** according to requirement F11141. So we do not need to make a
4832 ** copy of the filename. */
4833 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00004834 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00004835 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00004836 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004837 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00004838 if( rc!=SQLITE_OK ){
4839 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00004840 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00004841 h = -1;
4842 }
drh7708e972008-11-29 00:56:52 +00004843 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00004844 }
drh7708e972008-11-29 00:56:52 +00004845 }
4846#endif
danielk1977e339d652008-06-28 11:23:00 +00004847
drh7708e972008-11-29 00:56:52 +00004848 else if( pLockingStyle == &dotlockIoMethods ){
4849 /* Dotfile locking uses the file path so it needs to be included in
4850 ** the dotlockLockingContext
4851 */
4852 char *zLockFile;
4853 int nFilename;
drhb07028f2011-10-14 21:49:18 +00004854 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00004855 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00004856 zLockFile = (char *)sqlite3_malloc(nFilename);
4857 if( zLockFile==0 ){
4858 rc = SQLITE_NOMEM;
4859 }else{
4860 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00004861 }
drh7708e972008-11-29 00:56:52 +00004862 pNew->lockingContext = zLockFile;
4863 }
danielk1977e339d652008-06-28 11:23:00 +00004864
drh6c7d5c52008-11-21 20:32:33 +00004865#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004866 else if( pLockingStyle == &semIoMethods ){
4867 /* Named semaphore locking uses the file path so it needs to be
4868 ** included in the semLockingContext
4869 */
4870 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00004871 rc = findInodeInfo(pNew, &pNew->pInode);
4872 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
4873 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00004874 int n;
drh2238dcc2009-08-27 17:56:20 +00004875 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00004876 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00004877 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00004878 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00004879 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
4880 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00004881 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00004882 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00004883 }
chw97185482008-11-17 08:05:31 +00004884 }
drh7708e972008-11-29 00:56:52 +00004885 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00004886 }
drh7708e972008-11-29 00:56:52 +00004887#endif
aswift5b1a2562008-08-22 00:22:35 +00004888
4889 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00004890#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00004891 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004892 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00004893 h = -1;
drh036ac7f2011-08-08 23:18:05 +00004894 osUnlink(zFilename);
chw97185482008-11-17 08:05:31 +00004895 isDelete = 0;
4896 }
drhc02a43a2012-01-10 23:18:38 +00004897 if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00004898#endif
danielk1977e339d652008-06-28 11:23:00 +00004899 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00004900 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00004901 }else{
drh7708e972008-11-29 00:56:52 +00004902 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00004903 OpenCounter(+1);
drhbfe66312006-10-03 17:40:40 +00004904 }
danielk1977e339d652008-06-28 11:23:00 +00004905 return rc;
drh054889e2005-11-30 03:20:31 +00004906}
drh9c06c952005-11-26 00:25:00 +00004907
danielk1977ad94b582007-08-20 06:44:22 +00004908/*
drh8b3cf822010-06-01 21:02:51 +00004909** Return the name of a directory in which to put temporary files.
4910** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00004911*/
drh7234c6d2010-06-19 15:10:09 +00004912static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00004913 static const char *azDirs[] = {
4914 0,
aswiftaebf4132008-11-21 00:10:35 +00004915 0,
danielk197717b90b52008-06-06 11:11:25 +00004916 "/var/tmp",
4917 "/usr/tmp",
4918 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00004919 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00004920 };
drh8b3cf822010-06-01 21:02:51 +00004921 unsigned int i;
4922 struct stat buf;
4923 const char *zDir = 0;
4924
4925 azDirs[0] = sqlite3_temp_directory;
4926 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00004927 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00004928 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00004929 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004930 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00004931 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00004932 break;
4933 }
4934 return zDir;
4935}
4936
4937/*
4938** Create a temporary file name in zBuf. zBuf must be allocated
4939** by the calling process and must be big enough to hold at least
4940** pVfs->mxPathname bytes.
4941*/
4942static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00004943 static const unsigned char zChars[] =
4944 "abcdefghijklmnopqrstuvwxyz"
4945 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4946 "0123456789";
drh41022642008-11-21 00:24:42 +00004947 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00004948 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00004949
4950 /* It's odd to simulate an io-error here, but really this is just
4951 ** using the io-error infrastructure to test that SQLite handles this
4952 ** function failing.
4953 */
4954 SimulateIOError( return SQLITE_IOERR );
4955
drh7234c6d2010-06-19 15:10:09 +00004956 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00004957 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00004958
4959 /* Check that the output buffer is large enough for the temporary file
4960 ** name. If it is not, return SQLITE_ERROR.
4961 */
drhc02a43a2012-01-10 23:18:38 +00004962 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00004963 return SQLITE_ERROR;
4964 }
4965
4966 do{
drhc02a43a2012-01-10 23:18:38 +00004967 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00004968 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00004969 sqlite3_randomness(15, &zBuf[j]);
4970 for(i=0; i<15; i++, j++){
4971 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
4972 }
4973 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00004974 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00004975 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00004976 return SQLITE_OK;
4977}
4978
drhd2cb50b2009-01-09 21:41:17 +00004979#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00004980/*
4981** Routine to transform a unixFile into a proxy-locking unixFile.
4982** Implementation in the proxy-lock division, but used by unixOpen()
4983** if SQLITE_PREFER_PROXY_LOCKING is defined.
4984*/
4985static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00004986#endif
drhc66d5b62008-12-03 22:48:32 +00004987
dan08da86a2009-08-21 17:18:03 +00004988/*
4989** Search for an unused file descriptor that was opened on the database
4990** file (not a journal or master-journal file) identified by pathname
4991** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
4992** argument to this function.
4993**
4994** Such a file descriptor may exist if a database connection was closed
4995** but the associated file descriptor could not be closed because some
4996** other file descriptor open on the same file is holding a file-lock.
4997** Refer to comments in the unixClose() function and the lengthy comment
4998** describing "Posix Advisory Locking" at the start of this file for
4999** further details. Also, ticket #4018.
5000**
5001** If a suitable file descriptor is found, then it is returned. If no
5002** such file descriptor is located, -1 is returned.
5003*/
dane946c392009-08-22 11:39:46 +00005004static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5005 UnixUnusedFd *pUnused = 0;
5006
5007 /* Do not search for an unused file descriptor on vxworks. Not because
5008 ** vxworks would not benefit from the change (it might, we're not sure),
5009 ** but because no way to test it is currently available. It is better
5010 ** not to risk breaking vxworks support for the sake of such an obscure
5011 ** feature. */
5012#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005013 struct stat sStat; /* Results of stat() call */
5014
5015 /* A stat() call may fail for various reasons. If this happens, it is
5016 ** almost certain that an open() call on the same path will also fail.
5017 ** For this reason, if an error occurs in the stat() call here, it is
5018 ** ignored and -1 is returned. The caller will try to open a new file
5019 ** descriptor on the same path, fail, and return an error to SQLite.
5020 **
5021 ** Even if a subsequent open() call does succeed, the consequences of
5022 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005023 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005024 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005025
5026 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005027 pInode = inodeList;
5028 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5029 || pInode->fileId.ino!=sStat.st_ino) ){
5030 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005031 }
drh8af6c222010-05-14 12:43:01 +00005032 if( pInode ){
dane946c392009-08-22 11:39:46 +00005033 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005034 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005035 pUnused = *pp;
5036 if( pUnused ){
5037 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005038 }
5039 }
5040 unixLeaveMutex();
5041 }
dane946c392009-08-22 11:39:46 +00005042#endif /* if !OS_VXWORKS */
5043 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005044}
danielk197717b90b52008-06-06 11:11:25 +00005045
5046/*
danddb0ac42010-07-14 14:48:58 +00005047** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005048** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005049** and a value suitable for passing as the third argument to open(2) is
5050** written to *pMode. If an IO error occurs, an SQLite error code is
5051** returned and the value of *pMode is not modified.
5052**
drh8c815d12012-02-13 20:16:37 +00005053** In most cases cases, this routine sets *pMode to 0, which will become
5054** an indication to robust_open() to create the file using
5055** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5056** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005057** this function queries the file-system for the permissions on the
5058** corresponding database file and sets *pMode to this value. Whenever
5059** possible, WAL and journal files are created using the same permissions
5060** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005061**
5062** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5063** original filename is unavailable. But 8_3_NAMES is only used for
5064** FAT filesystems and permissions do not matter there, so just use
5065** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005066*/
5067static int findCreateFileMode(
5068 const char *zPath, /* Path of file (possibly) being created */
5069 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005070 mode_t *pMode, /* OUT: Permissions to open file with */
5071 uid_t *pUid, /* OUT: uid to set on the file */
5072 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005073){
5074 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005075 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005076 *pUid = 0;
5077 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005078 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005079 char zDb[MAX_PATHNAME+1]; /* Database file path */
5080 int nDb; /* Number of valid bytes in zDb */
5081 struct stat sStat; /* Output of stat() on database file */
5082
dana0c989d2010-11-05 18:07:37 +00005083 /* zPath is a path to a WAL or journal file. The following block derives
5084 ** the path to the associated database file from zPath. This block handles
5085 ** the following naming conventions:
5086 **
5087 ** "<path to db>-journal"
5088 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005089 ** "<path to db>-journalNN"
5090 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005091 **
drhd337c5b2011-10-20 18:23:35 +00005092 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005093 ** used by the test_multiplex.c module.
5094 */
5095 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005096#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005097 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005098 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005099#else
5100 while( zPath[nDb]!='-' ){
5101 assert( nDb>0 );
5102 assert( zPath[nDb]!='\n' );
5103 nDb--;
5104 }
5105#endif
danddb0ac42010-07-14 14:48:58 +00005106 memcpy(zDb, zPath, nDb);
5107 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005108
drh58384f12011-07-28 00:14:45 +00005109 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005110 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005111 *pUid = sStat.st_uid;
5112 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005113 }else{
5114 rc = SQLITE_IOERR_FSTAT;
5115 }
5116 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5117 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005118 }
5119 return rc;
5120}
5121
5122/*
danielk1977ad94b582007-08-20 06:44:22 +00005123** Open the file zPath.
5124**
danielk1977b4b47412007-08-17 15:53:36 +00005125** Previously, the SQLite OS layer used three functions in place of this
5126** one:
5127**
5128** sqlite3OsOpenReadWrite();
5129** sqlite3OsOpenReadOnly();
5130** sqlite3OsOpenExclusive();
5131**
5132** These calls correspond to the following combinations of flags:
5133**
5134** ReadWrite() -> (READWRITE | CREATE)
5135** ReadOnly() -> (READONLY)
5136** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5137**
5138** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5139** true, the file was configured to be automatically deleted when the
5140** file handle closed. To achieve the same effect using this new
5141** interface, add the DELETEONCLOSE flag to those specified above for
5142** OpenExclusive().
5143*/
5144static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005145 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5146 const char *zPath, /* Pathname of file to be opened */
5147 sqlite3_file *pFile, /* The file descriptor to be filled in */
5148 int flags, /* Input flags to control the opening */
5149 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005150){
dan08da86a2009-08-21 17:18:03 +00005151 unixFile *p = (unixFile *)pFile;
5152 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005153 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005154 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005155 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005156 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005157 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005158
5159 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5160 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5161 int isCreate = (flags & SQLITE_OPEN_CREATE);
5162 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5163 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005164#if SQLITE_ENABLE_LOCKING_STYLE
5165 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5166#endif
drh3d4435b2011-08-26 20:55:50 +00005167#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5168 struct statfs fsInfo;
5169#endif
danielk1977b4b47412007-08-17 15:53:36 +00005170
danielk1977fee2d252007-08-18 10:59:19 +00005171 /* If creating a master or main-file journal, this function will open
5172 ** a file-descriptor on the directory too. The first time unixSync()
5173 ** is called the directory file descriptor will be fsync()ed and close()d.
5174 */
drh0059eae2011-08-08 23:48:40 +00005175 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005176 eType==SQLITE_OPEN_MASTER_JOURNAL
5177 || eType==SQLITE_OPEN_MAIN_JOURNAL
5178 || eType==SQLITE_OPEN_WAL
5179 ));
danielk1977fee2d252007-08-18 10:59:19 +00005180
danielk197717b90b52008-06-06 11:11:25 +00005181 /* If argument zPath is a NULL pointer, this function is required to open
5182 ** a temporary file. Use this buffer to store the file name in.
5183 */
drhc02a43a2012-01-10 23:18:38 +00005184 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005185 const char *zName = zPath;
5186
danielk1977fee2d252007-08-18 10:59:19 +00005187 /* Check the following statements are true:
5188 **
5189 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5190 ** (b) if CREATE is set, then READWRITE must also be set, and
5191 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005192 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005193 */
danielk1977b4b47412007-08-17 15:53:36 +00005194 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005195 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005196 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005197 assert(isDelete==0 || isCreate);
5198
danddb0ac42010-07-14 14:48:58 +00005199 /* The main DB, main journal, WAL file and master journal are never
5200 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005201 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5202 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5203 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005204 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005205
danielk1977fee2d252007-08-18 10:59:19 +00005206 /* Assert that the upper layer has set one of the "file-type" flags. */
5207 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5208 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5209 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005210 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005211 );
5212
dan08da86a2009-08-21 17:18:03 +00005213 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005214
dan08da86a2009-08-21 17:18:03 +00005215 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005216 UnixUnusedFd *pUnused;
5217 pUnused = findReusableFd(zName, flags);
5218 if( pUnused ){
5219 fd = pUnused->fd;
5220 }else{
dan6aa657f2009-08-24 18:57:58 +00005221 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005222 if( !pUnused ){
5223 return SQLITE_NOMEM;
5224 }
5225 }
5226 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005227
5228 /* Database filenames are double-zero terminated if they are not
5229 ** URIs with parameters. Hence, they can always be passed into
5230 ** sqlite3_uri_parameter(). */
5231 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5232
dan08da86a2009-08-21 17:18:03 +00005233 }else if( !zName ){
5234 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005235 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005236 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005237 if( rc!=SQLITE_OK ){
5238 return rc;
5239 }
5240 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005241
5242 /* Generated temporary filenames are always double-zero terminated
5243 ** for use by sqlite3_uri_parameter(). */
5244 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005245 }
5246
dan08da86a2009-08-21 17:18:03 +00005247 /* Determine the value of the flags parameter passed to POSIX function
5248 ** open(). These must be calculated even if open() is not called, as
5249 ** they may be stored as part of the file handle and used by the
5250 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005251 if( isReadonly ) openFlags |= O_RDONLY;
5252 if( isReadWrite ) openFlags |= O_RDWR;
5253 if( isCreate ) openFlags |= O_CREAT;
5254 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5255 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005256
danielk1977b4b47412007-08-17 15:53:36 +00005257 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005258 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005259 uid_t uid; /* Userid for the file */
5260 gid_t gid; /* Groupid for the file */
5261 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005262 if( rc!=SQLITE_OK ){
5263 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005264 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005265 return rc;
5266 }
drhad4f1e52011-03-04 15:43:57 +00005267 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005268 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005269 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5270 /* Failed to open the file for read/write access. Try read-only. */
5271 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005272 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005273 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005274 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005275 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005276 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005277 }
5278 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005279 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005280 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005281 }
drhac7c3ac2012-02-11 19:23:48 +00005282
5283 /* If this process is running as root and if creating a new rollback
5284 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005285 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005286 */
5287 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005288 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005289 }
danielk1977b4b47412007-08-17 15:53:36 +00005290 }
dan08da86a2009-08-21 17:18:03 +00005291 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005292 if( pOutFlags ){
5293 *pOutFlags = flags;
5294 }
5295
dane946c392009-08-22 11:39:46 +00005296 if( p->pUnused ){
5297 p->pUnused->fd = fd;
5298 p->pUnused->flags = flags;
5299 }
5300
danielk1977b4b47412007-08-17 15:53:36 +00005301 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005302#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005303 zPath = zName;
5304#else
drh036ac7f2011-08-08 23:18:05 +00005305 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005306#endif
danielk1977b4b47412007-08-17 15:53:36 +00005307 }
drh41022642008-11-21 00:24:42 +00005308#if SQLITE_ENABLE_LOCKING_STYLE
5309 else{
dan08da86a2009-08-21 17:18:03 +00005310 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005311 }
5312#endif
5313
drhda0e7682008-07-30 15:27:54 +00005314 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005315
drh7ed97b92010-01-20 13:07:21 +00005316
5317#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005318 if( fstatfs(fd, &fsInfo) == -1 ){
5319 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005320 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005321 return SQLITE_IOERR_ACCESS;
5322 }
5323 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5324 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5325 }
5326#endif
drhc02a43a2012-01-10 23:18:38 +00005327
5328 /* Set up appropriate ctrlFlags */
5329 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5330 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5331 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5332 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5333 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5334
drh7ed97b92010-01-20 13:07:21 +00005335#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005336#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005337 isAutoProxy = 1;
5338#endif
5339 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005340 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5341 int useProxy = 0;
5342
dan08da86a2009-08-21 17:18:03 +00005343 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5344 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005345 if( envforce!=NULL ){
5346 useProxy = atoi(envforce)>0;
5347 }else{
aswiftaebf4132008-11-21 00:10:35 +00005348 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005349 /* In theory, the close(fd) call is sub-optimal. If the file opened
5350 ** with fd is a database file, and there are other connections open
5351 ** on that file that are currently holding advisory locks on it,
5352 ** then the call to close() will cancel those locks. In practice,
5353 ** we're assuming that statfs() doesn't fail very often. At least
5354 ** not while other file descriptors opened by the same process on
5355 ** the same file are working. */
5356 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005357 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005358 rc = SQLITE_IOERR_ACCESS;
5359 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005360 }
5361 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5362 }
5363 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005364 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005365 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005366 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005367 if( rc!=SQLITE_OK ){
5368 /* Use unixClose to clean up the resources added in fillInUnixFile
5369 ** and clear all the structure's references. Specifically,
5370 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5371 */
5372 unixClose(pFile);
5373 return rc;
5374 }
aswiftaebf4132008-11-21 00:10:35 +00005375 }
dane946c392009-08-22 11:39:46 +00005376 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005377 }
5378 }
5379#endif
5380
drhc02a43a2012-01-10 23:18:38 +00005381 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5382
dane946c392009-08-22 11:39:46 +00005383open_finished:
5384 if( rc!=SQLITE_OK ){
5385 sqlite3_free(p->pUnused);
5386 }
5387 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005388}
5389
dane946c392009-08-22 11:39:46 +00005390
danielk1977b4b47412007-08-17 15:53:36 +00005391/*
danielk1977fee2d252007-08-18 10:59:19 +00005392** Delete the file at zPath. If the dirSync argument is true, fsync()
5393** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005394*/
drh6b9d6dd2008-12-03 19:34:47 +00005395static int unixDelete(
5396 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5397 const char *zPath, /* Name of file to be deleted */
5398 int dirSync /* If true, fsync() directory after deleting file */
5399){
danielk1977fee2d252007-08-18 10:59:19 +00005400 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005401 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005402 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005403 if( osUnlink(zPath)==(-1) ){
5404 if( errno==ENOENT ){
5405 rc = SQLITE_IOERR_DELETE_NOENT;
5406 }else{
drhb4308162012-11-09 21:40:02 +00005407 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005408 }
drhb4308162012-11-09 21:40:02 +00005409 return rc;
drh5d4feff2010-07-14 01:45:22 +00005410 }
danielk1977d39fa702008-10-16 13:27:40 +00005411#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005412 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005413 int fd;
drh90315a22011-08-10 01:52:12 +00005414 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005415 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005416#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005417 if( fsync(fd)==-1 )
5418#else
5419 if( fsync(fd) )
5420#endif
5421 {
dane18d4952011-02-21 11:46:24 +00005422 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005423 }
drh0e9365c2011-03-02 02:08:13 +00005424 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005425 }else if( rc==SQLITE_CANTOPEN ){
5426 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005427 }
5428 }
danielk1977d138dd82008-10-15 16:02:48 +00005429#endif
danielk1977fee2d252007-08-18 10:59:19 +00005430 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005431}
5432
danielk197790949c22007-08-17 16:50:38 +00005433/*
5434** Test the existance of or access permissions of file zPath. The
5435** test performed depends on the value of flags:
5436**
5437** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5438** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5439** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5440**
5441** Otherwise return 0.
5442*/
danielk1977861f7452008-06-05 11:39:11 +00005443static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005444 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5445 const char *zPath, /* Path of the file to examine */
5446 int flags, /* What do we want to learn about the zPath file? */
5447 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005448){
rse25c0d1a2007-09-20 08:38:14 +00005449 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005450 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005451 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005452 switch( flags ){
5453 case SQLITE_ACCESS_EXISTS:
5454 amode = F_OK;
5455 break;
5456 case SQLITE_ACCESS_READWRITE:
5457 amode = W_OK|R_OK;
5458 break;
drh50d3f902007-08-27 21:10:36 +00005459 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005460 amode = R_OK;
5461 break;
5462
5463 default:
5464 assert(!"Invalid flags argument");
5465 }
drh99ab3b12011-03-02 15:09:07 +00005466 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005467 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5468 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005469 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005470 *pResOut = 0;
5471 }
5472 }
danielk1977861f7452008-06-05 11:39:11 +00005473 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005474}
5475
danielk1977b4b47412007-08-17 15:53:36 +00005476
5477/*
5478** Turn a relative pathname into a full pathname. The relative path
5479** is stored as a nul-terminated string in the buffer pointed to by
5480** zPath.
5481**
5482** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5483** (in this case, MAX_PATHNAME bytes). The full-path is written to
5484** this buffer before returning.
5485*/
danielk1977adfb9b02007-09-17 07:02:56 +00005486static int unixFullPathname(
5487 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5488 const char *zPath, /* Possibly relative input path */
5489 int nOut, /* Size of output buffer in bytes */
5490 char *zOut /* Output buffer */
5491){
danielk1977843e65f2007-09-01 16:16:15 +00005492
5493 /* It's odd to simulate an io-error here, but really this is just
5494 ** using the io-error infrastructure to test that SQLite handles this
5495 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005496 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005497 */
5498 SimulateIOError( return SQLITE_ERROR );
5499
drh153c62c2007-08-24 03:51:33 +00005500 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005501 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005502
drh3c7f2dc2007-12-06 13:26:20 +00005503 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005504 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005505 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005506 }else{
5507 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005508 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005509 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005510 }
drhea678832008-12-10 19:26:22 +00005511 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005512 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005513 }
5514 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005515}
5516
drh0ccebe72005-06-07 22:22:50 +00005517
drh761df872006-12-21 01:29:22 +00005518#ifndef SQLITE_OMIT_LOAD_EXTENSION
5519/*
5520** Interfaces for opening a shared library, finding entry points
5521** within the shared library, and closing the shared library.
5522*/
5523#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00005524static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
5525 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00005526 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
5527}
danielk197795c8a542007-09-01 06:51:27 +00005528
5529/*
5530** SQLite calls this function immediately after a call to unixDlSym() or
5531** unixDlOpen() fails (returns a null pointer). If a more detailed error
5532** message is available, it is written to zBufOut. If no error message
5533** is available, zBufOut is left unmodified and SQLite uses a default
5534** error message.
5535*/
danielk1977397d65f2008-11-19 11:35:39 +00005536static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00005537 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00005538 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00005539 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005540 zErr = dlerror();
5541 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00005542 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00005543 }
drh6c7d5c52008-11-21 20:32:33 +00005544 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00005545}
drh1875f7a2008-12-08 18:19:17 +00005546static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
5547 /*
5548 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
5549 ** cast into a pointer to a function. And yet the library dlsym() routine
5550 ** returns a void* which is really a pointer to a function. So how do we
5551 ** use dlsym() with -pedantic-errors?
5552 **
5553 ** Variable x below is defined to be a pointer to a function taking
5554 ** parameters void* and const char* and returning a pointer to a function.
5555 ** We initialize x by assigning it a pointer to the dlsym() function.
5556 ** (That assignment requires a cast.) Then we call the function that
5557 ** x points to.
5558 **
5559 ** This work-around is unlikely to work correctly on any system where
5560 ** you really cannot cast a function pointer into void*. But then, on the
5561 ** other hand, dlsym() will not work on such a system either, so we have
5562 ** not really lost anything.
5563 */
5564 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00005565 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00005566 x = (void(*(*)(void*,const char*))(void))dlsym;
5567 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00005568}
danielk1977397d65f2008-11-19 11:35:39 +00005569static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
5570 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005571 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00005572}
danielk1977b4b47412007-08-17 15:53:36 +00005573#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
5574 #define unixDlOpen 0
5575 #define unixDlError 0
5576 #define unixDlSym 0
5577 #define unixDlClose 0
5578#endif
5579
5580/*
danielk197790949c22007-08-17 16:50:38 +00005581** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00005582*/
danielk1977397d65f2008-11-19 11:35:39 +00005583static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
5584 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00005585 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00005586
drhbbd42a62004-05-22 17:41:58 +00005587 /* We have to initialize zBuf to prevent valgrind from reporting
5588 ** errors. The reports issued by valgrind are incorrect - we would
5589 ** prefer that the randomness be increased by making use of the
5590 ** uninitialized space in zBuf - but valgrind errors tend to worry
5591 ** some users. Rather than argue, it seems easier just to initialize
5592 ** the whole array and silence valgrind, even if that means less randomness
5593 ** in the random seed.
5594 **
5595 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00005596 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00005597 ** tests repeatable.
5598 */
danielk1977b4b47412007-08-17 15:53:36 +00005599 memset(zBuf, 0, nBuf);
drhbbd42a62004-05-22 17:41:58 +00005600#if !defined(SQLITE_TEST)
5601 {
drhc18b4042012-02-10 03:10:27 +00005602 int pid, fd, got;
drhad4f1e52011-03-04 15:43:57 +00005603 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00005604 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00005605 time_t t;
5606 time(&t);
danielk197790949c22007-08-17 16:50:38 +00005607 memcpy(zBuf, &t, sizeof(t));
5608 pid = getpid();
5609 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
danielk197700e13612008-11-17 19:18:54 +00005610 assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
drh72cbd072008-10-14 17:58:38 +00005611 nBuf = sizeof(t) + sizeof(pid);
drh842b8642005-01-21 17:53:17 +00005612 }else{
drhc18b4042012-02-10 03:10:27 +00005613 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00005614 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00005615 }
drhbbd42a62004-05-22 17:41:58 +00005616 }
5617#endif
drh72cbd072008-10-14 17:58:38 +00005618 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00005619}
5620
danielk1977b4b47412007-08-17 15:53:36 +00005621
drhbbd42a62004-05-22 17:41:58 +00005622/*
5623** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00005624** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00005625** The return value is the number of microseconds of sleep actually
5626** requested from the underlying operating system, a number which
5627** might be greater than or equal to the argument, but not less
5628** than the argument.
drhbbd42a62004-05-22 17:41:58 +00005629*/
danielk1977397d65f2008-11-19 11:35:39 +00005630static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00005631#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005632 struct timespec sp;
5633
5634 sp.tv_sec = microseconds / 1000000;
5635 sp.tv_nsec = (microseconds % 1000000) * 1000;
5636 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00005637 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00005638 return microseconds;
5639#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00005640 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00005641 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005642 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00005643#else
danielk1977b4b47412007-08-17 15:53:36 +00005644 int seconds = (microseconds+999999)/1000000;
5645 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00005646 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00005647 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00005648#endif
drh88f474a2006-01-02 20:00:12 +00005649}
5650
5651/*
drh6b9d6dd2008-12-03 19:34:47 +00005652** The following variable, if set to a non-zero value, is interpreted as
5653** the number of seconds since 1970 and is used to set the result of
5654** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00005655*/
5656#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00005657int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00005658#endif
5659
5660/*
drhb7e8ea22010-05-03 14:32:30 +00005661** Find the current time (in Universal Coordinated Time). Write into *piNow
5662** the current time and date as a Julian Day number times 86_400_000. In
5663** other words, write into *piNow the number of milliseconds since the Julian
5664** epoch of noon in Greenwich on November 24, 4714 B.C according to the
5665** proleptic Gregorian calendar.
5666**
drh31702252011-10-12 23:13:43 +00005667** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
5668** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00005669*/
5670static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
5671 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00005672 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00005673#if defined(NO_GETTOD)
5674 time_t t;
5675 time(&t);
dan15eac4e2010-11-22 17:26:07 +00005676 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00005677#elif OS_VXWORKS
5678 struct timespec sNow;
5679 clock_gettime(CLOCK_REALTIME, &sNow);
5680 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
5681#else
5682 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00005683 if( gettimeofday(&sNow, 0)==0 ){
5684 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
5685 }else{
5686 rc = SQLITE_ERROR;
5687 }
drhb7e8ea22010-05-03 14:32:30 +00005688#endif
5689
5690#ifdef SQLITE_TEST
5691 if( sqlite3_current_time ){
5692 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
5693 }
5694#endif
5695 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005696 return rc;
drhb7e8ea22010-05-03 14:32:30 +00005697}
5698
5699/*
drhbbd42a62004-05-22 17:41:58 +00005700** Find the current time (in Universal Coordinated Time). Write the
5701** current time and date as a Julian Day number into *prNow and
5702** return 0. Return 1 if the time and date cannot be found.
5703*/
danielk1977397d65f2008-11-19 11:35:39 +00005704static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00005705 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00005706 int rc;
drhff828942010-06-26 21:34:06 +00005707 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00005708 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00005709 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00005710 return rc;
drhbbd42a62004-05-22 17:41:58 +00005711}
danielk1977b4b47412007-08-17 15:53:36 +00005712
drh6b9d6dd2008-12-03 19:34:47 +00005713/*
5714** We added the xGetLastError() method with the intention of providing
5715** better low-level error messages when operating-system problems come up
5716** during SQLite operation. But so far, none of that has been implemented
5717** in the core. So this routine is never called. For now, it is merely
5718** a place-holder.
5719*/
danielk1977397d65f2008-11-19 11:35:39 +00005720static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
5721 UNUSED_PARAMETER(NotUsed);
5722 UNUSED_PARAMETER(NotUsed2);
5723 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00005724 return 0;
5725}
5726
drhf2424c52010-04-26 00:04:55 +00005727
5728/*
drh734c9862008-11-28 15:37:20 +00005729************************ End of sqlite3_vfs methods ***************************
5730******************************************************************************/
5731
drh715ff302008-12-03 22:32:44 +00005732/******************************************************************************
5733************************** Begin Proxy Locking ********************************
5734**
5735** Proxy locking is a "uber-locking-method" in this sense: It uses the
5736** other locking methods on secondary lock files. Proxy locking is a
5737** meta-layer over top of the primitive locking implemented above. For
5738** this reason, the division that implements of proxy locking is deferred
5739** until late in the file (here) after all of the other I/O methods have
5740** been defined - so that the primitive locking methods are available
5741** as services to help with the implementation of proxy locking.
5742**
5743****
5744**
5745** The default locking schemes in SQLite use byte-range locks on the
5746** database file to coordinate safe, concurrent access by multiple readers
5747** and writers [http://sqlite.org/lockingv3.html]. The five file locking
5748** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
5749** as POSIX read & write locks over fixed set of locations (via fsctl),
5750** on AFP and SMB only exclusive byte-range locks are available via fsctl
5751** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
5752** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
5753** address in the shared range is taken for a SHARED lock, the entire
5754** shared range is taken for an EXCLUSIVE lock):
5755**
drhf2f105d2012-08-20 15:53:54 +00005756** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00005757** RESERVED_BYTE 0x40000001
5758** SHARED_RANGE 0x40000002 -> 0x40000200
5759**
5760** This works well on the local file system, but shows a nearly 100x
5761** slowdown in read performance on AFP because the AFP client disables
5762** the read cache when byte-range locks are present. Enabling the read
5763** cache exposes a cache coherency problem that is present on all OS X
5764** supported network file systems. NFS and AFP both observe the
5765** close-to-open semantics for ensuring cache coherency
5766** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
5767** address the requirements for concurrent database access by multiple
5768** readers and writers
5769** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
5770**
5771** To address the performance and cache coherency issues, proxy file locking
5772** changes the way database access is controlled by limiting access to a
5773** single host at a time and moving file locks off of the database file
5774** and onto a proxy file on the local file system.
5775**
5776**
5777** Using proxy locks
5778** -----------------
5779**
5780** C APIs
5781**
5782** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
5783** <proxy_path> | ":auto:");
5784** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
5785**
5786**
5787** SQL pragmas
5788**
5789** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
5790** PRAGMA [database.]lock_proxy_file
5791**
5792** Specifying ":auto:" means that if there is a conch file with a matching
5793** host ID in it, the proxy path in the conch file will be used, otherwise
5794** a proxy path based on the user's temp dir
5795** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
5796** actual proxy file name is generated from the name and path of the
5797** database file. For example:
5798**
5799** For database path "/Users/me/foo.db"
5800** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
5801**
5802** Once a lock proxy is configured for a database connection, it can not
5803** be removed, however it may be switched to a different proxy path via
5804** the above APIs (assuming the conch file is not being held by another
5805** connection or process).
5806**
5807**
5808** How proxy locking works
5809** -----------------------
5810**
5811** Proxy file locking relies primarily on two new supporting files:
5812**
5813** * conch file to limit access to the database file to a single host
5814** at a time
5815**
5816** * proxy file to act as a proxy for the advisory locks normally
5817** taken on the database
5818**
5819** The conch file - to use a proxy file, sqlite must first "hold the conch"
5820** by taking an sqlite-style shared lock on the conch file, reading the
5821** contents and comparing the host's unique host ID (see below) and lock
5822** proxy path against the values stored in the conch. The conch file is
5823** stored in the same directory as the database file and the file name
5824** is patterned after the database file name as ".<databasename>-conch".
5825** If the conch file does not exist, or it's contents do not match the
5826** host ID and/or proxy path, then the lock is escalated to an exclusive
5827** lock and the conch file contents is updated with the host ID and proxy
5828** path and the lock is downgraded to a shared lock again. If the conch
5829** is held by another process (with a shared lock), the exclusive lock
5830** will fail and SQLITE_BUSY is returned.
5831**
5832** The proxy file - a single-byte file used for all advisory file locks
5833** normally taken on the database file. This allows for safe sharing
5834** of the database file for multiple readers and writers on the same
5835** host (the conch ensures that they all use the same local lock file).
5836**
drh715ff302008-12-03 22:32:44 +00005837** Requesting the lock proxy does not immediately take the conch, it is
5838** only taken when the first request to lock database file is made.
5839** This matches the semantics of the traditional locking behavior, where
5840** opening a connection to a database file does not take a lock on it.
5841** The shared lock and an open file descriptor are maintained until
5842** the connection to the database is closed.
5843**
5844** The proxy file and the lock file are never deleted so they only need
5845** to be created the first time they are used.
5846**
5847** Configuration options
5848** ---------------------
5849**
5850** SQLITE_PREFER_PROXY_LOCKING
5851**
5852** Database files accessed on non-local file systems are
5853** automatically configured for proxy locking, lock files are
5854** named automatically using the same logic as
5855** PRAGMA lock_proxy_file=":auto:"
5856**
5857** SQLITE_PROXY_DEBUG
5858**
5859** Enables the logging of error messages during host id file
5860** retrieval and creation
5861**
drh715ff302008-12-03 22:32:44 +00005862** LOCKPROXYDIR
5863**
5864** Overrides the default directory used for lock proxy files that
5865** are named automatically via the ":auto:" setting
5866**
5867** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
5868**
5869** Permissions to use when creating a directory for storing the
5870** lock proxy files, only used when LOCKPROXYDIR is not set.
5871**
5872**
5873** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
5874** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
5875** force proxy locking to be used for every database file opened, and 0
5876** will force automatic proxy locking to be disabled for all database
5877** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
5878** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
5879*/
5880
5881/*
5882** Proxy locking is only available on MacOSX
5883*/
drhd2cb50b2009-01-09 21:41:17 +00005884#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005885
drh715ff302008-12-03 22:32:44 +00005886/*
5887** The proxyLockingContext has the path and file structures for the remote
5888** and local proxy files in it
5889*/
5890typedef struct proxyLockingContext proxyLockingContext;
5891struct proxyLockingContext {
5892 unixFile *conchFile; /* Open conch file */
5893 char *conchFilePath; /* Name of the conch file */
5894 unixFile *lockProxy; /* Open proxy lock file */
5895 char *lockProxyPath; /* Name of the proxy lock file */
5896 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00005897 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00005898 void *oldLockingContext; /* Original lockingcontext to restore on close */
5899 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
5900};
5901
drh7ed97b92010-01-20 13:07:21 +00005902/*
5903** The proxy lock file path for the database at dbPath is written into lPath,
5904** which must point to valid, writable memory large enough for a maxLen length
5905** file path.
drh715ff302008-12-03 22:32:44 +00005906*/
drh715ff302008-12-03 22:32:44 +00005907static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
5908 int len;
5909 int dbLen;
5910 int i;
5911
5912#ifdef LOCKPROXYDIR
5913 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
5914#else
5915# ifdef _CS_DARWIN_USER_TEMP_DIR
5916 {
drh7ed97b92010-01-20 13:07:21 +00005917 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00005918 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
5919 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005920 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00005921 }
drh7ed97b92010-01-20 13:07:21 +00005922 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00005923 }
5924# else
5925 len = strlcpy(lPath, "/tmp/", maxLen);
5926# endif
5927#endif
5928
5929 if( lPath[len-1]!='/' ){
5930 len = strlcat(lPath, "/", maxLen);
5931 }
5932
5933 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00005934 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00005935 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00005936 char c = dbPath[i];
5937 lPath[i+len] = (c=='/')?'_':c;
5938 }
5939 lPath[i+len]='\0';
5940 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00005941 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00005942 return SQLITE_OK;
5943}
5944
drh7ed97b92010-01-20 13:07:21 +00005945/*
5946 ** Creates the lock file and any missing directories in lockPath
5947 */
5948static int proxyCreateLockPath(const char *lockPath){
5949 int i, len;
5950 char buf[MAXPATHLEN];
5951 int start = 0;
5952
5953 assert(lockPath!=NULL);
5954 /* try to create all the intermediate directories */
5955 len = (int)strlen(lockPath);
5956 buf[0] = lockPath[0];
5957 for( i=1; i<len; i++ ){
5958 if( lockPath[i] == '/' && (i - start > 0) ){
5959 /* only mkdir if leaf dir != "." or "/" or ".." */
5960 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5961 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5962 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00005963 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00005964 int err=errno;
5965 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00005966 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00005967 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00005968 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005969 return err;
5970 }
5971 }
5972 }
5973 start=i+1;
5974 }
5975 buf[i] = lockPath[i];
5976 }
drh308c2a52010-05-14 11:30:18 +00005977 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00005978 return 0;
5979}
5980
drh715ff302008-12-03 22:32:44 +00005981/*
5982** Create a new VFS file descriptor (stored in memory obtained from
5983** sqlite3_malloc) and open the file named "path" in the file descriptor.
5984**
5985** The caller is responsible not only for closing the file descriptor
5986** but also for freeing the memory associated with the file descriptor.
5987*/
drh7ed97b92010-01-20 13:07:21 +00005988static int proxyCreateUnixFile(
5989 const char *path, /* path for the new unixFile */
5990 unixFile **ppFile, /* unixFile created and returned by ref */
5991 int islockfile /* if non zero missing dirs will be created */
5992) {
5993 int fd = -1;
drh715ff302008-12-03 22:32:44 +00005994 unixFile *pNew;
5995 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00005996 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00005997 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00005998 int terrno = 0;
5999 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006000
drh7ed97b92010-01-20 13:07:21 +00006001 /* 1. first try to open/create the file
6002 ** 2. if that fails, and this is a lock file (not-conch), try creating
6003 ** the parent directories and then try again.
6004 ** 3. if that fails, try to open the file read-only
6005 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6006 */
6007 pUnused = findReusableFd(path, openFlags);
6008 if( pUnused ){
6009 fd = pUnused->fd;
6010 }else{
6011 pUnused = sqlite3_malloc(sizeof(*pUnused));
6012 if( !pUnused ){
6013 return SQLITE_NOMEM;
6014 }
6015 }
6016 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006017 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006018 terrno = errno;
6019 if( fd<0 && errno==ENOENT && islockfile ){
6020 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006021 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006022 }
6023 }
6024 }
6025 if( fd<0 ){
6026 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006027 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006028 terrno = errno;
6029 }
6030 if( fd<0 ){
6031 if( islockfile ){
6032 return SQLITE_BUSY;
6033 }
6034 switch (terrno) {
6035 case EACCES:
6036 return SQLITE_PERM;
6037 case EIO:
6038 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6039 default:
drh9978c972010-02-23 17:36:32 +00006040 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006041 }
6042 }
6043
6044 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6045 if( pNew==NULL ){
6046 rc = SQLITE_NOMEM;
6047 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006048 }
6049 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006050 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006051 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006052 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006053 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006054 pUnused->fd = fd;
6055 pUnused->flags = openFlags;
6056 pNew->pUnused = pUnused;
6057
drhc02a43a2012-01-10 23:18:38 +00006058 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006059 if( rc==SQLITE_OK ){
6060 *ppFile = pNew;
6061 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006062 }
drh7ed97b92010-01-20 13:07:21 +00006063end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006064 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006065 sqlite3_free(pNew);
6066 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006067 return rc;
6068}
6069
drh7ed97b92010-01-20 13:07:21 +00006070#ifdef SQLITE_TEST
6071/* simulate multiple hosts by creating unique hostid file paths */
6072int sqlite3_hostid_num = 0;
6073#endif
6074
6075#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6076
drh0ab216a2010-07-02 17:10:40 +00006077/* Not always defined in the headers as it ought to be */
6078extern int gethostuuid(uuid_t id, const struct timespec *wait);
6079
drh7ed97b92010-01-20 13:07:21 +00006080/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6081** bytes of writable memory.
6082*/
6083static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006084 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6085 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006086#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6087 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006088 {
6089 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6090 if( gethostuuid(pHostID, &timeout) ){
6091 int err = errno;
6092 if( pError ){
6093 *pError = err;
6094 }
6095 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006096 }
drh7ed97b92010-01-20 13:07:21 +00006097 }
drh3d4435b2011-08-26 20:55:50 +00006098#else
6099 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006100#endif
drh7ed97b92010-01-20 13:07:21 +00006101#ifdef SQLITE_TEST
6102 /* simulate multiple hosts by creating unique hostid file paths */
6103 if( sqlite3_hostid_num != 0){
6104 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6105 }
6106#endif
6107
6108 return SQLITE_OK;
6109}
6110
6111/* The conch file contains the header, host id and lock file path
6112 */
6113#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6114#define PROXY_HEADERLEN 1 /* conch file header length */
6115#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6116#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6117
6118/*
6119** Takes an open conch file, copies the contents to a new path and then moves
6120** it back. The newly created file's file descriptor is assigned to the
6121** conch file structure and finally the original conch file descriptor is
6122** closed. Returns zero if successful.
6123*/
6124static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6125 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6126 unixFile *conchFile = pCtx->conchFile;
6127 char tPath[MAXPATHLEN];
6128 char buf[PROXY_MAXCONCHLEN];
6129 char *cPath = pCtx->conchFilePath;
6130 size_t readLen = 0;
6131 size_t pathLen = 0;
6132 char errmsg[64] = "";
6133 int fd = -1;
6134 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006135 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006136
6137 /* create a new path by replace the trailing '-conch' with '-break' */
6138 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6139 if( pathLen>MAXPATHLEN || pathLen<6 ||
6140 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006141 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006142 goto end_breaklock;
6143 }
6144 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006145 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006146 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006147 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006148 goto end_breaklock;
6149 }
6150 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006151 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006152 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006153 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006154 goto end_breaklock;
6155 }
drhe562be52011-03-02 18:01:10 +00006156 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006157 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006158 goto end_breaklock;
6159 }
6160 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006161 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006162 goto end_breaklock;
6163 }
6164 rc = 0;
6165 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006166 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006167 conchFile->h = fd;
6168 conchFile->openFlags = O_RDWR | O_CREAT;
6169
6170end_breaklock:
6171 if( rc ){
6172 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006173 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006174 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006175 }
6176 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6177 }
6178 return rc;
6179}
6180
6181/* Take the requested lock on the conch file and break a stale lock if the
6182** host id matches.
6183*/
6184static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6185 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6186 unixFile *conchFile = pCtx->conchFile;
6187 int rc = SQLITE_OK;
6188 int nTries = 0;
6189 struct timespec conchModTime;
6190
drh3d4435b2011-08-26 20:55:50 +00006191 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006192 do {
6193 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6194 nTries ++;
6195 if( rc==SQLITE_BUSY ){
6196 /* If the lock failed (busy):
6197 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6198 * 2nd try: fail if the mod time changed or host id is different, wait
6199 * 10 sec and try again
6200 * 3rd try: break the lock unless the mod time has changed.
6201 */
6202 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006203 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006204 pFile->lastErrno = errno;
6205 return SQLITE_IOERR_LOCK;
6206 }
6207
6208 if( nTries==1 ){
6209 conchModTime = buf.st_mtimespec;
6210 usleep(500000); /* wait 0.5 sec and try the lock again*/
6211 continue;
6212 }
6213
6214 assert( nTries>1 );
6215 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6216 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6217 return SQLITE_BUSY;
6218 }
6219
6220 if( nTries==2 ){
6221 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006222 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006223 if( len<0 ){
6224 pFile->lastErrno = errno;
6225 return SQLITE_IOERR_LOCK;
6226 }
6227 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6228 /* don't break the lock if the host id doesn't match */
6229 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6230 return SQLITE_BUSY;
6231 }
6232 }else{
6233 /* don't break the lock on short read or a version mismatch */
6234 return SQLITE_BUSY;
6235 }
6236 usleep(10000000); /* wait 10 sec and try the lock again */
6237 continue;
6238 }
6239
6240 assert( nTries==3 );
6241 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6242 rc = SQLITE_OK;
6243 if( lockType==EXCLUSIVE_LOCK ){
6244 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6245 }
6246 if( !rc ){
6247 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6248 }
6249 }
6250 }
6251 } while( rc==SQLITE_BUSY && nTries<3 );
6252
6253 return rc;
6254}
6255
6256/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006257** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6258** lockPath means that the lockPath in the conch file will be used if the
6259** host IDs match, or a new lock path will be generated automatically
6260** and written to the conch file.
6261*/
6262static int proxyTakeConch(unixFile *pFile){
6263 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6264
drh7ed97b92010-01-20 13:07:21 +00006265 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006266 return SQLITE_OK;
6267 }else{
6268 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006269 uuid_t myHostID;
6270 int pError = 0;
6271 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006272 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006273 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006274 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006275 int createConch = 0;
6276 int hostIdMatch = 0;
6277 int readLen = 0;
6278 int tryOldLockPath = 0;
6279 int forceNewLockPath = 0;
6280
drh308c2a52010-05-14 11:30:18 +00006281 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6282 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006283
drh7ed97b92010-01-20 13:07:21 +00006284 rc = proxyGetHostID(myHostID, &pError);
6285 if( (rc&0xff)==SQLITE_IOERR ){
6286 pFile->lastErrno = pError;
6287 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006288 }
drh7ed97b92010-01-20 13:07:21 +00006289 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006290 if( rc!=SQLITE_OK ){
6291 goto end_takeconch;
6292 }
drh7ed97b92010-01-20 13:07:21 +00006293 /* read the existing conch file */
6294 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6295 if( readLen<0 ){
6296 /* I/O error: lastErrno set by seekAndRead */
6297 pFile->lastErrno = conchFile->lastErrno;
6298 rc = SQLITE_IOERR_READ;
6299 goto end_takeconch;
6300 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6301 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6302 /* a short read or version format mismatch means we need to create a new
6303 ** conch file.
6304 */
6305 createConch = 1;
6306 }
6307 /* if the host id matches and the lock path already exists in the conch
6308 ** we'll try to use the path there, if we can't open that path, we'll
6309 ** retry with a new auto-generated path
6310 */
6311 do { /* in case we need to try again for an :auto: named lock file */
6312
6313 if( !createConch && !forceNewLockPath ){
6314 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6315 PROXY_HOSTIDLEN);
6316 /* if the conch has data compare the contents */
6317 if( !pCtx->lockProxyPath ){
6318 /* for auto-named local lock file, just check the host ID and we'll
6319 ** use the local lock file path that's already in there
6320 */
6321 if( hostIdMatch ){
6322 size_t pathLen = (readLen - PROXY_PATHINDEX);
6323
6324 if( pathLen>=MAXPATHLEN ){
6325 pathLen=MAXPATHLEN-1;
6326 }
6327 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6328 lockPath[pathLen] = 0;
6329 tempLockPath = lockPath;
6330 tryOldLockPath = 1;
6331 /* create a copy of the lock path if the conch is taken */
6332 goto end_takeconch;
6333 }
6334 }else if( hostIdMatch
6335 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6336 readLen-PROXY_PATHINDEX)
6337 ){
6338 /* conch host and lock path match */
6339 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006340 }
drh7ed97b92010-01-20 13:07:21 +00006341 }
6342
6343 /* if the conch isn't writable and doesn't match, we can't take it */
6344 if( (conchFile->openFlags&O_RDWR) == 0 ){
6345 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006346 goto end_takeconch;
6347 }
drh7ed97b92010-01-20 13:07:21 +00006348
6349 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006350 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006351 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6352 tempLockPath = lockPath;
6353 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006354 }
drh7ed97b92010-01-20 13:07:21 +00006355
6356 /* update conch with host and path (this will fail if other process
6357 ** has a shared lock already), if the host id matches, use the big
6358 ** stick.
drh715ff302008-12-03 22:32:44 +00006359 */
drh7ed97b92010-01-20 13:07:21 +00006360 futimes(conchFile->h, NULL);
6361 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006362 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006363 /* We are trying for an exclusive lock but another thread in this
6364 ** same process is still holding a shared lock. */
6365 rc = SQLITE_BUSY;
6366 } else {
6367 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006368 }
drh715ff302008-12-03 22:32:44 +00006369 }else{
drh7ed97b92010-01-20 13:07:21 +00006370 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006371 }
drh7ed97b92010-01-20 13:07:21 +00006372 if( rc==SQLITE_OK ){
6373 char writeBuffer[PROXY_MAXCONCHLEN];
6374 int writeSize = 0;
6375
6376 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6377 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6378 if( pCtx->lockProxyPath!=NULL ){
6379 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6380 }else{
6381 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6382 }
6383 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006384 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006385 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6386 fsync(conchFile->h);
6387 /* If we created a new conch file (not just updated the contents of a
6388 ** valid conch file), try to match the permissions of the database
6389 */
6390 if( rc==SQLITE_OK && createConch ){
6391 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006392 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006393 if( err==0 ){
6394 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6395 S_IROTH|S_IWOTH);
6396 /* try to match the database file R/W permissions, ignore failure */
6397#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006398 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006399#else
drhff812312011-02-23 13:33:46 +00006400 do{
drhe562be52011-03-02 18:01:10 +00006401 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006402 }while( rc==(-1) && errno==EINTR );
6403 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006404 int code = errno;
6405 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6406 cmode, code, strerror(code));
6407 } else {
6408 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6409 }
6410 }else{
6411 int code = errno;
6412 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6413 err, code, strerror(code));
6414#endif
6415 }
drh715ff302008-12-03 22:32:44 +00006416 }
6417 }
drh7ed97b92010-01-20 13:07:21 +00006418 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6419
6420 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006421 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006422 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006423 int fd;
drh7ed97b92010-01-20 13:07:21 +00006424 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006425 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006426 }
6427 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006428 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006429 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006430 if( fd>=0 ){
6431 pFile->h = fd;
6432 }else{
drh9978c972010-02-23 17:36:32 +00006433 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006434 during locking */
6435 }
6436 }
6437 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6438 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6439 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6440 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6441 /* we couldn't create the proxy lock file with the old lock file path
6442 ** so try again via auto-naming
6443 */
6444 forceNewLockPath = 1;
6445 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006446 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006447 }
6448 }
6449 if( rc==SQLITE_OK ){
6450 /* Need to make a copy of path if we extracted the value
6451 ** from the conch file or the path was allocated on the stack
6452 */
6453 if( tempLockPath ){
6454 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6455 if( !pCtx->lockProxyPath ){
6456 rc = SQLITE_NOMEM;
6457 }
6458 }
6459 }
6460 if( rc==SQLITE_OK ){
6461 pCtx->conchHeld = 1;
6462
6463 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6464 afpLockingContext *afpCtx;
6465 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6466 afpCtx->dbPath = pCtx->lockProxyPath;
6467 }
6468 } else {
6469 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6470 }
drh308c2a52010-05-14 11:30:18 +00006471 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6472 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006473 return rc;
drh308c2a52010-05-14 11:30:18 +00006474 } while (1); /* in case we need to retry the :auto: lock file -
6475 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006476 }
6477}
6478
6479/*
6480** If pFile holds a lock on a conch file, then release that lock.
6481*/
6482static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006483 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006484 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6485 unixFile *conchFile; /* Name of the conch file */
6486
6487 pCtx = (proxyLockingContext *)pFile->lockingContext;
6488 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006489 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006490 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006491 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006492 if( pCtx->conchHeld>0 ){
6493 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6494 }
drh715ff302008-12-03 22:32:44 +00006495 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006496 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6497 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006498 return rc;
6499}
6500
6501/*
6502** Given the name of a database file, compute the name of its conch file.
6503** Store the conch filename in memory obtained from sqlite3_malloc().
6504** Make *pConchPath point to the new name. Return SQLITE_OK on success
6505** or SQLITE_NOMEM if unable to obtain memory.
6506**
6507** The caller is responsible for ensuring that the allocated memory
6508** space is eventually freed.
6509**
6510** *pConchPath is set to NULL if a memory allocation error occurs.
6511*/
6512static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6513 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006514 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006515 char *conchPath; /* buffer in which to construct conch name */
6516
6517 /* Allocate space for the conch filename and initialize the name to
6518 ** the name of the original database file. */
6519 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
6520 if( conchPath==0 ){
6521 return SQLITE_NOMEM;
6522 }
6523 memcpy(conchPath, dbPath, len+1);
6524
6525 /* now insert a "." before the last / character */
6526 for( i=(len-1); i>=0; i-- ){
6527 if( conchPath[i]=='/' ){
6528 i++;
6529 break;
6530 }
6531 }
6532 conchPath[i]='.';
6533 while ( i<len ){
6534 conchPath[i+1]=dbPath[i];
6535 i++;
6536 }
6537
6538 /* append the "-conch" suffix to the file */
6539 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00006540 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00006541
6542 return SQLITE_OK;
6543}
6544
6545
6546/* Takes a fully configured proxy locking-style unix file and switches
6547** the local lock file path
6548*/
6549static int switchLockProxyPath(unixFile *pFile, const char *path) {
6550 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6551 char *oldPath = pCtx->lockProxyPath;
6552 int rc = SQLITE_OK;
6553
drh308c2a52010-05-14 11:30:18 +00006554 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006555 return SQLITE_BUSY;
6556 }
6557
6558 /* nothing to do if the path is NULL, :auto: or matches the existing path */
6559 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
6560 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
6561 return SQLITE_OK;
6562 }else{
6563 unixFile *lockProxy = pCtx->lockProxy;
6564 pCtx->lockProxy=NULL;
6565 pCtx->conchHeld = 0;
6566 if( lockProxy!=NULL ){
6567 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
6568 if( rc ) return rc;
6569 sqlite3_free(lockProxy);
6570 }
6571 sqlite3_free(oldPath);
6572 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
6573 }
6574
6575 return rc;
6576}
6577
6578/*
6579** pFile is a file that has been opened by a prior xOpen call. dbPath
6580** is a string buffer at least MAXPATHLEN+1 characters in size.
6581**
6582** This routine find the filename associated with pFile and writes it
6583** int dbPath.
6584*/
6585static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00006586#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00006587 if( pFile->pMethod == &afpIoMethods ){
6588 /* afp style keeps a reference to the db path in the filePath field
6589 ** of the struct */
drhea678832008-12-10 19:26:22 +00006590 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006591 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
6592 } else
drh715ff302008-12-03 22:32:44 +00006593#endif
6594 if( pFile->pMethod == &dotlockIoMethods ){
6595 /* dot lock style uses the locking context to store the dot lock
6596 ** file path */
6597 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
6598 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
6599 }else{
6600 /* all other styles use the locking context to store the db file path */
6601 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00006602 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00006603 }
6604 return SQLITE_OK;
6605}
6606
6607/*
6608** Takes an already filled in unix file and alters it so all file locking
6609** will be performed on the local proxy lock file. The following fields
6610** are preserved in the locking context so that they can be restored and
6611** the unix structure properly cleaned up at close time:
6612** ->lockingContext
6613** ->pMethod
6614*/
6615static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
6616 proxyLockingContext *pCtx;
6617 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
6618 char *lockPath=NULL;
6619 int rc = SQLITE_OK;
6620
drh308c2a52010-05-14 11:30:18 +00006621 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00006622 return SQLITE_BUSY;
6623 }
6624 proxyGetDbPathForUnixFile(pFile, dbPath);
6625 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
6626 lockPath=NULL;
6627 }else{
6628 lockPath=(char *)path;
6629 }
6630
drh308c2a52010-05-14 11:30:18 +00006631 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
6632 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006633
6634 pCtx = sqlite3_malloc( sizeof(*pCtx) );
6635 if( pCtx==0 ){
6636 return SQLITE_NOMEM;
6637 }
6638 memset(pCtx, 0, sizeof(*pCtx));
6639
6640 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
6641 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006642 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
6643 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
6644 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
6645 ** (c) the file system is read-only, then enable no-locking access.
6646 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
6647 ** that openFlags will have only one of O_RDONLY or O_RDWR.
6648 */
6649 struct statfs fsInfo;
6650 struct stat conchInfo;
6651 int goLockless = 0;
6652
drh99ab3b12011-03-02 15:09:07 +00006653 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00006654 int err = errno;
6655 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
6656 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
6657 }
6658 }
6659 if( goLockless ){
6660 pCtx->conchHeld = -1; /* read only FS/ lockless */
6661 rc = SQLITE_OK;
6662 }
6663 }
drh715ff302008-12-03 22:32:44 +00006664 }
6665 if( rc==SQLITE_OK && lockPath ){
6666 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
6667 }
6668
6669 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00006670 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
6671 if( pCtx->dbPath==NULL ){
6672 rc = SQLITE_NOMEM;
6673 }
6674 }
6675 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006676 /* all memory is allocated, proxys are created and assigned,
6677 ** switch the locking context and pMethod then return.
6678 */
drh715ff302008-12-03 22:32:44 +00006679 pCtx->oldLockingContext = pFile->lockingContext;
6680 pFile->lockingContext = pCtx;
6681 pCtx->pOldMethod = pFile->pMethod;
6682 pFile->pMethod = &proxyIoMethods;
6683 }else{
6684 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00006685 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00006686 sqlite3_free(pCtx->conchFile);
6687 }
drhd56b1212010-08-11 06:14:15 +00006688 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006689 sqlite3_free(pCtx->conchFilePath);
6690 sqlite3_free(pCtx);
6691 }
drh308c2a52010-05-14 11:30:18 +00006692 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
6693 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006694 return rc;
6695}
6696
6697
6698/*
6699** This routine handles sqlite3_file_control() calls that are specific
6700** to proxy locking.
6701*/
6702static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
6703 switch( op ){
6704 case SQLITE_GET_LOCKPROXYFILE: {
6705 unixFile *pFile = (unixFile*)id;
6706 if( pFile->pMethod == &proxyIoMethods ){
6707 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
6708 proxyTakeConch(pFile);
6709 if( pCtx->lockProxyPath ){
6710 *(const char **)pArg = pCtx->lockProxyPath;
6711 }else{
6712 *(const char **)pArg = ":auto: (not held)";
6713 }
6714 } else {
6715 *(const char **)pArg = NULL;
6716 }
6717 return SQLITE_OK;
6718 }
6719 case SQLITE_SET_LOCKPROXYFILE: {
6720 unixFile *pFile = (unixFile*)id;
6721 int rc = SQLITE_OK;
6722 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
6723 if( pArg==NULL || (const char *)pArg==0 ){
6724 if( isProxyStyle ){
6725 /* turn off proxy locking - not supported */
6726 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
6727 }else{
6728 /* turn off proxy locking - already off - NOOP */
6729 rc = SQLITE_OK;
6730 }
6731 }else{
6732 const char *proxyPath = (const char *)pArg;
6733 if( isProxyStyle ){
6734 proxyLockingContext *pCtx =
6735 (proxyLockingContext*)pFile->lockingContext;
6736 if( !strcmp(pArg, ":auto:")
6737 || (pCtx->lockProxyPath &&
6738 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
6739 ){
6740 rc = SQLITE_OK;
6741 }else{
6742 rc = switchLockProxyPath(pFile, proxyPath);
6743 }
6744 }else{
6745 /* turn on proxy file locking */
6746 rc = proxyTransformUnixFile(pFile, proxyPath);
6747 }
6748 }
6749 return rc;
6750 }
6751 default: {
6752 assert( 0 ); /* The call assures that only valid opcodes are sent */
6753 }
6754 }
6755 /*NOTREACHED*/
6756 return SQLITE_ERROR;
6757}
6758
6759/*
6760** Within this division (the proxying locking implementation) the procedures
6761** above this point are all utilities. The lock-related methods of the
6762** proxy-locking sqlite3_io_method object follow.
6763*/
6764
6765
6766/*
6767** This routine checks if there is a RESERVED lock held on the specified
6768** file by this or any other process. If such a lock is held, set *pResOut
6769** to a non-zero value otherwise *pResOut is set to zero. The return value
6770** is set to SQLITE_OK unless an I/O error occurs during lock checking.
6771*/
6772static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
6773 unixFile *pFile = (unixFile*)id;
6774 int rc = proxyTakeConch(pFile);
6775 if( rc==SQLITE_OK ){
6776 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006777 if( pCtx->conchHeld>0 ){
6778 unixFile *proxy = pCtx->lockProxy;
6779 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6780 }else{ /* conchHeld < 0 is lockless */
6781 pResOut=0;
6782 }
drh715ff302008-12-03 22:32:44 +00006783 }
6784 return rc;
6785}
6786
6787/*
drh308c2a52010-05-14 11:30:18 +00006788** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00006789** of the following:
6790**
6791** (1) SHARED_LOCK
6792** (2) RESERVED_LOCK
6793** (3) PENDING_LOCK
6794** (4) EXCLUSIVE_LOCK
6795**
6796** Sometimes when requesting one lock state, additional lock states
6797** are inserted in between. The locking might fail on one of the later
6798** transitions leaving the lock state different from what it started but
6799** still short of its goal. The following chart shows the allowed
6800** transitions and the inserted intermediate states:
6801**
6802** UNLOCKED -> SHARED
6803** SHARED -> RESERVED
6804** SHARED -> (PENDING) -> EXCLUSIVE
6805** RESERVED -> (PENDING) -> EXCLUSIVE
6806** PENDING -> EXCLUSIVE
6807**
6808** This routine will only increase a lock. Use the sqlite3OsUnlock()
6809** routine to lower a locking level.
6810*/
drh308c2a52010-05-14 11:30:18 +00006811static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006812 unixFile *pFile = (unixFile*)id;
6813 int rc = proxyTakeConch(pFile);
6814 if( rc==SQLITE_OK ){
6815 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006816 if( pCtx->conchHeld>0 ){
6817 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006818 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6819 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006820 }else{
6821 /* conchHeld < 0 is lockless */
6822 }
drh715ff302008-12-03 22:32:44 +00006823 }
6824 return rc;
6825}
6826
6827
6828/*
drh308c2a52010-05-14 11:30:18 +00006829** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00006830** must be either NO_LOCK or SHARED_LOCK.
6831**
6832** If the locking level of the file descriptor is already at or below
6833** the requested locking level, this routine is a no-op.
6834*/
drh308c2a52010-05-14 11:30:18 +00006835static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00006836 unixFile *pFile = (unixFile*)id;
6837 int rc = proxyTakeConch(pFile);
6838 if( rc==SQLITE_OK ){
6839 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00006840 if( pCtx->conchHeld>0 ){
6841 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00006842 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6843 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00006844 }else{
6845 /* conchHeld < 0 is lockless */
6846 }
drh715ff302008-12-03 22:32:44 +00006847 }
6848 return rc;
6849}
6850
6851/*
6852** Close a file that uses proxy locks.
6853*/
6854static int proxyClose(sqlite3_file *id) {
6855 if( id ){
6856 unixFile *pFile = (unixFile*)id;
6857 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6858 unixFile *lockProxy = pCtx->lockProxy;
6859 unixFile *conchFile = pCtx->conchFile;
6860 int rc = SQLITE_OK;
6861
6862 if( lockProxy ){
6863 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
6864 if( rc ) return rc;
6865 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
6866 if( rc ) return rc;
6867 sqlite3_free(lockProxy);
6868 pCtx->lockProxy = 0;
6869 }
6870 if( conchFile ){
6871 if( pCtx->conchHeld ){
6872 rc = proxyReleaseConch(pFile);
6873 if( rc ) return rc;
6874 }
6875 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
6876 if( rc ) return rc;
6877 sqlite3_free(conchFile);
6878 }
drhd56b1212010-08-11 06:14:15 +00006879 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00006880 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00006881 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00006882 /* restore the original locking context and pMethod then close it */
6883 pFile->lockingContext = pCtx->oldLockingContext;
6884 pFile->pMethod = pCtx->pOldMethod;
6885 sqlite3_free(pCtx);
6886 return pFile->pMethod->xClose(id);
6887 }
6888 return SQLITE_OK;
6889}
6890
6891
6892
drhd2cb50b2009-01-09 21:41:17 +00006893#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00006894/*
6895** The proxy locking style is intended for use with AFP filesystems.
6896** And since AFP is only supported on MacOSX, the proxy locking is also
6897** restricted to MacOSX.
6898**
6899**
6900******************* End of the proxy lock implementation **********************
6901******************************************************************************/
6902
drh734c9862008-11-28 15:37:20 +00006903/*
danielk1977e339d652008-06-28 11:23:00 +00006904** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00006905**
6906** This routine registers all VFS implementations for unix-like operating
6907** systems. This routine, and the sqlite3_os_end() routine that follows,
6908** should be the only routines in this file that are visible from other
6909** files.
drh6b9d6dd2008-12-03 19:34:47 +00006910**
6911** This routine is called once during SQLite initialization and by a
6912** single thread. The memory allocation and mutex subsystems have not
6913** necessarily been initialized when this routine is called, and so they
6914** should not be used.
drh153c62c2007-08-24 03:51:33 +00006915*/
danielk1977c0fa4c52008-06-25 17:19:00 +00006916int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00006917 /*
6918 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00006919 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
6920 ** to the "finder" function. (pAppData is a pointer to a pointer because
6921 ** silly C90 rules prohibit a void* from being cast to a function pointer
6922 ** and so we have to go through the intermediate pointer to avoid problems
6923 ** when compiling with -pedantic-errors on GCC.)
6924 **
6925 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00006926 ** finder-function. The finder-function returns a pointer to the
6927 ** sqlite_io_methods object that implements the desired locking
6928 ** behaviors. See the division above that contains the IOMETHODS
6929 ** macro for addition information on finder-functions.
6930 **
6931 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
6932 ** object. But the "autolockIoFinder" available on MacOSX does a little
6933 ** more than that; it looks at the filesystem type that hosts the
6934 ** database file and tries to choose an locking method appropriate for
6935 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00006936 */
drh7708e972008-11-29 00:56:52 +00006937 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00006938 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00006939 sizeof(unixFile), /* szOsFile */ \
6940 MAX_PATHNAME, /* mxPathname */ \
6941 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00006942 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00006943 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00006944 unixOpen, /* xOpen */ \
6945 unixDelete, /* xDelete */ \
6946 unixAccess, /* xAccess */ \
6947 unixFullPathname, /* xFullPathname */ \
6948 unixDlOpen, /* xDlOpen */ \
6949 unixDlError, /* xDlError */ \
6950 unixDlSym, /* xDlSym */ \
6951 unixDlClose, /* xDlClose */ \
6952 unixRandomness, /* xRandomness */ \
6953 unixSleep, /* xSleep */ \
6954 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00006955 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00006956 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00006957 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00006958 unixGetSystemCall, /* xGetSystemCall */ \
6959 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00006960 }
6961
drh6b9d6dd2008-12-03 19:34:47 +00006962 /*
6963 ** All default VFSes for unix are contained in the following array.
6964 **
6965 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
6966 ** by the SQLite core when the VFS is registered. So the following
6967 ** array cannot be const.
6968 */
danielk1977e339d652008-06-28 11:23:00 +00006969 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00006970#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00006971 UNIXVFS("unix", autolockIoFinder ),
6972#else
6973 UNIXVFS("unix", posixIoFinder ),
6974#endif
6975 UNIXVFS("unix-none", nolockIoFinder ),
6976 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00006977 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00006978#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006979 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00006980#endif
6981#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00006982 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00006983#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00006984 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00006985#endif
chw78a13182009-04-07 05:35:03 +00006986#endif
drhd2cb50b2009-01-09 21:41:17 +00006987#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00006988 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00006989 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00006990 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00006991#endif
drh153c62c2007-08-24 03:51:33 +00006992 };
drh6b9d6dd2008-12-03 19:34:47 +00006993 unsigned int i; /* Loop counter */
6994
drh2aa5a002011-04-13 13:42:25 +00006995 /* Double-check that the aSyscall[] array has been constructed
6996 ** correctly. See ticket [bb3a86e890c8e96ab] */
drh8c815d12012-02-13 20:16:37 +00006997 assert( ArraySize(aSyscall)==22 );
drh2aa5a002011-04-13 13:42:25 +00006998
drh6b9d6dd2008-12-03 19:34:47 +00006999 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007000 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007001 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007002 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007003 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007004}
danielk1977e339d652008-06-28 11:23:00 +00007005
7006/*
drh6b9d6dd2008-12-03 19:34:47 +00007007** Shutdown the operating system interface.
7008**
7009** Some operating systems might need to do some cleanup in this routine,
7010** to release dynamically allocated objects. But not on unix.
7011** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007012*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007013int sqlite3_os_end(void){
7014 return SQLITE_OK;
7015}
drhdce8bdb2007-08-16 13:01:44 +00007016
danielk197729bafea2008-06-26 10:41:19 +00007017#endif /* SQLITE_OS_UNIX */