blob: d8b5db7680291e60b12ac823185fc1df6a61f80e [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh6c7d5c52008-11-21 20:32:33 +000075** Define the OS_VXWORKS pre-processor macro to 1 if building on
danielk1977397d65f2008-11-19 11:35:39 +000076** vxworks, or 0 otherwise.
77*/
drh6c7d5c52008-11-21 20:32:33 +000078#ifndef OS_VXWORKS
79# if defined(__RTP__) || defined(_WRS_KERNEL)
80# define OS_VXWORKS 1
81# else
82# define OS_VXWORKS 0
83# endif
danielk1977397d65f2008-11-19 11:35:39 +000084#endif
85
86/*
drh9cbe6352005-11-29 03:13:21 +000087** standard include files.
88*/
89#include <sys/types.h>
90#include <sys/stat.h>
91#include <fcntl.h>
92#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000093#include <time.h>
drh19e2d372005-08-29 23:00:03 +000094#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000095#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000096#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000097# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000098#endif
drh1da88f02011-12-17 16:09:16 +000099
drh91be7dc2014-08-11 13:53:30 +0000100#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000101# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +0000102# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +0000103# include <semaphore.h>
104# include <limits.h>
105# else
drh9b35ea62008-11-29 02:20:26 +0000106# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000107# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +0000108# endif
drhbfe66312006-10-03 17:40:40 +0000109#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000110
drhf8b4d8c2010-03-05 13:53:22 +0000111#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000112# include <sys/mount.h>
113#endif
114
drhdbe4b882011-06-20 18:00:17 +0000115#ifdef HAVE_UTIME
116# include <utime.h>
117#endif
118
drh9cbe6352005-11-29 03:13:21 +0000119/*
drh7ed97b92010-01-20 13:07:21 +0000120** Allowed values of unixFile.fsFlags
121*/
122#define SQLITE_FSFLAGS_IS_MSDOS 0x1
123
124/*
drhf1a221e2006-01-15 17:27:17 +0000125** If we are to be thread-safe, include the pthreads header and define
126** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000127*/
drhd677b3d2007-08-20 22:48:41 +0000128#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000129# include <pthread.h>
130# define SQLITE_UNIX_THREADS 1
131#endif
132
133/*
134** Default permissions when creating a new file
135*/
136#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
137# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
138#endif
139
danielk1977b4b47412007-08-17 15:53:36 +0000140/*
drh5adc60b2012-04-14 13:25:11 +0000141** Default permissions when creating auto proxy dir
142*/
aswiftaebf4132008-11-21 00:10:35 +0000143#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
144# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
145#endif
146
147/*
danielk1977b4b47412007-08-17 15:53:36 +0000148** Maximum supported path-length.
149*/
150#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000151
drh734c9862008-11-28 15:37:20 +0000152/*
drh734c9862008-11-28 15:37:20 +0000153** Only set the lastErrno if the error code is a real error and not
154** a normal expected return code of SQLITE_BUSY or SQLITE_OK
155*/
156#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
157
drhd91c68f2010-05-14 14:52:25 +0000158/* Forward references */
159typedef struct unixShm unixShm; /* Connection shared memory */
160typedef struct unixShmNode unixShmNode; /* Shared memory instance */
161typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
162typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000163
164/*
dane946c392009-08-22 11:39:46 +0000165** Sometimes, after a file handle is closed by SQLite, the file descriptor
166** cannot be closed immediately. In these cases, instances of the following
167** structure are used to store the file descriptor while waiting for an
168** opportunity to either close or reuse it.
169*/
dane946c392009-08-22 11:39:46 +0000170struct UnixUnusedFd {
171 int fd; /* File descriptor to close */
172 int flags; /* Flags this file descriptor was opened with */
173 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
174};
175
176/*
drh9b35ea62008-11-29 02:20:26 +0000177** The unixFile structure is subclass of sqlite3_file specific to the unix
178** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000179*/
drh054889e2005-11-30 03:20:31 +0000180typedef struct unixFile unixFile;
181struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000182 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000183 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000184 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000185 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000186 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000187 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000188 int lastErrno; /* The unix errno from last I/O error */
189 void *lockingContext; /* Locking style specific state */
190 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000191 const char *zPath; /* Name of the file */
192 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000193 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000194#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000195 int nFetchOut; /* Number of outstanding xFetch refs */
196 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000197 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
198 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000199 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000200#endif
drh537dddf2012-10-26 13:46:24 +0000201#ifdef __QNXNTO__
202 int sectorSize; /* Device sector size */
203 int deviceCharacteristics; /* Precomputed device characteristics */
204#endif
drh08c6d442009-02-09 17:34:07 +0000205#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000206 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000207#endif
drh7ed97b92010-01-20 13:07:21 +0000208#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000209 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000210#endif
211#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000212 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000213#endif
drhd3d8c042012-05-29 17:02:40 +0000214#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000215 /* The next group of variables are used to track whether or not the
216 ** transaction counter in bytes 24-27 of database files are updated
217 ** whenever any part of the database changes. An assertion fault will
218 ** occur if a file is updated without also updating the transaction
219 ** counter. This test is made to avoid new problems similar to the
220 ** one described by ticket #3584.
221 */
222 unsigned char transCntrChng; /* True if the transaction counter changed */
223 unsigned char dbUpdate; /* True if any part of database file changed */
224 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000225
drh8f941bc2009-01-14 23:03:40 +0000226#endif
danf23da962013-03-23 21:00:41 +0000227
danielk1977967a4a12007-08-20 14:23:44 +0000228#ifdef SQLITE_TEST
229 /* In test mode, increase the size of this structure a bit so that
230 ** it is larger than the struct CrashFile defined in test6.c.
231 */
232 char aPadding[32];
233#endif
drh9cbe6352005-11-29 03:13:21 +0000234};
235
drhb00d8622014-01-01 15:18:36 +0000236/* This variable holds the process id (pid) from when the xRandomness()
237** method was called. If xOpen() is called from a different process id,
238** indicating that a fork() has occurred, the PRNG will be reset.
239*/
240static int randomnessPid = 0;
241
drh0ccebe72005-06-07 22:22:50 +0000242/*
drha7e61d82011-03-12 17:02:57 +0000243** Allowed values for the unixFile.ctrlFlags bitmask:
244*/
drhf0b190d2011-07-26 16:03:07 +0000245#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
246#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
247#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000248#ifndef SQLITE_DISABLE_DIRSYNC
249# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
250#else
251# define UNIXFILE_DIRSYNC 0x00
252#endif
drhcb15f352011-12-23 01:04:17 +0000253#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000254#define UNIXFILE_DELETE 0x20 /* Delete on close */
255#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
256#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhfbc7e882013-04-11 01:16:15 +0000257#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
drha7e61d82011-03-12 17:02:57 +0000258
259/*
drh198bf392006-01-06 21:52:49 +0000260** Include code that is common to all os_*.c files
261*/
262#include "os_common.h"
263
264/*
drh0ccebe72005-06-07 22:22:50 +0000265** Define various macros that are missing from some systems.
266*/
drhbbd42a62004-05-22 17:41:58 +0000267#ifndef O_LARGEFILE
268# define O_LARGEFILE 0
269#endif
270#ifdef SQLITE_DISABLE_LFS
271# undef O_LARGEFILE
272# define O_LARGEFILE 0
273#endif
274#ifndef O_NOFOLLOW
275# define O_NOFOLLOW 0
276#endif
277#ifndef O_BINARY
278# define O_BINARY 0
279#endif
280
281/*
drh2b4b5962005-06-15 17:47:55 +0000282** The threadid macro resolves to the thread-id or to 0. Used for
283** testing and debugging only.
284*/
drhd677b3d2007-08-20 22:48:41 +0000285#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000286#define threadid pthread_self()
287#else
288#define threadid 0
289#endif
290
drh99ab3b12011-03-02 15:09:07 +0000291/*
dane6ecd662013-04-01 17:56:59 +0000292** HAVE_MREMAP defaults to true on Linux and false everywhere else.
293*/
294#if !defined(HAVE_MREMAP)
295# if defined(__linux__) && defined(_GNU_SOURCE)
296# define HAVE_MREMAP 1
297# else
298# define HAVE_MREMAP 0
299# endif
300#endif
301
302/*
drh9a3baf12011-04-25 18:01:27 +0000303** Different Unix systems declare open() in different ways. Same use
304** open(const char*,int,mode_t). Others use open(const char*,int,...).
305** The difference is important when using a pointer to the function.
306**
307** The safest way to deal with the problem is to always use this wrapper
308** which always has the same well-defined interface.
309*/
310static int posixOpen(const char *zFile, int flags, int mode){
311 return open(zFile, flags, mode);
312}
313
drhed466822012-05-31 13:10:49 +0000314/*
315** On some systems, calls to fchown() will trigger a message in a security
316** log if they come from non-root processes. So avoid calling fchown() if
317** we are not running as root.
318*/
319static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000320#if OS_VXWORKS
321 return 0;
322#else
drhed466822012-05-31 13:10:49 +0000323 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000324#endif
drhed466822012-05-31 13:10:49 +0000325}
326
drh90315a22011-08-10 01:52:12 +0000327/* Forward reference */
328static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000329static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000330
drh9a3baf12011-04-25 18:01:27 +0000331/*
drh99ab3b12011-03-02 15:09:07 +0000332** Many system calls are accessed through pointer-to-functions so that
333** they may be overridden at runtime to facilitate fault injection during
334** testing and sandboxing. The following array holds the names and pointers
335** to all overrideable system calls.
336*/
337static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000338 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000339 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
340 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000341} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000342 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
343#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000344
drh58ad5802011-03-23 22:02:23 +0000345 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000346#define osClose ((int(*)(int))aSyscall[1].pCurrent)
347
drh58ad5802011-03-23 22:02:23 +0000348 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
353
drh58ad5802011-03-23 22:02:23 +0000354 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
356
357/*
358** The DJGPP compiler environment looks mostly like Unix, but it
359** lacks the fcntl() system call. So redefine fcntl() to be something
360** that always succeeds. This means that locking does not occur under
361** DJGPP. But it is DOS - what did you expect?
362*/
363#ifdef __DJGPP__
364 { "fstat", 0, 0 },
365#define osFstat(a,b,c) 0
366#else
drh58ad5802011-03-23 22:02:23 +0000367 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
369#endif
370
drh58ad5802011-03-23 22:02:23 +0000371 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000372#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
373
drh58ad5802011-03-23 22:02:23 +0000374 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000375#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000376
drh58ad5802011-03-23 22:02:23 +0000377 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000378#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
379
drh91be7dc2014-08-11 13:53:30 +0000380#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000381 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000384#endif
385#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
386
387#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000388 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000389#else
drh58ad5802011-03-23 22:02:23 +0000390 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000391#endif
392#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
393
drh58ad5802011-03-23 22:02:23 +0000394 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000395#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
396
drh91be7dc2014-08-11 13:53:30 +0000397#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000398 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000399#else
drh58ad5802011-03-23 22:02:23 +0000400 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000401#endif
402#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
403 aSyscall[12].pCurrent)
404
405#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000407#else
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000409#endif
410#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
411 aSyscall[13].pCurrent)
412
drh58ad5802011-03-23 22:02:23 +0000413 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000414#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000415
416#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000417 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000418#else
drh58ad5802011-03-23 22:02:23 +0000419 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000420#endif
dan0fd7d862011-03-29 10:04:23 +0000421#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000422
drh036ac7f2011-08-08 23:18:05 +0000423 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
424#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
425
drh90315a22011-08-10 01:52:12 +0000426 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
427#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
428
drh9ef6bc42011-11-04 02:24:02 +0000429 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
430#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
431
432 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
433#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
434
drhed466822012-05-31 13:10:49 +0000435 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000436#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000437
dan4dd51442013-08-26 14:30:25 +0000438#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000439 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
440#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
441
drhd1ab8062013-03-25 20:50:25 +0000442 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
443#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
444
dane6ecd662013-04-01 17:56:59 +0000445#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000446 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
447#else
448 { "mremap", (sqlite3_syscall_ptr)0, 0 },
449#endif
450#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000451 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
452#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
453
dan702eec12014-06-23 10:04:58 +0000454#endif
455
drhe562be52011-03-02 18:01:10 +0000456}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000457
458/*
459** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000460** "unix" VFSes. Return SQLITE_OK opon successfully updating the
461** system call pointer, or SQLITE_NOTFOUND if there is no configurable
462** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000463*/
464static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000465 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
466 const char *zName, /* Name of system call to override */
467 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000468){
drh58ad5802011-03-23 22:02:23 +0000469 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000470 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000471
472 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000473 if( zName==0 ){
474 /* If no zName is given, restore all system calls to their default
475 ** settings and return NULL
476 */
dan51438a72011-04-02 17:00:47 +0000477 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000478 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
479 if( aSyscall[i].pDefault ){
480 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000481 }
482 }
483 }else{
484 /* If zName is specified, operate on only the one system call
485 ** specified.
486 */
487 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
488 if( strcmp(zName, aSyscall[i].zName)==0 ){
489 if( aSyscall[i].pDefault==0 ){
490 aSyscall[i].pDefault = aSyscall[i].pCurrent;
491 }
drh1df30962011-03-02 19:06:42 +0000492 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000493 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
494 aSyscall[i].pCurrent = pNewFunc;
495 break;
496 }
497 }
498 }
499 return rc;
500}
501
drh1df30962011-03-02 19:06:42 +0000502/*
503** Return the value of a system call. Return NULL if zName is not a
504** recognized system call name. NULL is also returned if the system call
505** is currently undefined.
506*/
drh58ad5802011-03-23 22:02:23 +0000507static sqlite3_syscall_ptr unixGetSystemCall(
508 sqlite3_vfs *pNotUsed,
509 const char *zName
510){
511 unsigned int i;
512
513 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000514 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
515 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
516 }
517 return 0;
518}
519
520/*
521** Return the name of the first system call after zName. If zName==NULL
522** then return the name of the first system call. Return NULL if zName
523** is the last system call or if zName is not the name of a valid
524** system call.
525*/
526static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000527 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000528
529 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000530 if( zName ){
531 for(i=0; i<ArraySize(aSyscall)-1; i++){
532 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000533 }
534 }
dan0fd7d862011-03-29 10:04:23 +0000535 for(i++; i<ArraySize(aSyscall); i++){
536 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000537 }
538 return 0;
539}
540
drhad4f1e52011-03-04 15:43:57 +0000541/*
drh77a3fdc2013-08-30 14:24:12 +0000542** Do not accept any file descriptor less than this value, in order to avoid
543** opening database file using file descriptors that are commonly used for
544** standard input, output, and error.
545*/
546#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
547# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
548#endif
549
550/*
drh8c815d12012-02-13 20:16:37 +0000551** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000552** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000553**
554** If the file creation mode "m" is 0 then set it to the default for
555** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
556** 0644) as modified by the system umask. If m is not 0, then
557** make the file creation mode be exactly m ignoring the umask.
558**
559** The m parameter will be non-zero only when creating -wal, -journal,
560** and -shm files. We want those files to have *exactly* the same
561** permissions as their original database, unadulterated by the umask.
562** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
563** transaction crashes and leaves behind hot journals, then any
564** process that is able to write to the database will also be able to
565** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000566*/
drh8c815d12012-02-13 20:16:37 +0000567static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000568 int fd;
drhe1186ab2013-01-04 20:45:13 +0000569 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000570 while(1){
drh5adc60b2012-04-14 13:25:11 +0000571#if defined(O_CLOEXEC)
572 fd = osOpen(z,f|O_CLOEXEC,m2);
573#else
574 fd = osOpen(z,f,m2);
575#endif
drh5128d002013-08-30 06:20:23 +0000576 if( fd<0 ){
577 if( errno==EINTR ) continue;
578 break;
579 }
drh77a3fdc2013-08-30 14:24:12 +0000580 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000581 osClose(fd);
582 sqlite3_log(SQLITE_WARNING,
583 "attempt to open \"%s\" as file descriptor %d", z, fd);
584 fd = -1;
585 if( osOpen("/dev/null", f, m)<0 ) break;
586 }
drhe1186ab2013-01-04 20:45:13 +0000587 if( fd>=0 ){
588 if( m!=0 ){
589 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000590 if( osFstat(fd, &statbuf)==0
591 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000592 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000593 ){
drhe1186ab2013-01-04 20:45:13 +0000594 osFchmod(fd, m);
595 }
596 }
drh5adc60b2012-04-14 13:25:11 +0000597#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000598 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000599#endif
drhe1186ab2013-01-04 20:45:13 +0000600 }
drh5adc60b2012-04-14 13:25:11 +0000601 return fd;
drhad4f1e52011-03-04 15:43:57 +0000602}
danielk197713adf8a2004-06-03 16:08:41 +0000603
drh107886a2008-11-21 22:21:50 +0000604/*
dan9359c7b2009-08-21 08:29:10 +0000605** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000606** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000607** vxworksFileId objects used by this file, all of which may be
608** shared by multiple threads.
609**
610** Function unixMutexHeld() is used to assert() that the global mutex
611** is held when required. This function is only used as part of assert()
612** statements. e.g.
613**
614** unixEnterMutex()
615** assert( unixMutexHeld() );
616** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000617*/
618static void unixEnterMutex(void){
619 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
620}
621static void unixLeaveMutex(void){
622 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
623}
dan9359c7b2009-08-21 08:29:10 +0000624#ifdef SQLITE_DEBUG
625static int unixMutexHeld(void) {
626 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
627}
628#endif
drh107886a2008-11-21 22:21:50 +0000629
drh734c9862008-11-28 15:37:20 +0000630
drh30ddce62011-10-15 00:16:30 +0000631#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000632/*
633** Helper function for printing out trace information from debugging
634** binaries. This returns the string represetation of the supplied
635** integer lock-type.
636*/
drh308c2a52010-05-14 11:30:18 +0000637static const char *azFileLock(int eFileLock){
638 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000639 case NO_LOCK: return "NONE";
640 case SHARED_LOCK: return "SHARED";
641 case RESERVED_LOCK: return "RESERVED";
642 case PENDING_LOCK: return "PENDING";
643 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000644 }
645 return "ERROR";
646}
647#endif
648
649#ifdef SQLITE_LOCK_TRACE
650/*
651** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000652**
drh734c9862008-11-28 15:37:20 +0000653** This routine is used for troubleshooting locks on multithreaded
654** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
655** command-line option on the compiler. This code is normally
656** turned off.
657*/
658static int lockTrace(int fd, int op, struct flock *p){
659 char *zOpName, *zType;
660 int s;
661 int savedErrno;
662 if( op==F_GETLK ){
663 zOpName = "GETLK";
664 }else if( op==F_SETLK ){
665 zOpName = "SETLK";
666 }else{
drh99ab3b12011-03-02 15:09:07 +0000667 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000668 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
669 return s;
670 }
671 if( p->l_type==F_RDLCK ){
672 zType = "RDLCK";
673 }else if( p->l_type==F_WRLCK ){
674 zType = "WRLCK";
675 }else if( p->l_type==F_UNLCK ){
676 zType = "UNLCK";
677 }else{
678 assert( 0 );
679 }
680 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000681 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000682 savedErrno = errno;
683 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
684 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
685 (int)p->l_pid, s);
686 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
687 struct flock l2;
688 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000689 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000690 if( l2.l_type==F_RDLCK ){
691 zType = "RDLCK";
692 }else if( l2.l_type==F_WRLCK ){
693 zType = "WRLCK";
694 }else if( l2.l_type==F_UNLCK ){
695 zType = "UNLCK";
696 }else{
697 assert( 0 );
698 }
699 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
700 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
701 }
702 errno = savedErrno;
703 return s;
704}
drh99ab3b12011-03-02 15:09:07 +0000705#undef osFcntl
706#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000707#endif /* SQLITE_LOCK_TRACE */
708
drhff812312011-02-23 13:33:46 +0000709/*
710** Retry ftruncate() calls that fail due to EINTR
711*/
drhff812312011-02-23 13:33:46 +0000712static int robust_ftruncate(int h, sqlite3_int64 sz){
713 int rc;
drh99ab3b12011-03-02 15:09:07 +0000714 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000715 return rc;
716}
drh734c9862008-11-28 15:37:20 +0000717
718/*
719** This routine translates a standard POSIX errno code into something
720** useful to the clients of the sqlite3 functions. Specifically, it is
721** intended to translate a variety of "try again" errors into SQLITE_BUSY
722** and a variety of "please close the file descriptor NOW" errors into
723** SQLITE_IOERR
724**
725** Errors during initialization of locks, or file system support for locks,
726** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
727*/
728static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
729 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000730#if 0
731 /* At one point this code was not commented out. In theory, this branch
732 ** should never be hit, as this function should only be called after
733 ** a locking-related function (i.e. fcntl()) has returned non-zero with
734 ** the value of errno as the first argument. Since a system call has failed,
735 ** errno should be non-zero.
736 **
737 ** Despite this, if errno really is zero, we still don't want to return
738 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
739 ** propagated back to the caller. Commenting this branch out means errno==0
740 ** will be handled by the "default:" case below.
741 */
drh734c9862008-11-28 15:37:20 +0000742 case 0:
743 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000744#endif
745
drh734c9862008-11-28 15:37:20 +0000746 case EAGAIN:
747 case ETIMEDOUT:
748 case EBUSY:
749 case EINTR:
750 case ENOLCK:
751 /* random NFS retry error, unless during file system support
752 * introspection, in which it actually means what it says */
753 return SQLITE_BUSY;
754
755 case EACCES:
756 /* EACCES is like EAGAIN during locking operations, but not any other time*/
757 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000758 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
759 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
760 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000761 return SQLITE_BUSY;
762 }
763 /* else fall through */
764 case EPERM:
765 return SQLITE_PERM;
766
drh734c9862008-11-28 15:37:20 +0000767#if EOPNOTSUPP!=ENOTSUP
768 case EOPNOTSUPP:
769 /* something went terribly awry, unless during file system support
770 * introspection, in which it actually means what it says */
771#endif
772#ifdef ENOTSUP
773 case ENOTSUP:
774 /* invalid fd, unless during file system support introspection, in which
775 * it actually means what it says */
776#endif
777 case EIO:
778 case EBADF:
779 case EINVAL:
780 case ENOTCONN:
781 case ENODEV:
782 case ENXIO:
783 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000784#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000785 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000786#endif
drh734c9862008-11-28 15:37:20 +0000787 case ENOSYS:
788 /* these should force the client to close the file and reconnect */
789
790 default:
791 return sqliteIOErr;
792 }
793}
794
795
drh734c9862008-11-28 15:37:20 +0000796/******************************************************************************
797****************** Begin Unique File ID Utility Used By VxWorks ***************
798**
799** On most versions of unix, we can get a unique ID for a file by concatenating
800** the device number and the inode number. But this does not work on VxWorks.
801** On VxWorks, a unique file id must be based on the canonical filename.
802**
803** A pointer to an instance of the following structure can be used as a
804** unique file ID in VxWorks. Each instance of this structure contains
805** a copy of the canonical filename. There is also a reference count.
806** The structure is reclaimed when the number of pointers to it drops to
807** zero.
808**
809** There are never very many files open at one time and lookups are not
810** a performance-critical path, so it is sufficient to put these
811** structures on a linked list.
812*/
813struct vxworksFileId {
814 struct vxworksFileId *pNext; /* Next in a list of them all */
815 int nRef; /* Number of references to this one */
816 int nName; /* Length of the zCanonicalName[] string */
817 char *zCanonicalName; /* Canonical filename */
818};
819
820#if OS_VXWORKS
821/*
drh9b35ea62008-11-29 02:20:26 +0000822** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000823** variable:
824*/
825static struct vxworksFileId *vxworksFileList = 0;
826
827/*
828** Simplify a filename into its canonical form
829** by making the following changes:
830**
831** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000832** * convert /./ into just /
833** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000834**
835** Changes are made in-place. Return the new name length.
836**
837** The original filename is in z[0..n-1]. Return the number of
838** characters in the simplified name.
839*/
840static int vxworksSimplifyName(char *z, int n){
841 int i, j;
842 while( n>1 && z[n-1]=='/' ){ n--; }
843 for(i=j=0; i<n; i++){
844 if( z[i]=='/' ){
845 if( z[i+1]=='/' ) continue;
846 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
847 i += 1;
848 continue;
849 }
850 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
851 while( j>0 && z[j-1]!='/' ){ j--; }
852 if( j>0 ){ j--; }
853 i += 2;
854 continue;
855 }
856 }
857 z[j++] = z[i];
858 }
859 z[j] = 0;
860 return j;
861}
862
863/*
864** Find a unique file ID for the given absolute pathname. Return
865** a pointer to the vxworksFileId object. This pointer is the unique
866** file ID.
867**
868** The nRef field of the vxworksFileId object is incremented before
869** the object is returned. A new vxworksFileId object is created
870** and added to the global list if necessary.
871**
872** If a memory allocation error occurs, return NULL.
873*/
874static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
875 struct vxworksFileId *pNew; /* search key and new file ID */
876 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
877 int n; /* Length of zAbsoluteName string */
878
879 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000880 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000881 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
882 if( pNew==0 ) return 0;
883 pNew->zCanonicalName = (char*)&pNew[1];
884 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
885 n = vxworksSimplifyName(pNew->zCanonicalName, n);
886
887 /* Search for an existing entry that matching the canonical name.
888 ** If found, increment the reference count and return a pointer to
889 ** the existing file ID.
890 */
891 unixEnterMutex();
892 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
893 if( pCandidate->nName==n
894 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
895 ){
896 sqlite3_free(pNew);
897 pCandidate->nRef++;
898 unixLeaveMutex();
899 return pCandidate;
900 }
901 }
902
903 /* No match was found. We will make a new file ID */
904 pNew->nRef = 1;
905 pNew->nName = n;
906 pNew->pNext = vxworksFileList;
907 vxworksFileList = pNew;
908 unixLeaveMutex();
909 return pNew;
910}
911
912/*
913** Decrement the reference count on a vxworksFileId object. Free
914** the object when the reference count reaches zero.
915*/
916static void vxworksReleaseFileId(struct vxworksFileId *pId){
917 unixEnterMutex();
918 assert( pId->nRef>0 );
919 pId->nRef--;
920 if( pId->nRef==0 ){
921 struct vxworksFileId **pp;
922 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
923 assert( *pp==pId );
924 *pp = pId->pNext;
925 sqlite3_free(pId);
926 }
927 unixLeaveMutex();
928}
929#endif /* OS_VXWORKS */
930/*************** End of Unique File ID Utility Used By VxWorks ****************
931******************************************************************************/
932
933
934/******************************************************************************
935*************************** Posix Advisory Locking ****************************
936**
drh9b35ea62008-11-29 02:20:26 +0000937** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000938** section 6.5.2.2 lines 483 through 490 specify that when a process
939** sets or clears a lock, that operation overrides any prior locks set
940** by the same process. It does not explicitly say so, but this implies
941** that it overrides locks set by the same process using a different
942** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000943**
944** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000945** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
946**
947** Suppose ./file1 and ./file2 are really the same file (because
948** one is a hard or symbolic link to the other) then if you set
949** an exclusive lock on fd1, then try to get an exclusive lock
950** on fd2, it works. I would have expected the second lock to
951** fail since there was already a lock on the file due to fd1.
952** But not so. Since both locks came from the same process, the
953** second overrides the first, even though they were on different
954** file descriptors opened on different file names.
955**
drh734c9862008-11-28 15:37:20 +0000956** This means that we cannot use POSIX locks to synchronize file access
957** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000958** to synchronize access for threads in separate processes, but not
959** threads within the same process.
960**
961** To work around the problem, SQLite has to manage file locks internally
962** on its own. Whenever a new database is opened, we have to find the
963** specific inode of the database file (the inode is determined by the
964** st_dev and st_ino fields of the stat structure that fstat() fills in)
965** and check for locks already existing on that inode. When locks are
966** created or removed, we have to look at our own internal record of the
967** locks to see if another thread has previously set a lock on that same
968** inode.
969**
drh9b35ea62008-11-29 02:20:26 +0000970** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
971** For VxWorks, we have to use the alternative unique ID system based on
972** canonical filename and implemented in the previous division.)
973**
danielk1977ad94b582007-08-20 06:44:22 +0000974** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000975** descriptor. It is now a structure that holds the integer file
976** descriptor and a pointer to a structure that describes the internal
977** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000978** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000979** point to the same locking structure. The locking structure keeps
980** a reference count (so we will know when to delete it) and a "cnt"
981** field that tells us its internal lock status. cnt==0 means the
982** file is unlocked. cnt==-1 means the file has an exclusive lock.
983** cnt>0 means there are cnt shared locks on the file.
984**
985** Any attempt to lock or unlock a file first checks the locking
986** structure. The fcntl() system call is only invoked to set a
987** POSIX lock if the internal lock structure transitions between
988** a locked and an unlocked state.
989**
drh734c9862008-11-28 15:37:20 +0000990** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +0000991**
992** If you close a file descriptor that points to a file that has locks,
993** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +0000994** released. To work around this problem, each unixInodeInfo object
995** maintains a count of the number of pending locks on tha inode.
996** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +0000997** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +0000998** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +0000999** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001000** be closed and that list is walked (and cleared) when the last lock
1001** clears.
1002**
drh9b35ea62008-11-29 02:20:26 +00001003** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001004**
drh9b35ea62008-11-29 02:20:26 +00001005** Many older versions of linux use the LinuxThreads library which is
1006** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001007** A cannot be modified or overridden by a different thread B.
1008** Only thread A can modify the lock. Locking behavior is correct
1009** if the appliation uses the newer Native Posix Thread Library (NPTL)
1010** on linux - with NPTL a lock created by thread A can override locks
1011** in thread B. But there is no way to know at compile-time which
1012** threading library is being used. So there is no way to know at
1013** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001014** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001015** current process.
drh5fdae772004-06-29 03:29:00 +00001016**
drh8af6c222010-05-14 12:43:01 +00001017** SQLite used to support LinuxThreads. But support for LinuxThreads
1018** was dropped beginning with version 3.7.0. SQLite will still work with
1019** LinuxThreads provided that (1) there is no more than one connection
1020** per database file in the same process and (2) database connections
1021** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001022*/
1023
1024/*
1025** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001026** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001027*/
1028struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001029 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001030#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001031 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001032#else
drh107886a2008-11-21 22:21:50 +00001033 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001034#endif
1035};
1036
1037/*
drhbbd42a62004-05-22 17:41:58 +00001038** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001039** inode. Or, on LinuxThreads, there is one of these structures for
1040** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001041**
danielk1977ad94b582007-08-20 06:44:22 +00001042** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001043** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001044** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001045*/
drh8af6c222010-05-14 12:43:01 +00001046struct unixInodeInfo {
1047 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001048 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001049 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1050 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001051 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001052 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1053 int nLock; /* Number of outstanding file locks */
1054 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1055 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1056 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001057#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001058 unsigned long long sharedByte; /* for AFP simulated shared lock */
1059#endif
drh6c7d5c52008-11-21 20:32:33 +00001060#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001061 sem_t *pSem; /* Named POSIX semaphore */
1062 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001063#endif
drhbbd42a62004-05-22 17:41:58 +00001064};
1065
drhda0e7682008-07-30 15:27:54 +00001066/*
drh8af6c222010-05-14 12:43:01 +00001067** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001068*/
drhd91c68f2010-05-14 14:52:25 +00001069static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001070
drh5fdae772004-06-29 03:29:00 +00001071/*
dane18d4952011-02-21 11:46:24 +00001072**
1073** This function - unixLogError_x(), is only ever called via the macro
1074** unixLogError().
1075**
1076** It is invoked after an error occurs in an OS function and errno has been
1077** set. It logs a message using sqlite3_log() containing the current value of
1078** errno and, if possible, the human-readable equivalent from strerror() or
1079** strerror_r().
1080**
1081** The first argument passed to the macro should be the error code that
1082** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1083** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001084** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001085** if any.
1086*/
drh0e9365c2011-03-02 02:08:13 +00001087#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1088static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001089 int errcode, /* SQLite error code */
1090 const char *zFunc, /* Name of OS function that failed */
1091 const char *zPath, /* File path associated with error */
1092 int iLine /* Source line number where error occurred */
1093){
1094 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001095 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001096
1097 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1098 ** the strerror() function to obtain the human-readable error message
1099 ** equivalent to errno. Otherwise, use strerror_r().
1100 */
1101#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1102 char aErr[80];
1103 memset(aErr, 0, sizeof(aErr));
1104 zErr = aErr;
1105
1106 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001107 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001108 ** returns a pointer to a buffer containing the error message. That pointer
1109 ** may point to aErr[], or it may point to some static storage somewhere.
1110 ** Otherwise, assume that the system provides the POSIX version of
1111 ** strerror_r(), which always writes an error message into aErr[].
1112 **
1113 ** If the code incorrectly assumes that it is the POSIX version that is
1114 ** available, the error message will often be an empty string. Not a
1115 ** huge problem. Incorrectly concluding that the GNU version is available
1116 ** could lead to a segfault though.
1117 */
1118#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1119 zErr =
1120# endif
drh0e9365c2011-03-02 02:08:13 +00001121 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001122
1123#elif SQLITE_THREADSAFE
1124 /* This is a threadsafe build, but strerror_r() is not available. */
1125 zErr = "";
1126#else
1127 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001128 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001129#endif
1130
drh0e9365c2011-03-02 02:08:13 +00001131 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001132 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001133 "os_unix.c:%d: (%d) %s(%s) - %s",
1134 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001135 );
1136
1137 return errcode;
1138}
1139
drh0e9365c2011-03-02 02:08:13 +00001140/*
1141** Close a file descriptor.
1142**
1143** We assume that close() almost always works, since it is only in a
1144** very sick application or on a very sick platform that it might fail.
1145** If it does fail, simply leak the file descriptor, but do log the
1146** error.
1147**
1148** Note that it is not safe to retry close() after EINTR since the
1149** file descriptor might have already been reused by another thread.
1150** So we don't even try to recover from an EINTR. Just log the error
1151** and move on.
1152*/
1153static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001154 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001155 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1156 pFile ? pFile->zPath : 0, lineno);
1157 }
1158}
dane18d4952011-02-21 11:46:24 +00001159
1160/*
danb0ac3e32010-06-16 10:55:42 +00001161** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001162*/
drh0e9365c2011-03-02 02:08:13 +00001163static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001164 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001165 UnixUnusedFd *p;
1166 UnixUnusedFd *pNext;
1167 for(p=pInode->pUnused; p; p=pNext){
1168 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001169 robust_close(pFile, p->fd, __LINE__);
1170 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001171 }
drh0e9365c2011-03-02 02:08:13 +00001172 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001173}
1174
1175/*
drh8af6c222010-05-14 12:43:01 +00001176** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001177**
1178** The mutex entered using the unixEnterMutex() function must be held
1179** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001180*/
danb0ac3e32010-06-16 10:55:42 +00001181static void releaseInodeInfo(unixFile *pFile){
1182 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001183 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001184 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001185 pInode->nRef--;
1186 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001187 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001188 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001189 if( pInode->pPrev ){
1190 assert( pInode->pPrev->pNext==pInode );
1191 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001192 }else{
drh8af6c222010-05-14 12:43:01 +00001193 assert( inodeList==pInode );
1194 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001195 }
drh8af6c222010-05-14 12:43:01 +00001196 if( pInode->pNext ){
1197 assert( pInode->pNext->pPrev==pInode );
1198 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001199 }
drh8af6c222010-05-14 12:43:01 +00001200 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001201 }
drhbbd42a62004-05-22 17:41:58 +00001202 }
1203}
1204
1205/*
drh8af6c222010-05-14 12:43:01 +00001206** Given a file descriptor, locate the unixInodeInfo object that
1207** describes that file descriptor. Create a new one if necessary. The
1208** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001209**
dan9359c7b2009-08-21 08:29:10 +00001210** The mutex entered using the unixEnterMutex() function must be held
1211** when this function is called.
1212**
drh6c7d5c52008-11-21 20:32:33 +00001213** Return an appropriate error code.
1214*/
drh8af6c222010-05-14 12:43:01 +00001215static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001216 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001217 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001218){
1219 int rc; /* System call return code */
1220 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001221 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1222 struct stat statbuf; /* Low-level file information */
1223 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001224
dan9359c7b2009-08-21 08:29:10 +00001225 assert( unixMutexHeld() );
1226
drh6c7d5c52008-11-21 20:32:33 +00001227 /* Get low-level information about the file that we can used to
1228 ** create a unique name for the file.
1229 */
1230 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001231 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001232 if( rc!=0 ){
1233 pFile->lastErrno = errno;
1234#ifdef EOVERFLOW
1235 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1236#endif
1237 return SQLITE_IOERR;
1238 }
1239
drheb0d74f2009-02-03 15:27:02 +00001240#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001241 /* On OS X on an msdos filesystem, the inode number is reported
1242 ** incorrectly for zero-size files. See ticket #3260. To work
1243 ** around this problem (we consider it a bug in OS X, not SQLite)
1244 ** we always increase the file size to 1 by writing a single byte
1245 ** prior to accessing the inode number. The one byte written is
1246 ** an ASCII 'S' character which also happens to be the first byte
1247 ** in the header of every SQLite database. In this way, if there
1248 ** is a race condition such that another thread has already populated
1249 ** the first page of the database, no damage is done.
1250 */
drh7ed97b92010-01-20 13:07:21 +00001251 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001252 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001253 if( rc!=1 ){
drh7ed97b92010-01-20 13:07:21 +00001254 pFile->lastErrno = errno;
drheb0d74f2009-02-03 15:27:02 +00001255 return SQLITE_IOERR;
1256 }
drh99ab3b12011-03-02 15:09:07 +00001257 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001258 if( rc!=0 ){
1259 pFile->lastErrno = errno;
1260 return SQLITE_IOERR;
1261 }
1262 }
drheb0d74f2009-02-03 15:27:02 +00001263#endif
drh6c7d5c52008-11-21 20:32:33 +00001264
drh8af6c222010-05-14 12:43:01 +00001265 memset(&fileId, 0, sizeof(fileId));
1266 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001267#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001268 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001269#else
drh8af6c222010-05-14 12:43:01 +00001270 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001271#endif
drh8af6c222010-05-14 12:43:01 +00001272 pInode = inodeList;
1273 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1274 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001275 }
drh8af6c222010-05-14 12:43:01 +00001276 if( pInode==0 ){
1277 pInode = sqlite3_malloc( sizeof(*pInode) );
1278 if( pInode==0 ){
1279 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001280 }
drh8af6c222010-05-14 12:43:01 +00001281 memset(pInode, 0, sizeof(*pInode));
1282 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1283 pInode->nRef = 1;
1284 pInode->pNext = inodeList;
1285 pInode->pPrev = 0;
1286 if( inodeList ) inodeList->pPrev = pInode;
1287 inodeList = pInode;
1288 }else{
1289 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001290 }
drh8af6c222010-05-14 12:43:01 +00001291 *ppInode = pInode;
1292 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001293}
drh6c7d5c52008-11-21 20:32:33 +00001294
drhb959a012013-12-07 12:29:22 +00001295/*
1296** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1297*/
1298static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001299#if OS_VXWORKS
1300 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1301#else
drhb959a012013-12-07 12:29:22 +00001302 struct stat buf;
1303 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001304 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001305#endif
drhb959a012013-12-07 12:29:22 +00001306}
1307
aswift5b1a2562008-08-22 00:22:35 +00001308
1309/*
drhfbc7e882013-04-11 01:16:15 +00001310** Check a unixFile that is a database. Verify the following:
1311**
1312** (1) There is exactly one hard link on the file
1313** (2) The file is not a symbolic link
1314** (3) The file has not been renamed or unlinked
1315**
1316** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1317*/
1318static void verifyDbFile(unixFile *pFile){
1319 struct stat buf;
1320 int rc;
drh3044b512014-06-16 16:41:52 +00001321 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1322 /* One or more of the following warnings have already been issued. Do not
1323 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001324 return;
1325 }
1326 rc = osFstat(pFile->h, &buf);
1327 if( rc!=0 ){
1328 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1329 pFile->ctrlFlags |= UNIXFILE_WARNED;
1330 return;
1331 }
drh3044b512014-06-16 16:41:52 +00001332 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001333 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1334 pFile->ctrlFlags |= UNIXFILE_WARNED;
1335 return;
1336 }
1337 if( buf.st_nlink>1 ){
1338 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1339 pFile->ctrlFlags |= UNIXFILE_WARNED;
1340 return;
1341 }
drhb959a012013-12-07 12:29:22 +00001342 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001343 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1344 pFile->ctrlFlags |= UNIXFILE_WARNED;
1345 return;
1346 }
1347}
1348
1349
1350/*
danielk197713adf8a2004-06-03 16:08:41 +00001351** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001352** file by this or any other process. If such a lock is held, set *pResOut
1353** to a non-zero value otherwise *pResOut is set to zero. The return value
1354** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001355*/
danielk1977861f7452008-06-05 11:39:11 +00001356static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001357 int rc = SQLITE_OK;
1358 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001359 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001360
danielk1977861f7452008-06-05 11:39:11 +00001361 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1362
drh054889e2005-11-30 03:20:31 +00001363 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001364 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001365
1366 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001367 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001368 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001369 }
1370
drh2ac3ee92004-06-07 16:27:46 +00001371 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001372 */
danielk197709480a92009-02-09 05:32:32 +00001373#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001374 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001375 struct flock lock;
1376 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001377 lock.l_start = RESERVED_BYTE;
1378 lock.l_len = 1;
1379 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001380 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1381 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
1382 pFile->lastErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001383 } else if( lock.l_type!=F_UNLCK ){
1384 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001385 }
1386 }
danielk197709480a92009-02-09 05:32:32 +00001387#endif
danielk197713adf8a2004-06-03 16:08:41 +00001388
drh6c7d5c52008-11-21 20:32:33 +00001389 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001390 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001391
aswift5b1a2562008-08-22 00:22:35 +00001392 *pResOut = reserved;
1393 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001394}
1395
1396/*
drha7e61d82011-03-12 17:02:57 +00001397** Attempt to set a system-lock on the file pFile. The lock is
1398** described by pLock.
1399**
drh77197112011-03-15 19:08:48 +00001400** If the pFile was opened read/write from unix-excl, then the only lock
1401** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001402** the first time any lock is attempted. All subsequent system locking
1403** operations become no-ops. Locking operations still happen internally,
1404** in order to coordinate access between separate database connections
1405** within this process, but all of that is handled in memory and the
1406** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001407**
1408** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1409** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1410** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001411**
1412** Zero is returned if the call completes successfully, or -1 if a call
1413** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001414*/
1415static int unixFileLock(unixFile *pFile, struct flock *pLock){
1416 int rc;
drh3cb93392011-03-12 18:10:44 +00001417 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001418 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001419 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001420 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1421 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1422 ){
drh3cb93392011-03-12 18:10:44 +00001423 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001424 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001425 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001426 lock.l_whence = SEEK_SET;
1427 lock.l_start = SHARED_FIRST;
1428 lock.l_len = SHARED_SIZE;
1429 lock.l_type = F_WRLCK;
1430 rc = osFcntl(pFile->h, F_SETLK, &lock);
1431 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001432 pInode->bProcessLock = 1;
1433 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001434 }else{
1435 rc = 0;
1436 }
1437 }else{
1438 rc = osFcntl(pFile->h, F_SETLK, pLock);
1439 }
1440 return rc;
1441}
1442
1443/*
drh308c2a52010-05-14 11:30:18 +00001444** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001445** of the following:
1446**
drh2ac3ee92004-06-07 16:27:46 +00001447** (1) SHARED_LOCK
1448** (2) RESERVED_LOCK
1449** (3) PENDING_LOCK
1450** (4) EXCLUSIVE_LOCK
1451**
drhb3e04342004-06-08 00:47:47 +00001452** Sometimes when requesting one lock state, additional lock states
1453** are inserted in between. The locking might fail on one of the later
1454** transitions leaving the lock state different from what it started but
1455** still short of its goal. The following chart shows the allowed
1456** transitions and the inserted intermediate states:
1457**
1458** UNLOCKED -> SHARED
1459** SHARED -> RESERVED
1460** SHARED -> (PENDING) -> EXCLUSIVE
1461** RESERVED -> (PENDING) -> EXCLUSIVE
1462** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001463**
drha6abd042004-06-09 17:37:22 +00001464** This routine will only increase a lock. Use the sqlite3OsUnlock()
1465** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001466*/
drh308c2a52010-05-14 11:30:18 +00001467static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001468 /* The following describes the implementation of the various locks and
1469 ** lock transitions in terms of the POSIX advisory shared and exclusive
1470 ** lock primitives (called read-locks and write-locks below, to avoid
1471 ** confusion with SQLite lock names). The algorithms are complicated
1472 ** slightly in order to be compatible with windows systems simultaneously
1473 ** accessing the same database file, in case that is ever required.
1474 **
1475 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1476 ** byte', each single bytes at well known offsets, and the 'shared byte
1477 ** range', a range of 510 bytes at a well known offset.
1478 **
1479 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1480 ** byte'. If this is successful, a random byte from the 'shared byte
1481 ** range' is read-locked and the lock on the 'pending byte' released.
1482 **
danielk197790ba3bd2004-06-25 08:32:25 +00001483 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1484 ** A RESERVED lock is implemented by grabbing a write-lock on the
1485 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001486 **
1487 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001488 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1489 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1490 ** obtained, but existing SHARED locks are allowed to persist. A process
1491 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1492 ** This property is used by the algorithm for rolling back a journal file
1493 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001494 **
danielk197790ba3bd2004-06-25 08:32:25 +00001495 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1496 ** implemented by obtaining a write-lock on the entire 'shared byte
1497 ** range'. Since all other locks require a read-lock on one of the bytes
1498 ** within this range, this ensures that no other locks are held on the
1499 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001500 **
1501 ** The reason a single byte cannot be used instead of the 'shared byte
1502 ** range' is that some versions of windows do not support read-locks. By
1503 ** locking a random byte from a range, concurrent SHARED locks may exist
1504 ** even if the locking primitive used is always a write-lock.
1505 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001506 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001507 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001508 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001509 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001510 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001511
drh054889e2005-11-30 03:20:31 +00001512 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001513 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1514 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drhb07028f2011-10-14 21:49:18 +00001515 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001516
1517 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001518 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001519 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001520 */
drh308c2a52010-05-14 11:30:18 +00001521 if( pFile->eFileLock>=eFileLock ){
1522 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1523 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001524 return SQLITE_OK;
1525 }
1526
drh0c2694b2009-09-03 16:23:44 +00001527 /* Make sure the locking sequence is correct.
1528 ** (1) We never move from unlocked to anything higher than shared lock.
1529 ** (2) SQLite never explicitly requests a pendig lock.
1530 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001531 */
drh308c2a52010-05-14 11:30:18 +00001532 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1533 assert( eFileLock!=PENDING_LOCK );
1534 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001535
drh8af6c222010-05-14 12:43:01 +00001536 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001537 */
drh6c7d5c52008-11-21 20:32:33 +00001538 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001539 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001540
danielk1977ad94b582007-08-20 06:44:22 +00001541 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001542 ** handle that precludes the requested lock, return BUSY.
1543 */
drh8af6c222010-05-14 12:43:01 +00001544 if( (pFile->eFileLock!=pInode->eFileLock &&
1545 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001546 ){
1547 rc = SQLITE_BUSY;
1548 goto end_lock;
1549 }
1550
1551 /* If a SHARED lock is requested, and some thread using this PID already
1552 ** has a SHARED or RESERVED lock, then increment reference counts and
1553 ** return SQLITE_OK.
1554 */
drh308c2a52010-05-14 11:30:18 +00001555 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001556 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001557 assert( eFileLock==SHARED_LOCK );
1558 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001559 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001560 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001561 pInode->nShared++;
1562 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001563 goto end_lock;
1564 }
1565
danielk19779a1d0ab2004-06-01 14:09:28 +00001566
drh3cde3bb2004-06-12 02:17:14 +00001567 /* A PENDING lock is needed before acquiring a SHARED lock and before
1568 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1569 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001570 */
drh0c2694b2009-09-03 16:23:44 +00001571 lock.l_len = 1L;
1572 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001573 if( eFileLock==SHARED_LOCK
1574 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001575 ){
drh308c2a52010-05-14 11:30:18 +00001576 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001577 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001578 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001579 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001580 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001581 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001582 pFile->lastErrno = tErrno;
1583 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001584 goto end_lock;
1585 }
drh3cde3bb2004-06-12 02:17:14 +00001586 }
1587
1588
1589 /* If control gets to this point, then actually go ahead and make
1590 ** operating system calls for the specified lock.
1591 */
drh308c2a52010-05-14 11:30:18 +00001592 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001593 assert( pInode->nShared==0 );
1594 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001595 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001596
drh2ac3ee92004-06-07 16:27:46 +00001597 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001598 lock.l_start = SHARED_FIRST;
1599 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001600 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001601 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001602 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001603 }
dan661d71a2011-03-30 19:08:03 +00001604
drh2ac3ee92004-06-07 16:27:46 +00001605 /* Drop the temporary PENDING lock */
1606 lock.l_start = PENDING_BYTE;
1607 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001608 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001609 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1610 /* This could happen with a network mount */
1611 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001612 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001613 }
dan661d71a2011-03-30 19:08:03 +00001614
1615 if( rc ){
1616 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001617 pFile->lastErrno = tErrno;
1618 }
dan661d71a2011-03-30 19:08:03 +00001619 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001620 }else{
drh308c2a52010-05-14 11:30:18 +00001621 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001622 pInode->nLock++;
1623 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001624 }
drh8af6c222010-05-14 12:43:01 +00001625 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001626 /* We are trying for an exclusive lock but another thread in this
1627 ** same process is still holding a shared lock. */
1628 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001629 }else{
drh3cde3bb2004-06-12 02:17:14 +00001630 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001631 ** assumed that there is a SHARED or greater lock on the file
1632 ** already.
1633 */
drh308c2a52010-05-14 11:30:18 +00001634 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001635 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001636
1637 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1638 if( eFileLock==RESERVED_LOCK ){
1639 lock.l_start = RESERVED_BYTE;
1640 lock.l_len = 1L;
1641 }else{
1642 lock.l_start = SHARED_FIRST;
1643 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001644 }
dan661d71a2011-03-30 19:08:03 +00001645
1646 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001647 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001648 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001649 if( rc!=SQLITE_BUSY ){
aswift5b1a2562008-08-22 00:22:35 +00001650 pFile->lastErrno = tErrno;
1651 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001652 }
drhbbd42a62004-05-22 17:41:58 +00001653 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001654
drh8f941bc2009-01-14 23:03:40 +00001655
drhd3d8c042012-05-29 17:02:40 +00001656#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001657 /* Set up the transaction-counter change checking flags when
1658 ** transitioning from a SHARED to a RESERVED lock. The change
1659 ** from SHARED to RESERVED marks the beginning of a normal
1660 ** write operation (not a hot journal rollback).
1661 */
1662 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001663 && pFile->eFileLock<=SHARED_LOCK
1664 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001665 ){
1666 pFile->transCntrChng = 0;
1667 pFile->dbUpdate = 0;
1668 pFile->inNormalWrite = 1;
1669 }
1670#endif
1671
1672
danielk1977ecb2a962004-06-02 06:30:16 +00001673 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001674 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001675 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001676 }else if( eFileLock==EXCLUSIVE_LOCK ){
1677 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001678 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001679 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001680
1681end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001682 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001683 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1684 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001685 return rc;
1686}
1687
1688/*
dan08da86a2009-08-21 17:18:03 +00001689** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001690** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001691*/
1692static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001693 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001694 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001695 p->pNext = pInode->pUnused;
1696 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001697 pFile->h = -1;
1698 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001699}
1700
1701/*
drh308c2a52010-05-14 11:30:18 +00001702** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001703** must be either NO_LOCK or SHARED_LOCK.
1704**
1705** If the locking level of the file descriptor is already at or below
1706** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001707**
1708** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1709** the byte range is divided into 2 parts and the first part is unlocked then
1710** set to a read lock, then the other part is simply unlocked. This works
1711** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1712** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001713*/
drha7e61d82011-03-12 17:02:57 +00001714static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001715 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001716 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001717 struct flock lock;
1718 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001719
drh054889e2005-11-30 03:20:31 +00001720 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001721 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001722 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00001723 getpid()));
drha6abd042004-06-09 17:37:22 +00001724
drh308c2a52010-05-14 11:30:18 +00001725 assert( eFileLock<=SHARED_LOCK );
1726 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001727 return SQLITE_OK;
1728 }
drh6c7d5c52008-11-21 20:32:33 +00001729 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001730 pInode = pFile->pInode;
1731 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001732 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001733 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001734
drhd3d8c042012-05-29 17:02:40 +00001735#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001736 /* When reducing a lock such that other processes can start
1737 ** reading the database file again, make sure that the
1738 ** transaction counter was updated if any part of the database
1739 ** file changed. If the transaction counter is not updated,
1740 ** other connections to the same file might not realize that
1741 ** the file has changed and hence might not know to flush their
1742 ** cache. The use of a stale cache can lead to database corruption.
1743 */
drh8f941bc2009-01-14 23:03:40 +00001744 pFile->inNormalWrite = 0;
1745#endif
1746
drh7ed97b92010-01-20 13:07:21 +00001747 /* downgrading to a shared lock on NFS involves clearing the write lock
1748 ** before establishing the readlock - to avoid a race condition we downgrade
1749 ** the lock in 2 blocks, so that part of the range will be covered by a
1750 ** write lock until the rest is covered by a read lock:
1751 ** 1: [WWWWW]
1752 ** 2: [....W]
1753 ** 3: [RRRRW]
1754 ** 4: [RRRR.]
1755 */
drh308c2a52010-05-14 11:30:18 +00001756 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001757
1758#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001759 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001760 assert( handleNFSUnlock==0 );
1761#endif
1762#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001763 if( handleNFSUnlock ){
drh026663d2011-04-01 13:29:29 +00001764 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001765 off_t divSize = SHARED_SIZE - 1;
1766
1767 lock.l_type = F_UNLCK;
1768 lock.l_whence = SEEK_SET;
1769 lock.l_start = SHARED_FIRST;
1770 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001771 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001772 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001773 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001774 if( IS_LOCK_ERROR(rc) ){
1775 pFile->lastErrno = tErrno;
1776 }
1777 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001778 }
drh7ed97b92010-01-20 13:07:21 +00001779 lock.l_type = F_RDLCK;
1780 lock.l_whence = SEEK_SET;
1781 lock.l_start = SHARED_FIRST;
1782 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001783 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001784 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001785 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1786 if( IS_LOCK_ERROR(rc) ){
1787 pFile->lastErrno = tErrno;
1788 }
1789 goto end_unlock;
1790 }
1791 lock.l_type = F_UNLCK;
1792 lock.l_whence = SEEK_SET;
1793 lock.l_start = SHARED_FIRST+divSize;
1794 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001795 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001796 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001797 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001798 if( IS_LOCK_ERROR(rc) ){
1799 pFile->lastErrno = tErrno;
1800 }
1801 goto end_unlock;
1802 }
drh30f776f2011-02-25 03:25:07 +00001803 }else
1804#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1805 {
drh7ed97b92010-01-20 13:07:21 +00001806 lock.l_type = F_RDLCK;
1807 lock.l_whence = SEEK_SET;
1808 lock.l_start = SHARED_FIRST;
1809 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001810 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001811 /* In theory, the call to unixFileLock() cannot fail because another
1812 ** process is holding an incompatible lock. If it does, this
1813 ** indicates that the other process is not following the locking
1814 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1815 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1816 ** an assert to fail). */
1817 rc = SQLITE_IOERR_RDLOCK;
1818 pFile->lastErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001819 goto end_unlock;
1820 }
drh9c105bb2004-10-02 20:38:28 +00001821 }
1822 }
drhbbd42a62004-05-22 17:41:58 +00001823 lock.l_type = F_UNLCK;
1824 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001825 lock.l_start = PENDING_BYTE;
1826 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001827 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001828 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001829 }else{
danea83bc62011-04-01 11:56:32 +00001830 rc = SQLITE_IOERR_UNLOCK;
1831 pFile->lastErrno = errno;
drhcd731cf2009-03-28 23:23:02 +00001832 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001833 }
drhbbd42a62004-05-22 17:41:58 +00001834 }
drh308c2a52010-05-14 11:30:18 +00001835 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001836 /* Decrement the shared lock counter. Release the lock using an
1837 ** OS call only when all threads in this same process have released
1838 ** the lock.
1839 */
drh8af6c222010-05-14 12:43:01 +00001840 pInode->nShared--;
1841 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001842 lock.l_type = F_UNLCK;
1843 lock.l_whence = SEEK_SET;
1844 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001845 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001846 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001847 }else{
danea83bc62011-04-01 11:56:32 +00001848 rc = SQLITE_IOERR_UNLOCK;
drhf2f105d2012-08-20 15:53:54 +00001849 pFile->lastErrno = errno;
drh8af6c222010-05-14 12:43:01 +00001850 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001851 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001852 }
drha6abd042004-06-09 17:37:22 +00001853 }
1854
drhbbd42a62004-05-22 17:41:58 +00001855 /* Decrement the count of locks against this same file. When the
1856 ** count reaches zero, close any other file descriptors whose close
1857 ** was deferred because of outstanding locks.
1858 */
drh8af6c222010-05-14 12:43:01 +00001859 pInode->nLock--;
1860 assert( pInode->nLock>=0 );
1861 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001862 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001863 }
1864 }
drhf2f105d2012-08-20 15:53:54 +00001865
aswift5b1a2562008-08-22 00:22:35 +00001866end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001867 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001868 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001869 return rc;
drhbbd42a62004-05-22 17:41:58 +00001870}
1871
1872/*
drh308c2a52010-05-14 11:30:18 +00001873** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001874** must be either NO_LOCK or SHARED_LOCK.
1875**
1876** If the locking level of the file descriptor is already at or below
1877** the requested locking level, this routine is a no-op.
1878*/
drh308c2a52010-05-14 11:30:18 +00001879static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001880#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001881 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001882#endif
drha7e61d82011-03-12 17:02:57 +00001883 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001884}
1885
mistachkine98844f2013-08-24 00:59:24 +00001886#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001887static int unixMapfile(unixFile *pFd, i64 nByte);
1888static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001889#endif
danf23da962013-03-23 21:00:41 +00001890
drh7ed97b92010-01-20 13:07:21 +00001891/*
danielk1977e339d652008-06-28 11:23:00 +00001892** This function performs the parts of the "close file" operation
1893** common to all locking schemes. It closes the directory and file
1894** handles, if they are valid, and sets all fields of the unixFile
1895** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001896**
1897** It is *not* necessary to hold the mutex when this routine is called,
1898** even on VxWorks. A mutex will be acquired on VxWorks by the
1899** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001900*/
1901static int closeUnixFile(sqlite3_file *id){
1902 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001903#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001904 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001905#endif
dan661d71a2011-03-30 19:08:03 +00001906 if( pFile->h>=0 ){
1907 robust_close(pFile, pFile->h, __LINE__);
1908 pFile->h = -1;
1909 }
1910#if OS_VXWORKS
1911 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001912 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001913 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001914 }
1915 vxworksReleaseFileId(pFile->pId);
1916 pFile->pId = 0;
1917 }
1918#endif
drh0bdbc902014-06-16 18:35:06 +00001919#ifdef SQLITE_UNLINK_AFTER_CLOSE
1920 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1921 osUnlink(pFile->zPath);
1922 sqlite3_free(*(char**)&pFile->zPath);
1923 pFile->zPath = 0;
1924 }
1925#endif
dan661d71a2011-03-30 19:08:03 +00001926 OSTRACE(("CLOSE %-3d\n", pFile->h));
1927 OpenCounter(-1);
1928 sqlite3_free(pFile->pUnused);
1929 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001930 return SQLITE_OK;
1931}
1932
1933/*
danielk1977e3026632004-06-22 11:29:02 +00001934** Close a file.
1935*/
danielk197762079062007-08-15 17:08:46 +00001936static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001937 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001938 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001939 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001940 unixUnlock(id, NO_LOCK);
1941 unixEnterMutex();
1942
1943 /* unixFile.pInode is always valid here. Otherwise, a different close
1944 ** routine (e.g. nolockClose()) would be called instead.
1945 */
1946 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1947 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1948 /* If there are outstanding locks, do not actually close the file just
1949 ** yet because that would clear those locks. Instead, add the file
1950 ** descriptor to pInode->pUnused list. It will be automatically closed
1951 ** when the last lock is cleared.
1952 */
1953 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001954 }
dan661d71a2011-03-30 19:08:03 +00001955 releaseInodeInfo(pFile);
1956 rc = closeUnixFile(id);
1957 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001958 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001959}
1960
drh734c9862008-11-28 15:37:20 +00001961/************** End of the posix advisory lock implementation *****************
1962******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001963
drh734c9862008-11-28 15:37:20 +00001964/******************************************************************************
1965****************************** No-op Locking **********************************
1966**
1967** Of the various locking implementations available, this is by far the
1968** simplest: locking is ignored. No attempt is made to lock the database
1969** file for reading or writing.
1970**
1971** This locking mode is appropriate for use on read-only databases
1972** (ex: databases that are burned into CD-ROM, for example.) It can
1973** also be used if the application employs some external mechanism to
1974** prevent simultaneous access of the same database by two or more
1975** database connections. But there is a serious risk of database
1976** corruption if this locking mode is used in situations where multiple
1977** database connections are accessing the same database file at the same
1978** time and one or more of those connections are writing.
1979*/
drhbfe66312006-10-03 17:40:40 +00001980
drh734c9862008-11-28 15:37:20 +00001981static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
1982 UNUSED_PARAMETER(NotUsed);
1983 *pResOut = 0;
1984 return SQLITE_OK;
1985}
drh734c9862008-11-28 15:37:20 +00001986static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
1987 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1988 return SQLITE_OK;
1989}
drh734c9862008-11-28 15:37:20 +00001990static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
1991 UNUSED_PARAMETER2(NotUsed, NotUsed2);
1992 return SQLITE_OK;
1993}
1994
1995/*
drh9b35ea62008-11-29 02:20:26 +00001996** Close the file.
drh734c9862008-11-28 15:37:20 +00001997*/
1998static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00001999 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002000}
2001
2002/******************* End of the no-op lock implementation *********************
2003******************************************************************************/
2004
2005/******************************************************************************
2006************************* Begin dot-file Locking ******************************
2007**
mistachkin48864df2013-03-21 21:20:32 +00002008** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002009** files (really a directory) to control access to the database. This works
2010** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002011**
2012** (1) There is zero concurrency. A single reader blocks all other
2013** connections from reading or writing the database.
2014**
2015** (2) An application crash or power loss can leave stale lock files
2016** sitting around that need to be cleared manually.
2017**
2018** Nevertheless, a dotlock is an appropriate locking mode for use if no
2019** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002020**
drh9ef6bc42011-11-04 02:24:02 +00002021** Dotfile locking works by creating a subdirectory in the same directory as
2022** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002023** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002024** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002025*/
2026
2027/*
2028** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002029** lock directory.
drh734c9862008-11-28 15:37:20 +00002030*/
2031#define DOTLOCK_SUFFIX ".lock"
2032
drh7708e972008-11-29 00:56:52 +00002033/*
2034** This routine checks if there is a RESERVED lock held on the specified
2035** file by this or any other process. If such a lock is held, set *pResOut
2036** to a non-zero value otherwise *pResOut is set to zero. The return value
2037** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2038**
2039** In dotfile locking, either a lock exists or it does not. So in this
2040** variation of CheckReservedLock(), *pResOut is set to true if any lock
2041** is held on the file and false if the file is unlocked.
2042*/
drh734c9862008-11-28 15:37:20 +00002043static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2044 int rc = SQLITE_OK;
2045 int reserved = 0;
2046 unixFile *pFile = (unixFile*)id;
2047
2048 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2049
2050 assert( pFile );
2051
2052 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002053 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002054 /* Either this connection or some other connection in the same process
2055 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002056 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002057 }else{
2058 /* The lock is held if and only if the lockfile exists */
2059 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002060 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002061 }
drh308c2a52010-05-14 11:30:18 +00002062 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002063 *pResOut = reserved;
2064 return rc;
2065}
2066
drh7708e972008-11-29 00:56:52 +00002067/*
drh308c2a52010-05-14 11:30:18 +00002068** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002069** of the following:
2070**
2071** (1) SHARED_LOCK
2072** (2) RESERVED_LOCK
2073** (3) PENDING_LOCK
2074** (4) EXCLUSIVE_LOCK
2075**
2076** Sometimes when requesting one lock state, additional lock states
2077** are inserted in between. The locking might fail on one of the later
2078** transitions leaving the lock state different from what it started but
2079** still short of its goal. The following chart shows the allowed
2080** transitions and the inserted intermediate states:
2081**
2082** UNLOCKED -> SHARED
2083** SHARED -> RESERVED
2084** SHARED -> (PENDING) -> EXCLUSIVE
2085** RESERVED -> (PENDING) -> EXCLUSIVE
2086** PENDING -> EXCLUSIVE
2087**
2088** This routine will only increase a lock. Use the sqlite3OsUnlock()
2089** routine to lower a locking level.
2090**
2091** With dotfile locking, we really only support state (4): EXCLUSIVE.
2092** But we track the other locking levels internally.
2093*/
drh308c2a52010-05-14 11:30:18 +00002094static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002095 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002096 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002097 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002098
drh7708e972008-11-29 00:56:52 +00002099
2100 /* If we have any lock, then the lock file already exists. All we have
2101 ** to do is adjust our internal record of the lock level.
2102 */
drh308c2a52010-05-14 11:30:18 +00002103 if( pFile->eFileLock > NO_LOCK ){
2104 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002105 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002106#ifdef HAVE_UTIME
2107 utime(zLockFile, NULL);
2108#else
drh734c9862008-11-28 15:37:20 +00002109 utimes(zLockFile, NULL);
2110#endif
drh7708e972008-11-29 00:56:52 +00002111 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002112 }
2113
2114 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002115 rc = osMkdir(zLockFile, 0777);
2116 if( rc<0 ){
2117 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002118 int tErrno = errno;
2119 if( EEXIST == tErrno ){
2120 rc = SQLITE_BUSY;
2121 } else {
2122 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2123 if( IS_LOCK_ERROR(rc) ){
2124 pFile->lastErrno = tErrno;
2125 }
2126 }
drh7708e972008-11-29 00:56:52 +00002127 return rc;
drh734c9862008-11-28 15:37:20 +00002128 }
drh734c9862008-11-28 15:37:20 +00002129
2130 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002131 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002132 return rc;
2133}
2134
drh7708e972008-11-29 00:56:52 +00002135/*
drh308c2a52010-05-14 11:30:18 +00002136** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002137** must be either NO_LOCK or SHARED_LOCK.
2138**
2139** If the locking level of the file descriptor is already at or below
2140** the requested locking level, this routine is a no-op.
2141**
2142** When the locking level reaches NO_LOCK, delete the lock file.
2143*/
drh308c2a52010-05-14 11:30:18 +00002144static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002145 unixFile *pFile = (unixFile*)id;
2146 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002147 int rc;
drh734c9862008-11-28 15:37:20 +00002148
2149 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002150 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002151 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002152 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002153
2154 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002155 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002156 return SQLITE_OK;
2157 }
drh7708e972008-11-29 00:56:52 +00002158
2159 /* To downgrade to shared, simply update our internal notion of the
2160 ** lock state. No need to mess with the file on disk.
2161 */
drh308c2a52010-05-14 11:30:18 +00002162 if( eFileLock==SHARED_LOCK ){
2163 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002164 return SQLITE_OK;
2165 }
2166
drh7708e972008-11-29 00:56:52 +00002167 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002168 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002169 rc = osRmdir(zLockFile);
2170 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2171 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002172 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002173 rc = 0;
drh734c9862008-11-28 15:37:20 +00002174 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002175 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002176 }
2177 if( IS_LOCK_ERROR(rc) ){
2178 pFile->lastErrno = tErrno;
2179 }
2180 return rc;
2181 }
drh308c2a52010-05-14 11:30:18 +00002182 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002183 return SQLITE_OK;
2184}
2185
2186/*
drh9b35ea62008-11-29 02:20:26 +00002187** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002188*/
2189static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002190 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002191 if( id ){
2192 unixFile *pFile = (unixFile*)id;
2193 dotlockUnlock(id, NO_LOCK);
2194 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002195 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002196 }
drh734c9862008-11-28 15:37:20 +00002197 return rc;
2198}
2199/****************** End of the dot-file lock implementation *******************
2200******************************************************************************/
2201
2202/******************************************************************************
2203************************** Begin flock Locking ********************************
2204**
2205** Use the flock() system call to do file locking.
2206**
drh6b9d6dd2008-12-03 19:34:47 +00002207** flock() locking is like dot-file locking in that the various
2208** fine-grain locking levels supported by SQLite are collapsed into
2209** a single exclusive lock. In other words, SHARED, RESERVED, and
2210** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2211** still works when you do this, but concurrency is reduced since
2212** only a single process can be reading the database at a time.
2213**
drh734c9862008-11-28 15:37:20 +00002214** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2215** compiling for VXWORKS.
2216*/
2217#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002218
drh6b9d6dd2008-12-03 19:34:47 +00002219/*
drhff812312011-02-23 13:33:46 +00002220** Retry flock() calls that fail with EINTR
2221*/
2222#ifdef EINTR
2223static int robust_flock(int fd, int op){
2224 int rc;
2225 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2226 return rc;
2227}
2228#else
drh5c819272011-02-23 14:00:12 +00002229# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002230#endif
2231
2232
2233/*
drh6b9d6dd2008-12-03 19:34:47 +00002234** This routine checks if there is a RESERVED lock held on the specified
2235** file by this or any other process. If such a lock is held, set *pResOut
2236** to a non-zero value otherwise *pResOut is set to zero. The return value
2237** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2238*/
drh734c9862008-11-28 15:37:20 +00002239static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2240 int rc = SQLITE_OK;
2241 int reserved = 0;
2242 unixFile *pFile = (unixFile*)id;
2243
2244 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2245
2246 assert( pFile );
2247
2248 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002249 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002250 reserved = 1;
2251 }
2252
2253 /* Otherwise see if some other process holds it. */
2254 if( !reserved ){
2255 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002256 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002257 if( !lrc ){
2258 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002259 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002260 if ( lrc ) {
2261 int tErrno = errno;
2262 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002263 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002264 if( IS_LOCK_ERROR(lrc) ){
2265 pFile->lastErrno = tErrno;
2266 rc = lrc;
2267 }
2268 }
2269 } else {
2270 int tErrno = errno;
2271 reserved = 1;
2272 /* someone else might have it reserved */
2273 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2274 if( IS_LOCK_ERROR(lrc) ){
2275 pFile->lastErrno = tErrno;
2276 rc = lrc;
2277 }
2278 }
2279 }
drh308c2a52010-05-14 11:30:18 +00002280 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002281
2282#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2283 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2284 rc = SQLITE_OK;
2285 reserved=1;
2286 }
2287#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2288 *pResOut = reserved;
2289 return rc;
2290}
2291
drh6b9d6dd2008-12-03 19:34:47 +00002292/*
drh308c2a52010-05-14 11:30:18 +00002293** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002294** of the following:
2295**
2296** (1) SHARED_LOCK
2297** (2) RESERVED_LOCK
2298** (3) PENDING_LOCK
2299** (4) EXCLUSIVE_LOCK
2300**
2301** Sometimes when requesting one lock state, additional lock states
2302** are inserted in between. The locking might fail on one of the later
2303** transitions leaving the lock state different from what it started but
2304** still short of its goal. The following chart shows the allowed
2305** transitions and the inserted intermediate states:
2306**
2307** UNLOCKED -> SHARED
2308** SHARED -> RESERVED
2309** SHARED -> (PENDING) -> EXCLUSIVE
2310** RESERVED -> (PENDING) -> EXCLUSIVE
2311** PENDING -> EXCLUSIVE
2312**
2313** flock() only really support EXCLUSIVE locks. We track intermediate
2314** lock states in the sqlite3_file structure, but all locks SHARED or
2315** above are really EXCLUSIVE locks and exclude all other processes from
2316** access the file.
2317**
2318** This routine will only increase a lock. Use the sqlite3OsUnlock()
2319** routine to lower a locking level.
2320*/
drh308c2a52010-05-14 11:30:18 +00002321static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002322 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002323 unixFile *pFile = (unixFile*)id;
2324
2325 assert( pFile );
2326
2327 /* if we already have a lock, it is exclusive.
2328 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002329 if (pFile->eFileLock > NO_LOCK) {
2330 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002331 return SQLITE_OK;
2332 }
2333
2334 /* grab an exclusive lock */
2335
drhff812312011-02-23 13:33:46 +00002336 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002337 int tErrno = errno;
2338 /* didn't get, must be busy */
2339 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2340 if( IS_LOCK_ERROR(rc) ){
2341 pFile->lastErrno = tErrno;
2342 }
2343 } else {
2344 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002345 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002346 }
drh308c2a52010-05-14 11:30:18 +00002347 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2348 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002349#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2350 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2351 rc = SQLITE_BUSY;
2352 }
2353#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2354 return rc;
2355}
2356
drh6b9d6dd2008-12-03 19:34:47 +00002357
2358/*
drh308c2a52010-05-14 11:30:18 +00002359** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002360** must be either NO_LOCK or SHARED_LOCK.
2361**
2362** If the locking level of the file descriptor is already at or below
2363** the requested locking level, this routine is a no-op.
2364*/
drh308c2a52010-05-14 11:30:18 +00002365static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002366 unixFile *pFile = (unixFile*)id;
2367
2368 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002369 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2370 pFile->eFileLock, getpid()));
2371 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002372
2373 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002374 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002375 return SQLITE_OK;
2376 }
2377
2378 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002379 if (eFileLock==SHARED_LOCK) {
2380 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002381 return SQLITE_OK;
2382 }
2383
2384 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002385 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002386#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002387 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002388#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002389 return SQLITE_IOERR_UNLOCK;
2390 }else{
drh308c2a52010-05-14 11:30:18 +00002391 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002392 return SQLITE_OK;
2393 }
2394}
2395
2396/*
2397** Close a file.
2398*/
2399static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002400 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002401 if( id ){
2402 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002403 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002404 }
drh5a05be12012-10-09 18:51:44 +00002405 return rc;
drh734c9862008-11-28 15:37:20 +00002406}
2407
2408#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2409
2410/******************* End of the flock lock implementation *********************
2411******************************************************************************/
2412
2413/******************************************************************************
2414************************ Begin Named Semaphore Locking ************************
2415**
2416** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002417**
2418** Semaphore locking is like dot-lock and flock in that it really only
2419** supports EXCLUSIVE locking. Only a single process can read or write
2420** the database file at a time. This reduces potential concurrency, but
2421** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002422*/
2423#if OS_VXWORKS
2424
drh6b9d6dd2008-12-03 19:34:47 +00002425/*
2426** This routine checks if there is a RESERVED lock held on the specified
2427** file by this or any other process. If such a lock is held, set *pResOut
2428** to a non-zero value otherwise *pResOut is set to zero. The return value
2429** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2430*/
drh734c9862008-11-28 15:37:20 +00002431static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2432 int rc = SQLITE_OK;
2433 int reserved = 0;
2434 unixFile *pFile = (unixFile*)id;
2435
2436 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2437
2438 assert( pFile );
2439
2440 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002441 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002442 reserved = 1;
2443 }
2444
2445 /* Otherwise see if some other process holds it. */
2446 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002447 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002448
2449 if( sem_trywait(pSem)==-1 ){
2450 int tErrno = errno;
2451 if( EAGAIN != tErrno ){
2452 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2453 pFile->lastErrno = tErrno;
2454 } else {
2455 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002456 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002457 }
2458 }else{
2459 /* we could have it if we want it */
2460 sem_post(pSem);
2461 }
2462 }
drh308c2a52010-05-14 11:30:18 +00002463 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002464
2465 *pResOut = reserved;
2466 return rc;
2467}
2468
drh6b9d6dd2008-12-03 19:34:47 +00002469/*
drh308c2a52010-05-14 11:30:18 +00002470** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002471** of the following:
2472**
2473** (1) SHARED_LOCK
2474** (2) RESERVED_LOCK
2475** (3) PENDING_LOCK
2476** (4) EXCLUSIVE_LOCK
2477**
2478** Sometimes when requesting one lock state, additional lock states
2479** are inserted in between. The locking might fail on one of the later
2480** transitions leaving the lock state different from what it started but
2481** still short of its goal. The following chart shows the allowed
2482** transitions and the inserted intermediate states:
2483**
2484** UNLOCKED -> SHARED
2485** SHARED -> RESERVED
2486** SHARED -> (PENDING) -> EXCLUSIVE
2487** RESERVED -> (PENDING) -> EXCLUSIVE
2488** PENDING -> EXCLUSIVE
2489**
2490** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2491** lock states in the sqlite3_file structure, but all locks SHARED or
2492** above are really EXCLUSIVE locks and exclude all other processes from
2493** access the file.
2494**
2495** This routine will only increase a lock. Use the sqlite3OsUnlock()
2496** routine to lower a locking level.
2497*/
drh308c2a52010-05-14 11:30:18 +00002498static int semLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002499 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002500 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002501 int rc = SQLITE_OK;
2502
2503 /* if we already have a lock, it is exclusive.
2504 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002505 if (pFile->eFileLock > NO_LOCK) {
2506 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002507 rc = SQLITE_OK;
2508 goto sem_end_lock;
2509 }
2510
2511 /* lock semaphore now but bail out when already locked. */
2512 if( sem_trywait(pSem)==-1 ){
2513 rc = SQLITE_BUSY;
2514 goto sem_end_lock;
2515 }
2516
2517 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002518 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002519
2520 sem_end_lock:
2521 return rc;
2522}
2523
drh6b9d6dd2008-12-03 19:34:47 +00002524/*
drh308c2a52010-05-14 11:30:18 +00002525** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002526** must be either NO_LOCK or SHARED_LOCK.
2527**
2528** If the locking level of the file descriptor is already at or below
2529** the requested locking level, this routine is a no-op.
2530*/
drh308c2a52010-05-14 11:30:18 +00002531static int semUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002532 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002533 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002534
2535 assert( pFile );
2536 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002537 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drhf2f105d2012-08-20 15:53:54 +00002538 pFile->eFileLock, getpid()));
drh308c2a52010-05-14 11:30:18 +00002539 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002540
2541 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002542 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002543 return SQLITE_OK;
2544 }
2545
2546 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002547 if (eFileLock==SHARED_LOCK) {
2548 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002549 return SQLITE_OK;
2550 }
2551
2552 /* no, really unlock. */
2553 if ( sem_post(pSem)==-1 ) {
2554 int rc, tErrno = errno;
2555 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2556 if( IS_LOCK_ERROR(rc) ){
2557 pFile->lastErrno = tErrno;
2558 }
2559 return rc;
2560 }
drh308c2a52010-05-14 11:30:18 +00002561 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002562 return SQLITE_OK;
2563}
2564
2565/*
2566 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002567 */
drh734c9862008-11-28 15:37:20 +00002568static int semClose(sqlite3_file *id) {
2569 if( id ){
2570 unixFile *pFile = (unixFile*)id;
2571 semUnlock(id, NO_LOCK);
2572 assert( pFile );
2573 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002574 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002575 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002576 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002577 }
2578 return SQLITE_OK;
2579}
2580
2581#endif /* OS_VXWORKS */
2582/*
2583** Named semaphore locking is only available on VxWorks.
2584**
2585*************** End of the named semaphore lock implementation ****************
2586******************************************************************************/
2587
2588
2589/******************************************************************************
2590*************************** Begin AFP Locking *********************************
2591**
2592** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2593** on Apple Macintosh computers - both OS9 and OSX.
2594**
2595** Third-party implementations of AFP are available. But this code here
2596** only works on OSX.
2597*/
2598
drhd2cb50b2009-01-09 21:41:17 +00002599#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002600/*
2601** The afpLockingContext structure contains all afp lock specific state
2602*/
drhbfe66312006-10-03 17:40:40 +00002603typedef struct afpLockingContext afpLockingContext;
2604struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002605 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002606 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002607};
2608
2609struct ByteRangeLockPB2
2610{
2611 unsigned long long offset; /* offset to first byte to lock */
2612 unsigned long long length; /* nbr of bytes to lock */
2613 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2614 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2615 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2616 int fd; /* file desc to assoc this lock with */
2617};
2618
drhfd131da2007-08-07 17:13:03 +00002619#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002620
drh6b9d6dd2008-12-03 19:34:47 +00002621/*
2622** This is a utility for setting or clearing a bit-range lock on an
2623** AFP filesystem.
2624**
2625** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2626*/
2627static int afpSetLock(
2628 const char *path, /* Name of the file to be locked or unlocked */
2629 unixFile *pFile, /* Open file descriptor on path */
2630 unsigned long long offset, /* First byte to be locked */
2631 unsigned long long length, /* Number of bytes to lock */
2632 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002633){
drh6b9d6dd2008-12-03 19:34:47 +00002634 struct ByteRangeLockPB2 pb;
2635 int err;
drhbfe66312006-10-03 17:40:40 +00002636
2637 pb.unLockFlag = setLockFlag ? 0 : 1;
2638 pb.startEndFlag = 0;
2639 pb.offset = offset;
2640 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002641 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002642
drh308c2a52010-05-14 11:30:18 +00002643 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002644 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002645 offset, length));
drhbfe66312006-10-03 17:40:40 +00002646 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2647 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002648 int rc;
2649 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002650 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2651 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002652#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2653 rc = SQLITE_BUSY;
2654#else
drh734c9862008-11-28 15:37:20 +00002655 rc = sqliteErrorFromPosixError(tErrno,
2656 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002657#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002658 if( IS_LOCK_ERROR(rc) ){
2659 pFile->lastErrno = tErrno;
2660 }
2661 return rc;
drhbfe66312006-10-03 17:40:40 +00002662 } else {
aswift5b1a2562008-08-22 00:22:35 +00002663 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002664 }
2665}
2666
drh6b9d6dd2008-12-03 19:34:47 +00002667/*
2668** This routine checks if there is a RESERVED lock held on the specified
2669** file by this or any other process. If such a lock is held, set *pResOut
2670** to a non-zero value otherwise *pResOut is set to zero. The return value
2671** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2672*/
danielk1977e339d652008-06-28 11:23:00 +00002673static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002674 int rc = SQLITE_OK;
2675 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002676 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002677 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002678
aswift5b1a2562008-08-22 00:22:35 +00002679 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2680
2681 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002682 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002683 if( context->reserved ){
2684 *pResOut = 1;
2685 return SQLITE_OK;
2686 }
drh8af6c222010-05-14 12:43:01 +00002687 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002688
2689 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002690 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002691 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002692 }
2693
2694 /* Otherwise see if some other process holds it.
2695 */
aswift5b1a2562008-08-22 00:22:35 +00002696 if( !reserved ){
2697 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002698 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002699 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002700 /* if we succeeded in taking the reserved lock, unlock it to restore
2701 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002702 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002703 } else {
2704 /* if we failed to get the lock then someone else must have it */
2705 reserved = 1;
2706 }
2707 if( IS_LOCK_ERROR(lrc) ){
2708 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002709 }
2710 }
drhbfe66312006-10-03 17:40:40 +00002711
drh7ed97b92010-01-20 13:07:21 +00002712 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002713 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002714
2715 *pResOut = reserved;
2716 return rc;
drhbfe66312006-10-03 17:40:40 +00002717}
2718
drh6b9d6dd2008-12-03 19:34:47 +00002719/*
drh308c2a52010-05-14 11:30:18 +00002720** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002721** of the following:
2722**
2723** (1) SHARED_LOCK
2724** (2) RESERVED_LOCK
2725** (3) PENDING_LOCK
2726** (4) EXCLUSIVE_LOCK
2727**
2728** Sometimes when requesting one lock state, additional lock states
2729** are inserted in between. The locking might fail on one of the later
2730** transitions leaving the lock state different from what it started but
2731** still short of its goal. The following chart shows the allowed
2732** transitions and the inserted intermediate states:
2733**
2734** UNLOCKED -> SHARED
2735** SHARED -> RESERVED
2736** SHARED -> (PENDING) -> EXCLUSIVE
2737** RESERVED -> (PENDING) -> EXCLUSIVE
2738** PENDING -> EXCLUSIVE
2739**
2740** This routine will only increase a lock. Use the sqlite3OsUnlock()
2741** routine to lower a locking level.
2742*/
drh308c2a52010-05-14 11:30:18 +00002743static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002744 int rc = SQLITE_OK;
2745 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002746 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002747 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002748
2749 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002750 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2751 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh8af6c222010-05-14 12:43:01 +00002752 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
drh339eb0b2008-03-07 15:34:11 +00002753
drhbfe66312006-10-03 17:40:40 +00002754 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002755 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002756 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002757 */
drh308c2a52010-05-14 11:30:18 +00002758 if( pFile->eFileLock>=eFileLock ){
2759 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2760 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002761 return SQLITE_OK;
2762 }
2763
2764 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002765 ** (1) We never move from unlocked to anything higher than shared lock.
2766 ** (2) SQLite never explicitly requests a pendig lock.
2767 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002768 */
drh308c2a52010-05-14 11:30:18 +00002769 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2770 assert( eFileLock!=PENDING_LOCK );
2771 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002772
drh8af6c222010-05-14 12:43:01 +00002773 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002774 */
drh6c7d5c52008-11-21 20:32:33 +00002775 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002776 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002777
2778 /* If some thread using this PID has a lock via a different unixFile*
2779 ** handle that precludes the requested lock, return BUSY.
2780 */
drh8af6c222010-05-14 12:43:01 +00002781 if( (pFile->eFileLock!=pInode->eFileLock &&
2782 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002783 ){
2784 rc = SQLITE_BUSY;
2785 goto afp_end_lock;
2786 }
2787
2788 /* If a SHARED lock is requested, and some thread using this PID already
2789 ** has a SHARED or RESERVED lock, then increment reference counts and
2790 ** return SQLITE_OK.
2791 */
drh308c2a52010-05-14 11:30:18 +00002792 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002793 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002794 assert( eFileLock==SHARED_LOCK );
2795 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002796 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002797 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002798 pInode->nShared++;
2799 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002800 goto afp_end_lock;
2801 }
drhbfe66312006-10-03 17:40:40 +00002802
2803 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002804 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2805 ** be released.
2806 */
drh308c2a52010-05-14 11:30:18 +00002807 if( eFileLock==SHARED_LOCK
2808 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002809 ){
2810 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002811 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002812 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002813 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002814 goto afp_end_lock;
2815 }
2816 }
2817
2818 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002819 ** operating system calls for the specified lock.
2820 */
drh308c2a52010-05-14 11:30:18 +00002821 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002822 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002823 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002824
drh8af6c222010-05-14 12:43:01 +00002825 assert( pInode->nShared==0 );
2826 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002827
2828 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002829 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002830 /* note that the quality of the randomness doesn't matter that much */
2831 lk = random();
drh8af6c222010-05-14 12:43:01 +00002832 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002833 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002834 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002835 if( IS_LOCK_ERROR(lrc1) ){
2836 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002837 }
aswift5b1a2562008-08-22 00:22:35 +00002838 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002839 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002840
aswift5b1a2562008-08-22 00:22:35 +00002841 if( IS_LOCK_ERROR(lrc1) ) {
2842 pFile->lastErrno = lrc1Errno;
2843 rc = lrc1;
2844 goto afp_end_lock;
2845 } else if( IS_LOCK_ERROR(lrc2) ){
2846 rc = lrc2;
2847 goto afp_end_lock;
2848 } else if( lrc1 != SQLITE_OK ) {
2849 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002850 } else {
drh308c2a52010-05-14 11:30:18 +00002851 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002852 pInode->nLock++;
2853 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002854 }
drh8af6c222010-05-14 12:43:01 +00002855 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002856 /* We are trying for an exclusive lock but another thread in this
2857 ** same process is still holding a shared lock. */
2858 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002859 }else{
2860 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2861 ** assumed that there is a SHARED or greater lock on the file
2862 ** already.
2863 */
2864 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002865 assert( 0!=pFile->eFileLock );
2866 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002867 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002868 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002869 if( !failed ){
2870 context->reserved = 1;
2871 }
drhbfe66312006-10-03 17:40:40 +00002872 }
drh308c2a52010-05-14 11:30:18 +00002873 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002874 /* Acquire an EXCLUSIVE lock */
2875
2876 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002877 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002878 */
drh6b9d6dd2008-12-03 19:34:47 +00002879 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002880 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002881 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002882 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002883 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002884 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002885 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002886 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002887 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2888 ** a critical I/O error
2889 */
2890 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2891 SQLITE_IOERR_LOCK;
2892 goto afp_end_lock;
2893 }
2894 }else{
aswift5b1a2562008-08-22 00:22:35 +00002895 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002896 }
2897 }
aswift5b1a2562008-08-22 00:22:35 +00002898 if( failed ){
2899 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002900 }
2901 }
2902
2903 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002904 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002905 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002906 }else if( eFileLock==EXCLUSIVE_LOCK ){
2907 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002908 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002909 }
2910
2911afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002912 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002913 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2914 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002915 return rc;
2916}
2917
2918/*
drh308c2a52010-05-14 11:30:18 +00002919** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002920** must be either NO_LOCK or SHARED_LOCK.
2921**
2922** If the locking level of the file descriptor is already at or below
2923** the requested locking level, this routine is a no-op.
2924*/
drh308c2a52010-05-14 11:30:18 +00002925static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002926 int rc = SQLITE_OK;
2927 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002928 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002929 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2930 int skipShared = 0;
2931#ifdef SQLITE_TEST
2932 int h = pFile->h;
2933#endif
drhbfe66312006-10-03 17:40:40 +00002934
2935 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002936 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002937 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh308c2a52010-05-14 11:30:18 +00002938 getpid()));
aswift5b1a2562008-08-22 00:22:35 +00002939
drh308c2a52010-05-14 11:30:18 +00002940 assert( eFileLock<=SHARED_LOCK );
2941 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002942 return SQLITE_OK;
2943 }
drh6c7d5c52008-11-21 20:32:33 +00002944 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002945 pInode = pFile->pInode;
2946 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002947 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002948 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002949 SimulateIOErrorBenign(1);
2950 SimulateIOError( h=(-1) )
2951 SimulateIOErrorBenign(0);
2952
drhd3d8c042012-05-29 17:02:40 +00002953#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002954 /* When reducing a lock such that other processes can start
2955 ** reading the database file again, make sure that the
2956 ** transaction counter was updated if any part of the database
2957 ** file changed. If the transaction counter is not updated,
2958 ** other connections to the same file might not realize that
2959 ** the file has changed and hence might not know to flush their
2960 ** cache. The use of a stale cache can lead to database corruption.
2961 */
2962 assert( pFile->inNormalWrite==0
2963 || pFile->dbUpdate==0
2964 || pFile->transCntrChng==1 );
2965 pFile->inNormalWrite = 0;
2966#endif
aswiftaebf4132008-11-21 00:10:35 +00002967
drh308c2a52010-05-14 11:30:18 +00002968 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002969 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002970 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002971 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002972 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002973 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2974 } else {
2975 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002976 }
2977 }
drh308c2a52010-05-14 11:30:18 +00002978 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002979 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002980 }
drh308c2a52010-05-14 11:30:18 +00002981 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002982 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2983 if( !rc ){
2984 context->reserved = 0;
2985 }
aswiftaebf4132008-11-21 00:10:35 +00002986 }
drh8af6c222010-05-14 12:43:01 +00002987 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2988 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002989 }
aswiftaebf4132008-11-21 00:10:35 +00002990 }
drh308c2a52010-05-14 11:30:18 +00002991 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002992
drh7ed97b92010-01-20 13:07:21 +00002993 /* Decrement the shared lock counter. Release the lock using an
2994 ** OS call only when all threads in this same process have released
2995 ** the lock.
2996 */
drh8af6c222010-05-14 12:43:01 +00002997 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2998 pInode->nShared--;
2999 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003000 SimulateIOErrorBenign(1);
3001 SimulateIOError( h=(-1) )
3002 SimulateIOErrorBenign(0);
3003 if( !skipShared ){
3004 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3005 }
3006 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003007 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003008 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003009 }
3010 }
3011 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003012 pInode->nLock--;
3013 assert( pInode->nLock>=0 );
3014 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003015 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003016 }
3017 }
drhbfe66312006-10-03 17:40:40 +00003018 }
drh7ed97b92010-01-20 13:07:21 +00003019
drh6c7d5c52008-11-21 20:32:33 +00003020 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003021 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003022 return rc;
3023}
3024
3025/*
drh339eb0b2008-03-07 15:34:11 +00003026** Close a file & cleanup AFP specific locking context
3027*/
danielk1977e339d652008-06-28 11:23:00 +00003028static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003029 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003030 if( id ){
3031 unixFile *pFile = (unixFile*)id;
3032 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003033 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003034 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003035 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003036 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003037 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003038 ** the last lock is cleared.
3039 */
dan08da86a2009-08-21 17:18:03 +00003040 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003041 }
danb0ac3e32010-06-16 10:55:42 +00003042 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003043 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003044 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003045 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003046 }
drh7ed97b92010-01-20 13:07:21 +00003047 return rc;
drhbfe66312006-10-03 17:40:40 +00003048}
3049
drhd2cb50b2009-01-09 21:41:17 +00003050#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003051/*
3052** The code above is the AFP lock implementation. The code is specific
3053** to MacOSX and does not work on other unix platforms. No alternative
3054** is available. If you don't compile for a mac, then the "unix-afp"
3055** VFS is not available.
3056**
3057********************* End of the AFP lock implementation **********************
3058******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003059
drh7ed97b92010-01-20 13:07:21 +00003060/******************************************************************************
3061*************************** Begin NFS Locking ********************************/
3062
3063#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3064/*
drh308c2a52010-05-14 11:30:18 +00003065 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003066 ** must be either NO_LOCK or SHARED_LOCK.
3067 **
3068 ** If the locking level of the file descriptor is already at or below
3069 ** the requested locking level, this routine is a no-op.
3070 */
drh308c2a52010-05-14 11:30:18 +00003071static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003072 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003073}
3074
3075#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3076/*
3077** The code above is the NFS lock implementation. The code is specific
3078** to MacOSX and does not work on other unix platforms. No alternative
3079** is available.
3080**
3081********************* End of the NFS lock implementation **********************
3082******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003083
3084/******************************************************************************
3085**************** Non-locking sqlite3_file methods *****************************
3086**
3087** The next division contains implementations for all methods of the
3088** sqlite3_file object other than the locking methods. The locking
3089** methods were defined in divisions above (one locking method per
3090** division). Those methods that are common to all locking modes
3091** are gather together into this division.
3092*/
drhbfe66312006-10-03 17:40:40 +00003093
3094/*
drh734c9862008-11-28 15:37:20 +00003095** Seek to the offset passed as the second argument, then read cnt
3096** bytes into pBuf. Return the number of bytes actually read.
3097**
3098** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3099** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3100** one system to another. Since SQLite does not define USE_PREAD
3101** any any form by default, we will not attempt to define _XOPEN_SOURCE.
3102** See tickets #2741 and #2681.
3103**
3104** To avoid stomping the errno value on a failed read the lastErrno value
3105** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003106*/
drh734c9862008-11-28 15:37:20 +00003107static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3108 int got;
drh58024642011-11-07 18:16:00 +00003109 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003110#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003111 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003112#endif
drh734c9862008-11-28 15:37:20 +00003113 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003114 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003115 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003116 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003117 do{
drh734c9862008-11-28 15:37:20 +00003118#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003119 got = osPread(id->h, pBuf, cnt, offset);
3120 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003121#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003122 got = osPread64(id->h, pBuf, cnt, offset);
3123 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003124#else
drh58024642011-11-07 18:16:00 +00003125 newOffset = lseek(id->h, offset, SEEK_SET);
3126 SimulateIOError( newOffset-- );
3127 if( newOffset!=offset ){
3128 if( newOffset == -1 ){
3129 ((unixFile*)id)->lastErrno = errno;
3130 }else{
drhf2f105d2012-08-20 15:53:54 +00003131 ((unixFile*)id)->lastErrno = 0;
drh58024642011-11-07 18:16:00 +00003132 }
3133 return -1;
drh734c9862008-11-28 15:37:20 +00003134 }
drh58024642011-11-07 18:16:00 +00003135 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003136#endif
drh58024642011-11-07 18:16:00 +00003137 if( got==cnt ) break;
3138 if( got<0 ){
3139 if( errno==EINTR ){ got = 1; continue; }
3140 prior = 0;
3141 ((unixFile*)id)->lastErrno = errno;
3142 break;
3143 }else if( got>0 ){
3144 cnt -= got;
3145 offset += got;
3146 prior += got;
3147 pBuf = (void*)(got + (char*)pBuf);
3148 }
3149 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003150 TIMER_END;
drh58024642011-11-07 18:16:00 +00003151 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3152 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3153 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003154}
3155
3156/*
drh734c9862008-11-28 15:37:20 +00003157** Read data from a file into a buffer. Return SQLITE_OK if all
3158** bytes were read successfully and SQLITE_IOERR if anything goes
3159** wrong.
drh339eb0b2008-03-07 15:34:11 +00003160*/
drh734c9862008-11-28 15:37:20 +00003161static int unixRead(
3162 sqlite3_file *id,
3163 void *pBuf,
3164 int amt,
3165 sqlite3_int64 offset
3166){
dan08da86a2009-08-21 17:18:03 +00003167 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003168 int got;
3169 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003170 assert( offset>=0 );
3171 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003172
dan08da86a2009-08-21 17:18:03 +00003173 /* If this is a database file (not a journal, master-journal or temp
3174 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003175#if 0
dane946c392009-08-22 11:39:46 +00003176 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003177 || offset>=PENDING_BYTE+512
3178 || offset+amt<=PENDING_BYTE
3179 );
dan7c246102010-04-12 19:00:29 +00003180#endif
drh08c6d442009-02-09 17:34:07 +00003181
drh9b4c59f2013-04-15 17:03:42 +00003182#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003183 /* Deal with as much of this read request as possible by transfering
3184 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003185 if( offset<pFile->mmapSize ){
3186 if( offset+amt <= pFile->mmapSize ){
3187 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3188 return SQLITE_OK;
3189 }else{
3190 int nCopy = pFile->mmapSize - offset;
3191 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3192 pBuf = &((u8 *)pBuf)[nCopy];
3193 amt -= nCopy;
3194 offset += nCopy;
3195 }
3196 }
drh6e0b6d52013-04-09 16:19:20 +00003197#endif
danf23da962013-03-23 21:00:41 +00003198
dan08da86a2009-08-21 17:18:03 +00003199 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003200 if( got==amt ){
3201 return SQLITE_OK;
3202 }else if( got<0 ){
3203 /* lastErrno set by seekAndRead */
3204 return SQLITE_IOERR_READ;
3205 }else{
dan08da86a2009-08-21 17:18:03 +00003206 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003207 /* Unread parts of the buffer must be zero-filled */
3208 memset(&((char*)pBuf)[got], 0, amt-got);
3209 return SQLITE_IOERR_SHORT_READ;
3210 }
3211}
3212
3213/*
dan47a2b4a2013-04-26 16:09:29 +00003214** Attempt to seek the file-descriptor passed as the first argument to
3215** absolute offset iOff, then attempt to write nBuf bytes of data from
3216** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3217** return the actual number of bytes written (which may be less than
3218** nBuf).
3219*/
3220static int seekAndWriteFd(
3221 int fd, /* File descriptor to write to */
3222 i64 iOff, /* File offset to begin writing at */
3223 const void *pBuf, /* Copy data from this buffer to the file */
3224 int nBuf, /* Size of buffer pBuf in bytes */
3225 int *piErrno /* OUT: Error number if error occurs */
3226){
3227 int rc = 0; /* Value returned by system call */
3228
3229 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003230 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003231 nBuf &= 0x1ffff;
3232 TIMER_START;
3233
3234#if defined(USE_PREAD)
3235 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
3236#elif defined(USE_PREAD64)
3237 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
3238#else
3239 do{
3240 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3241 SimulateIOError( iSeek-- );
3242
3243 if( iSeek!=iOff ){
3244 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3245 return -1;
3246 }
3247 rc = osWrite(fd, pBuf, nBuf);
3248 }while( rc<0 && errno==EINTR );
3249#endif
3250
3251 TIMER_END;
3252 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3253
3254 if( rc<0 && piErrno ) *piErrno = errno;
3255 return rc;
3256}
3257
3258
3259/*
drh734c9862008-11-28 15:37:20 +00003260** Seek to the offset in id->offset then read cnt bytes into pBuf.
3261** Return the number of bytes actually read. Update the offset.
3262**
3263** To avoid stomping the errno value on a failed write the lastErrno value
3264** is set before returning.
3265*/
3266static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003267 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003268}
3269
3270
3271/*
3272** Write data from a buffer into a file. Return SQLITE_OK on success
3273** or some other error code on failure.
3274*/
3275static int unixWrite(
3276 sqlite3_file *id,
3277 const void *pBuf,
3278 int amt,
3279 sqlite3_int64 offset
3280){
dan08da86a2009-08-21 17:18:03 +00003281 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003282 int wrote = 0;
3283 assert( id );
3284 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003285
dan08da86a2009-08-21 17:18:03 +00003286 /* If this is a database file (not a journal, master-journal or temp
3287 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003288#if 0
dane946c392009-08-22 11:39:46 +00003289 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003290 || offset>=PENDING_BYTE+512
3291 || offset+amt<=PENDING_BYTE
3292 );
dan7c246102010-04-12 19:00:29 +00003293#endif
drh08c6d442009-02-09 17:34:07 +00003294
drhd3d8c042012-05-29 17:02:40 +00003295#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003296 /* If we are doing a normal write to a database file (as opposed to
3297 ** doing a hot-journal rollback or a write to some file other than a
3298 ** normal database file) then record the fact that the database
3299 ** has changed. If the transaction counter is modified, record that
3300 ** fact too.
3301 */
dan08da86a2009-08-21 17:18:03 +00003302 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003303 pFile->dbUpdate = 1; /* The database has been modified */
3304 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003305 int rc;
drh8f941bc2009-01-14 23:03:40 +00003306 char oldCntr[4];
3307 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003308 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003309 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003310 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003311 pFile->transCntrChng = 1; /* The transaction counter has changed */
3312 }
3313 }
3314 }
3315#endif
3316
drh9b4c59f2013-04-15 17:03:42 +00003317#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003318 /* Deal with as much of this write request as possible by transfering
3319 ** data from the memory mapping using memcpy(). */
3320 if( offset<pFile->mmapSize ){
3321 if( offset+amt <= pFile->mmapSize ){
3322 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3323 return SQLITE_OK;
3324 }else{
3325 int nCopy = pFile->mmapSize - offset;
3326 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3327 pBuf = &((u8 *)pBuf)[nCopy];
3328 amt -= nCopy;
3329 offset += nCopy;
3330 }
3331 }
drh6e0b6d52013-04-09 16:19:20 +00003332#endif
danf23da962013-03-23 21:00:41 +00003333
dan08da86a2009-08-21 17:18:03 +00003334 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003335 amt -= wrote;
3336 offset += wrote;
3337 pBuf = &((char*)pBuf)[wrote];
3338 }
3339 SimulateIOError(( wrote=(-1), amt=1 ));
3340 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003341
drh734c9862008-11-28 15:37:20 +00003342 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003343 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003344 /* lastErrno set by seekAndWrite */
3345 return SQLITE_IOERR_WRITE;
3346 }else{
dan08da86a2009-08-21 17:18:03 +00003347 pFile->lastErrno = 0; /* not a system error */
drh734c9862008-11-28 15:37:20 +00003348 return SQLITE_FULL;
3349 }
3350 }
dan6e09d692010-07-27 18:34:15 +00003351
drh734c9862008-11-28 15:37:20 +00003352 return SQLITE_OK;
3353}
3354
3355#ifdef SQLITE_TEST
3356/*
3357** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003358** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003359*/
3360int sqlite3_sync_count = 0;
3361int sqlite3_fullsync_count = 0;
3362#endif
3363
3364/*
drh89240432009-03-25 01:06:01 +00003365** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003366** Others do no. To be safe, we will stick with the (slightly slower)
3367** fsync(). If you know that your system does support fdatasync() correctly,
drh89240432009-03-25 01:06:01 +00003368** then simply compile with -Dfdatasync=fdatasync
drh734c9862008-11-28 15:37:20 +00003369*/
drh20f8e132011-08-31 21:01:55 +00003370#if !defined(fdatasync)
drh734c9862008-11-28 15:37:20 +00003371# define fdatasync fsync
3372#endif
3373
3374/*
3375** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3376** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3377** only available on Mac OS X. But that could change.
3378*/
3379#ifdef F_FULLFSYNC
3380# define HAVE_FULLFSYNC 1
3381#else
3382# define HAVE_FULLFSYNC 0
3383#endif
3384
3385
3386/*
3387** The fsync() system call does not work as advertised on many
3388** unix systems. The following procedure is an attempt to make
3389** it work better.
3390**
3391** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3392** for testing when we want to run through the test suite quickly.
3393** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3394** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3395** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003396**
3397** SQLite sets the dataOnly flag if the size of the file is unchanged.
3398** The idea behind dataOnly is that it should only write the file content
3399** to disk, not the inode. We only set dataOnly if the file size is
3400** unchanged since the file size is part of the inode. However,
3401** Ted Ts'o tells us that fdatasync() will also write the inode if the
3402** file size has changed. The only real difference between fdatasync()
3403** and fsync(), Ted tells us, is that fdatasync() will not flush the
3404** inode if the mtime or owner or other inode attributes have changed.
3405** We only care about the file size, not the other file attributes, so
3406** as far as SQLite is concerned, an fdatasync() is always adequate.
3407** So, we always use fdatasync() if it is available, regardless of
3408** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003409*/
3410static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003411 int rc;
drh734c9862008-11-28 15:37:20 +00003412
3413 /* The following "ifdef/elif/else/" block has the same structure as
3414 ** the one below. It is replicated here solely to avoid cluttering
3415 ** up the real code with the UNUSED_PARAMETER() macros.
3416 */
3417#ifdef SQLITE_NO_SYNC
3418 UNUSED_PARAMETER(fd);
3419 UNUSED_PARAMETER(fullSync);
3420 UNUSED_PARAMETER(dataOnly);
3421#elif HAVE_FULLFSYNC
3422 UNUSED_PARAMETER(dataOnly);
3423#else
3424 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003425 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003426#endif
3427
3428 /* Record the number of times that we do a normal fsync() and
3429 ** FULLSYNC. This is used during testing to verify that this procedure
3430 ** gets called with the correct arguments.
3431 */
3432#ifdef SQLITE_TEST
3433 if( fullSync ) sqlite3_fullsync_count++;
3434 sqlite3_sync_count++;
3435#endif
3436
3437 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3438 ** no-op
3439 */
3440#ifdef SQLITE_NO_SYNC
3441 rc = SQLITE_OK;
3442#elif HAVE_FULLFSYNC
3443 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003444 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003445 }else{
3446 rc = 1;
3447 }
3448 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003449 ** It shouldn't be possible for fullfsync to fail on the local
3450 ** file system (on OSX), so failure indicates that FULLFSYNC
3451 ** isn't supported for this file system. So, attempt an fsync
3452 ** and (for now) ignore the overhead of a superfluous fcntl call.
3453 ** It'd be better to detect fullfsync support once and avoid
3454 ** the fcntl call every time sync is called.
3455 */
drh734c9862008-11-28 15:37:20 +00003456 if( rc ) rc = fsync(fd);
3457
drh7ed97b92010-01-20 13:07:21 +00003458#elif defined(__APPLE__)
3459 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3460 ** so currently we default to the macro that redefines fdatasync to fsync
3461 */
3462 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003463#else
drh0b647ff2009-03-21 14:41:04 +00003464 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003465#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003466 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003467 rc = fsync(fd);
3468 }
drh0b647ff2009-03-21 14:41:04 +00003469#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003470#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3471
3472 if( OS_VXWORKS && rc!= -1 ){
3473 rc = 0;
3474 }
chw97185482008-11-17 08:05:31 +00003475 return rc;
drhbfe66312006-10-03 17:40:40 +00003476}
3477
drh734c9862008-11-28 15:37:20 +00003478/*
drh0059eae2011-08-08 23:48:40 +00003479** Open a file descriptor to the directory containing file zFilename.
3480** If successful, *pFd is set to the opened file descriptor and
3481** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3482** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3483** value.
3484**
drh90315a22011-08-10 01:52:12 +00003485** The directory file descriptor is used for only one thing - to
3486** fsync() a directory to make sure file creation and deletion events
3487** are flushed to disk. Such fsyncs are not needed on newer
3488** journaling filesystems, but are required on older filesystems.
3489**
3490** This routine can be overridden using the xSetSysCall interface.
3491** The ability to override this routine was added in support of the
3492** chromium sandbox. Opening a directory is a security risk (we are
3493** told) so making it overrideable allows the chromium sandbox to
3494** replace this routine with a harmless no-op. To make this routine
3495** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3496** *pFd set to a negative number.
3497**
drh0059eae2011-08-08 23:48:40 +00003498** If SQLITE_OK is returned, the caller is responsible for closing
3499** the file descriptor *pFd using close().
3500*/
3501static int openDirectory(const char *zFilename, int *pFd){
3502 int ii;
3503 int fd = -1;
3504 char zDirname[MAX_PATHNAME+1];
3505
3506 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3507 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3508 if( ii>0 ){
3509 zDirname[ii] = '\0';
3510 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3511 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003512 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3513 }
3514 }
3515 *pFd = fd;
3516 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3517}
3518
3519/*
drh734c9862008-11-28 15:37:20 +00003520** Make sure all writes to a particular file are committed to disk.
3521**
3522** If dataOnly==0 then both the file itself and its metadata (file
3523** size, access time, etc) are synced. If dataOnly!=0 then only the
3524** file data is synced.
3525**
3526** Under Unix, also make sure that the directory entry for the file
3527** has been created by fsync-ing the directory that contains the file.
3528** If we do not do this and we encounter a power failure, the directory
3529** entry for the journal might not exist after we reboot. The next
3530** SQLite to access the file will not know that the journal exists (because
3531** the directory entry for the journal was never created) and the transaction
3532** will not roll back - possibly leading to database corruption.
3533*/
3534static int unixSync(sqlite3_file *id, int flags){
3535 int rc;
3536 unixFile *pFile = (unixFile*)id;
3537
3538 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3539 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3540
3541 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3542 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3543 || (flags&0x0F)==SQLITE_SYNC_FULL
3544 );
3545
3546 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3547 ** line is to test that doing so does not cause any problems.
3548 */
3549 SimulateDiskfullError( return SQLITE_FULL );
3550
3551 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003552 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003553 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3554 SimulateIOError( rc=1 );
3555 if( rc ){
3556 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003557 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003558 }
drh0059eae2011-08-08 23:48:40 +00003559
3560 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003561 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003562 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003563 */
3564 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3565 int dirfd;
3566 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003567 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003568 rc = osOpenDirectory(pFile->zPath, &dirfd);
3569 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003570 full_fsync(dirfd, 0, 0);
3571 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003572 }else if( rc==SQLITE_CANTOPEN ){
3573 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003574 }
drh0059eae2011-08-08 23:48:40 +00003575 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003576 }
3577 return rc;
3578}
3579
3580/*
3581** Truncate an open file to a specified size
3582*/
3583static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003584 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003585 int rc;
dan6e09d692010-07-27 18:34:15 +00003586 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003587 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003588
3589 /* If the user has configured a chunk-size for this file, truncate the
3590 ** file so that it consists of an integer number of chunks (i.e. the
3591 ** actual file size after the operation may be larger than the requested
3592 ** size).
3593 */
drhb8af4b72012-04-05 20:04:39 +00003594 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003595 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3596 }
3597
drhff812312011-02-23 13:33:46 +00003598 rc = robust_ftruncate(pFile->h, (off_t)nByte);
drh734c9862008-11-28 15:37:20 +00003599 if( rc ){
dan6e09d692010-07-27 18:34:15 +00003600 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003601 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003602 }else{
drhd3d8c042012-05-29 17:02:40 +00003603#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003604 /* If we are doing a normal write to a database file (as opposed to
3605 ** doing a hot-journal rollback or a write to some file other than a
3606 ** normal database file) and we truncate the file to zero length,
3607 ** that effectively updates the change counter. This might happen
3608 ** when restoring a database using the backup API from a zero-length
3609 ** source.
3610 */
dan6e09d692010-07-27 18:34:15 +00003611 if( pFile->inNormalWrite && nByte==0 ){
3612 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003613 }
danf23da962013-03-23 21:00:41 +00003614#endif
danc0003312013-03-22 17:46:11 +00003615
mistachkine98844f2013-08-24 00:59:24 +00003616#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003617 /* If the file was just truncated to a size smaller than the currently
3618 ** mapped region, reduce the effective mapping size as well. SQLite will
3619 ** use read() and write() to access data beyond this point from now on.
3620 */
3621 if( nByte<pFile->mmapSize ){
3622 pFile->mmapSize = nByte;
3623 }
mistachkine98844f2013-08-24 00:59:24 +00003624#endif
drh3313b142009-11-06 04:13:18 +00003625
drh734c9862008-11-28 15:37:20 +00003626 return SQLITE_OK;
3627 }
3628}
3629
3630/*
3631** Determine the current size of a file in bytes
3632*/
3633static int unixFileSize(sqlite3_file *id, i64 *pSize){
3634 int rc;
3635 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003636 assert( id );
3637 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003638 SimulateIOError( rc=1 );
3639 if( rc!=0 ){
drh3044b512014-06-16 16:41:52 +00003640 ((unixFile*)id)->lastErrno = errno;
drh734c9862008-11-28 15:37:20 +00003641 return SQLITE_IOERR_FSTAT;
3642 }
3643 *pSize = buf.st_size;
3644
drh8af6c222010-05-14 12:43:01 +00003645 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003646 ** writes a single byte into that file in order to work around a bug
3647 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3648 ** layers, we need to report this file size as zero even though it is
3649 ** really 1. Ticket #3260.
3650 */
3651 if( *pSize==1 ) *pSize = 0;
3652
3653
3654 return SQLITE_OK;
3655}
3656
drhd2cb50b2009-01-09 21:41:17 +00003657#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003658/*
3659** Handler for proxy-locking file-control verbs. Defined below in the
3660** proxying locking division.
3661*/
3662static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003663#endif
drh715ff302008-12-03 22:32:44 +00003664
dan502019c2010-07-28 14:26:17 +00003665/*
3666** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003667** file-control operation. Enlarge the database to nBytes in size
3668** (rounded up to the next chunk-size). If the database is already
3669** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003670*/
3671static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003672 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003673 i64 nSize; /* Required file size */
3674 struct stat buf; /* Used to hold return values of fstat() */
3675
drh99ab3b12011-03-02 15:09:07 +00003676 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
dan502019c2010-07-28 14:26:17 +00003677
3678 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3679 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003680
dan502019c2010-07-28 14:26:17 +00003681#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003682 /* The code below is handling the return value of osFallocate()
3683 ** correctly. posix_fallocate() is defined to "returns zero on success,
3684 ** or an error number on failure". See the manpage for details. */
3685 int err;
drhff812312011-02-23 13:33:46 +00003686 do{
dan661d71a2011-03-30 19:08:03 +00003687 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3688 }while( err==EINTR );
3689 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003690#else
3691 /* If the OS does not have posix_fallocate(), fake it. First use
3692 ** ftruncate() to set the file size, then write a single byte to
3693 ** the last byte in each block within the extended region. This
3694 ** is the same technique used by glibc to implement posix_fallocate()
3695 ** on systems that do not have a real fallocate() system call.
3696 */
3697 int nBlk = buf.st_blksize; /* File-system block size */
3698 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003699
drhff812312011-02-23 13:33:46 +00003700 if( robust_ftruncate(pFile->h, nSize) ){
dan502019c2010-07-28 14:26:17 +00003701 pFile->lastErrno = errno;
dane18d4952011-02-21 11:46:24 +00003702 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
dan502019c2010-07-28 14:26:17 +00003703 }
3704 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dandc5df0f2011-04-06 19:15:45 +00003705 while( iWrite<nSize ){
3706 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
3707 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003708 iWrite += nBlk;
dandc5df0f2011-04-06 19:15:45 +00003709 }
dan502019c2010-07-28 14:26:17 +00003710#endif
3711 }
3712 }
3713
mistachkine98844f2013-08-24 00:59:24 +00003714#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003715 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003716 int rc;
3717 if( pFile->szChunk<=0 ){
3718 if( robust_ftruncate(pFile->h, nByte) ){
3719 pFile->lastErrno = errno;
3720 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3721 }
3722 }
3723
3724 rc = unixMapfile(pFile, nByte);
3725 return rc;
3726 }
mistachkine98844f2013-08-24 00:59:24 +00003727#endif
danf23da962013-03-23 21:00:41 +00003728
dan502019c2010-07-28 14:26:17 +00003729 return SQLITE_OK;
3730}
danielk1977ad94b582007-08-20 06:44:22 +00003731
danielk1977e3026632004-06-22 11:29:02 +00003732/*
drhf12b3f62011-12-21 14:42:29 +00003733** If *pArg is inititially negative then this is a query. Set *pArg to
3734** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3735**
3736** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3737*/
3738static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3739 if( *pArg<0 ){
3740 *pArg = (pFile->ctrlFlags & mask)!=0;
3741 }else if( (*pArg)==0 ){
3742 pFile->ctrlFlags &= ~mask;
3743 }else{
3744 pFile->ctrlFlags |= mask;
3745 }
3746}
3747
drh696b33e2012-12-06 19:01:42 +00003748/* Forward declaration */
3749static int unixGetTempname(int nBuf, char *zBuf);
3750
drhf12b3f62011-12-21 14:42:29 +00003751/*
drh9e33c2c2007-08-31 18:34:59 +00003752** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003753*/
drhcc6bb3e2007-08-31 16:11:35 +00003754static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003755 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003756 switch( op ){
3757 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003758 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003759 return SQLITE_OK;
3760 }
drh7708e972008-11-29 00:56:52 +00003761 case SQLITE_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003762 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003763 return SQLITE_OK;
3764 }
dan6e09d692010-07-27 18:34:15 +00003765 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003766 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003767 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003768 }
drh9ff27ec2010-05-19 19:26:05 +00003769 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003770 int rc;
3771 SimulateIOErrorBenign(1);
3772 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3773 SimulateIOErrorBenign(0);
3774 return rc;
drhf0b190d2011-07-26 16:03:07 +00003775 }
3776 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003777 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3778 return SQLITE_OK;
3779 }
drhcb15f352011-12-23 01:04:17 +00003780 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3781 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003782 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003783 }
drhde60fc22011-12-14 17:53:36 +00003784 case SQLITE_FCNTL_VFSNAME: {
3785 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3786 return SQLITE_OK;
3787 }
drh696b33e2012-12-06 19:01:42 +00003788 case SQLITE_FCNTL_TEMPFILENAME: {
3789 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3790 if( zTFile ){
3791 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3792 *(char**)pArg = zTFile;
3793 }
3794 return SQLITE_OK;
3795 }
drhb959a012013-12-07 12:29:22 +00003796 case SQLITE_FCNTL_HAS_MOVED: {
3797 *(int*)pArg = fileHasMoved(pFile);
3798 return SQLITE_OK;
3799 }
mistachkine98844f2013-08-24 00:59:24 +00003800#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003801 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003802 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003803 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003804 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3805 newLimit = sqlite3GlobalConfig.mxMmap;
3806 }
3807 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003808 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003809 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003810 if( pFile->mmapSize>0 ){
3811 unixUnmapfile(pFile);
3812 rc = unixMapfile(pFile, -1);
3813 }
danbcb8a862013-04-08 15:30:41 +00003814 }
drh34e258c2013-05-23 01:40:53 +00003815 return rc;
danb2d3de32013-03-14 18:34:37 +00003816 }
mistachkine98844f2013-08-24 00:59:24 +00003817#endif
drhd3d8c042012-05-29 17:02:40 +00003818#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003819 /* The pager calls this method to signal that it has done
3820 ** a rollback and that the database is therefore unchanged and
3821 ** it hence it is OK for the transaction change counter to be
3822 ** unchanged.
3823 */
3824 case SQLITE_FCNTL_DB_UNCHANGED: {
3825 ((unixFile*)id)->dbUpdate = 0;
3826 return SQLITE_OK;
3827 }
3828#endif
drhd2cb50b2009-01-09 21:41:17 +00003829#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003830 case SQLITE_SET_LOCKPROXYFILE:
aswiftaebf4132008-11-21 00:10:35 +00003831 case SQLITE_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003832 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003833 }
drhd2cb50b2009-01-09 21:41:17 +00003834#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003835 }
drh0b52b7d2011-01-26 19:46:22 +00003836 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003837}
3838
3839/*
danielk1977a3d4c882007-03-23 10:08:38 +00003840** Return the sector size in bytes of the underlying block device for
3841** the specified file. This is almost always 512 bytes, but may be
3842** larger for some devices.
3843**
3844** SQLite code assumes this function cannot fail. It also assumes that
3845** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003846** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003847** same for both.
3848*/
drh537dddf2012-10-26 13:46:24 +00003849#ifndef __QNXNTO__
3850static int unixSectorSize(sqlite3_file *NotUsed){
3851 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003852 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003853}
drh537dddf2012-10-26 13:46:24 +00003854#endif
3855
3856/*
3857** The following version of unixSectorSize() is optimized for QNX.
3858*/
3859#ifdef __QNXNTO__
3860#include <sys/dcmd_blk.h>
3861#include <sys/statvfs.h>
3862static int unixSectorSize(sqlite3_file *id){
3863 unixFile *pFile = (unixFile*)id;
3864 if( pFile->sectorSize == 0 ){
3865 struct statvfs fsInfo;
3866
3867 /* Set defaults for non-supported filesystems */
3868 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3869 pFile->deviceCharacteristics = 0;
3870 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3871 return pFile->sectorSize;
3872 }
3873
3874 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3875 pFile->sectorSize = fsInfo.f_bsize;
3876 pFile->deviceCharacteristics =
3877 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3878 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3879 ** the write succeeds */
3880 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3881 ** so it is ordered */
3882 0;
3883 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3884 pFile->sectorSize = fsInfo.f_bsize;
3885 pFile->deviceCharacteristics =
3886 /* etfs cluster size writes are atomic */
3887 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3888 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3889 ** the write succeeds */
3890 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3891 ** so it is ordered */
3892 0;
3893 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3894 pFile->sectorSize = fsInfo.f_bsize;
3895 pFile->deviceCharacteristics =
3896 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3897 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3898 ** the write succeeds */
3899 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3900 ** so it is ordered */
3901 0;
3902 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3903 pFile->sectorSize = fsInfo.f_bsize;
3904 pFile->deviceCharacteristics =
3905 /* full bitset of atomics from max sector size and smaller */
3906 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3907 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3908 ** so it is ordered */
3909 0;
3910 }else if( strstr(fsInfo.f_basetype, "dos") ){
3911 pFile->sectorSize = fsInfo.f_bsize;
3912 pFile->deviceCharacteristics =
3913 /* full bitset of atomics from max sector size and smaller */
3914 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3915 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3916 ** so it is ordered */
3917 0;
3918 }else{
3919 pFile->deviceCharacteristics =
3920 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3921 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3922 ** the write succeeds */
3923 0;
3924 }
3925 }
3926 /* Last chance verification. If the sector size isn't a multiple of 512
3927 ** then it isn't valid.*/
3928 if( pFile->sectorSize % 512 != 0 ){
3929 pFile->deviceCharacteristics = 0;
3930 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3931 }
3932 return pFile->sectorSize;
3933}
3934#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003935
danielk197790949c22007-08-17 16:50:38 +00003936/*
drhf12b3f62011-12-21 14:42:29 +00003937** Return the device characteristics for the file.
3938**
drhcb15f352011-12-23 01:04:17 +00003939** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
3940** However, that choice is contraversial since technically the underlying
3941** file system does not always provide powersafe overwrites. (In other
3942** words, after a power-loss event, parts of the file that were never
3943** written might end up being altered.) However, non-PSOW behavior is very,
3944** very rare. And asserting PSOW makes a large reduction in the amount
3945** of required I/O for journaling, since a lot of padding is eliminated.
3946** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3947** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003948*/
drhf12b3f62011-12-21 14:42:29 +00003949static int unixDeviceCharacteristics(sqlite3_file *id){
3950 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003951 int rc = 0;
3952#ifdef __QNXNTO__
3953 if( p->sectorSize==0 ) unixSectorSize(id);
3954 rc = p->deviceCharacteristics;
3955#endif
drhcb15f352011-12-23 01:04:17 +00003956 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003957 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003958 }
drh537dddf2012-10-26 13:46:24 +00003959 return rc;
danielk197762079062007-08-15 17:08:46 +00003960}
3961
dan702eec12014-06-23 10:04:58 +00003962#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003963
dan702eec12014-06-23 10:04:58 +00003964/*
3965** Return the system page size.
3966**
3967** This function should not be called directly by other code in this file.
3968** Instead, it should be called via macro osGetpagesize().
3969*/
3970static int unixGetpagesize(void){
3971#if defined(_BSD_SOURCE)
3972 return getpagesize();
3973#else
3974 return (int)sysconf(_SC_PAGESIZE);
3975#endif
3976}
3977
3978#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3979
3980#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003981
3982/*
drhd91c68f2010-05-14 14:52:25 +00003983** Object used to represent an shared memory buffer.
3984**
3985** When multiple threads all reference the same wal-index, each thread
3986** has its own unixShm object, but they all point to a single instance
3987** of this unixShmNode object. In other words, each wal-index is opened
3988** only once per process.
3989**
3990** Each unixShmNode object is connected to a single unixInodeInfo object.
3991** We could coalesce this object into unixInodeInfo, but that would mean
3992** every open file that does not use shared memory (in other words, most
3993** open files) would have to carry around this extra information. So
3994** the unixInodeInfo object contains a pointer to this unixShmNode object
3995** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00003996**
3997** unixMutexHeld() must be true when creating or destroying
3998** this object or while reading or writing the following fields:
3999**
4000** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004001**
4002** The following fields are read-only after the object is created:
4003**
4004** fid
4005** zFilename
4006**
drhd91c68f2010-05-14 14:52:25 +00004007** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004008** unixMutexHeld() is true when reading or writing any other field
4009** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004010*/
drhd91c68f2010-05-14 14:52:25 +00004011struct unixShmNode {
4012 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004013 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004014 char *zFilename; /* Name of the mmapped file */
4015 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004016 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004017 u16 nRegion; /* Size of array apRegion */
4018 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004019 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004020 int nRef; /* Number of unixShm objects pointing to this */
4021 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004022#ifdef SQLITE_DEBUG
4023 u8 exclMask; /* Mask of exclusive locks held */
4024 u8 sharedMask; /* Mask of shared locks held */
4025 u8 nextShmId; /* Next available unixShm.id value */
4026#endif
4027};
4028
4029/*
drhd9e5c4f2010-05-12 18:01:39 +00004030** Structure used internally by this VFS to record the state of an
4031** open shared memory connection.
4032**
drhd91c68f2010-05-14 14:52:25 +00004033** The following fields are initialized when this object is created and
4034** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004035**
drhd91c68f2010-05-14 14:52:25 +00004036** unixShm.pFile
4037** unixShm.id
4038**
4039** All other fields are read/write. The unixShm.pFile->mutex must be held
4040** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004041*/
4042struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004043 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4044 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004045 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004046 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004047 u16 sharedMask; /* Mask of shared locks held */
4048 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004049};
4050
4051/*
drhd9e5c4f2010-05-12 18:01:39 +00004052** Constants used for locking
4053*/
drhbd9676c2010-06-23 17:58:38 +00004054#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004055#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004056
drhd9e5c4f2010-05-12 18:01:39 +00004057/*
drh73b64e42010-05-30 19:55:15 +00004058** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004059**
4060** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4061** otherwise.
4062*/
4063static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004064 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4065 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004066 int ofst, /* First byte of the locking range */
4067 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004068){
4069 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004070 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004071
drhd91c68f2010-05-14 14:52:25 +00004072 /* Access to the unixShmNode object is serialized by the caller */
4073 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004074
drh73b64e42010-05-30 19:55:15 +00004075 /* Shared locks never span more than one byte */
4076 assert( n==1 || lockType!=F_RDLCK );
4077
4078 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004079 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004080
drh3cb93392011-03-12 18:10:44 +00004081 if( pShmNode->h>=0 ){
4082 /* Initialize the locking parameters */
4083 memset(&f, 0, sizeof(f));
4084 f.l_type = lockType;
4085 f.l_whence = SEEK_SET;
4086 f.l_start = ofst;
4087 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004088
drh3cb93392011-03-12 18:10:44 +00004089 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4090 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4091 }
drhd9e5c4f2010-05-12 18:01:39 +00004092
4093 /* Update the global lock state and do debug tracing */
4094#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004095 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004096 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004097 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004098 if( rc==SQLITE_OK ){
4099 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004100 OSTRACE(("unlock %d ok", ofst));
4101 pShmNode->exclMask &= ~mask;
4102 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004103 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004104 OSTRACE(("read-lock %d ok", ofst));
4105 pShmNode->exclMask &= ~mask;
4106 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004107 }else{
4108 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004109 OSTRACE(("write-lock %d ok", ofst));
4110 pShmNode->exclMask |= mask;
4111 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004112 }
4113 }else{
4114 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004115 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004116 }else if( lockType==F_RDLCK ){
4117 OSTRACE(("read-lock failed"));
4118 }else{
4119 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004120 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004121 }
4122 }
drh20e1f082010-05-31 16:10:12 +00004123 OSTRACE((" - afterwards %03x,%03x\n",
4124 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004125 }
drhd9e5c4f2010-05-12 18:01:39 +00004126#endif
4127
4128 return rc;
4129}
4130
dan781e34c2014-03-20 08:59:47 +00004131/*
dan781e34c2014-03-20 08:59:47 +00004132** Return the minimum number of 32KB shm regions that should be mapped at
4133** a time, assuming that each mapping must be an integer multiple of the
4134** current system page-size.
4135**
4136** Usually, this is 1. The exception seems to be systems that are configured
4137** to use 64KB pages - in this case each mapping must cover at least two
4138** shm regions.
4139*/
4140static int unixShmRegionPerMap(void){
4141 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004142 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004143 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4144 if( pgsz<shmsz ) return 1;
4145 return pgsz/shmsz;
4146}
drhd9e5c4f2010-05-12 18:01:39 +00004147
4148/*
drhd91c68f2010-05-14 14:52:25 +00004149** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004150**
4151** This is not a VFS shared-memory method; it is a utility function called
4152** by VFS shared-memory methods.
4153*/
drhd91c68f2010-05-14 14:52:25 +00004154static void unixShmPurge(unixFile *pFd){
4155 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004156 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004157 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004158 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004159 int i;
drhd91c68f2010-05-14 14:52:25 +00004160 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004161 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004162 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004163 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004164 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004165 }else{
4166 sqlite3_free(p->apRegion[i]);
4167 }
dan13a3cb82010-06-11 19:04:21 +00004168 }
dan18801912010-06-14 14:07:50 +00004169 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004170 if( p->h>=0 ){
4171 robust_close(pFd, p->h, __LINE__);
4172 p->h = -1;
4173 }
drhd91c68f2010-05-14 14:52:25 +00004174 p->pInode->pShmNode = 0;
4175 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004176 }
4177}
4178
4179/*
danda9fe0c2010-07-13 18:44:03 +00004180** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004181** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004182**
drh7234c6d2010-06-19 15:10:09 +00004183** The file used to implement shared-memory is in the same directory
4184** as the open database file and has the same name as the open database
4185** file with the "-shm" suffix added. For example, if the database file
4186** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004187** for shared memory will be called "/home/user1/config.db-shm".
4188**
4189** Another approach to is to use files in /dev/shm or /dev/tmp or an
4190** some other tmpfs mount. But if a file in a different directory
4191** from the database file is used, then differing access permissions
4192** or a chroot() might cause two different processes on the same
4193** database to end up using different files for shared memory -
4194** meaning that their memory would not really be shared - resulting
4195** in database corruption. Nevertheless, this tmpfs file usage
4196** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4197** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4198** option results in an incompatible build of SQLite; builds of SQLite
4199** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4200** same database file at the same time, database corruption will likely
4201** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4202** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004203**
4204** When opening a new shared-memory file, if no other instances of that
4205** file are currently open, in this process or in other processes, then
4206** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004207**
4208** If the original database file (pDbFd) is using the "unix-excl" VFS
4209** that means that an exclusive lock is held on the database file and
4210** that no other processes are able to read or write the database. In
4211** that case, we do not really need shared memory. No shared memory
4212** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004213*/
danda9fe0c2010-07-13 18:44:03 +00004214static int unixOpenSharedMemory(unixFile *pDbFd){
4215 struct unixShm *p = 0; /* The connection to be opened */
4216 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4217 int rc; /* Result code */
4218 unixInodeInfo *pInode; /* The inode of fd */
4219 char *zShmFilename; /* Name of the file used for SHM */
4220 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004221
danda9fe0c2010-07-13 18:44:03 +00004222 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004223 p = sqlite3_malloc( sizeof(*p) );
4224 if( p==0 ) return SQLITE_NOMEM;
4225 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004226 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004227
danda9fe0c2010-07-13 18:44:03 +00004228 /* Check to see if a unixShmNode object already exists. Reuse an existing
4229 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004230 */
4231 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004232 pInode = pDbFd->pInode;
4233 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004234 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004235 struct stat sStat; /* fstat() info for database file */
4236
4237 /* Call fstat() to figure out the permissions on the database file. If
4238 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004239 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004240 */
drh3cb93392011-03-12 18:10:44 +00004241 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004242 rc = SQLITE_IOERR_FSTAT;
4243 goto shm_open_err;
4244 }
4245
drha4ced192010-07-15 18:32:40 +00004246#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004247 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004248#else
drh52bcde02012-01-03 14:50:45 +00004249 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
drha4ced192010-07-15 18:32:40 +00004250#endif
drh7234c6d2010-06-19 15:10:09 +00004251 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004252 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004253 rc = SQLITE_NOMEM;
4254 goto shm_open_err;
4255 }
drh9cb5a0d2012-01-05 21:19:54 +00004256 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004257 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004258#ifdef SQLITE_SHM_DIRECTORY
4259 sqlite3_snprintf(nShmFilename, zShmFilename,
4260 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4261 (u32)sStat.st_ino, (u32)sStat.st_dev);
4262#else
drh7234c6d2010-06-19 15:10:09 +00004263 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
drh81cc5162011-05-17 20:36:21 +00004264 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004265#endif
drhd91c68f2010-05-14 14:52:25 +00004266 pShmNode->h = -1;
4267 pDbFd->pInode->pShmNode = pShmNode;
4268 pShmNode->pInode = pDbFd->pInode;
4269 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4270 if( pShmNode->mutex==0 ){
4271 rc = SQLITE_NOMEM;
4272 goto shm_open_err;
4273 }
drhd9e5c4f2010-05-12 18:01:39 +00004274
drh3cb93392011-03-12 18:10:44 +00004275 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004276 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004277 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004278 openFlags = O_RDONLY;
4279 pShmNode->isReadonly = 1;
4280 }
4281 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004282 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004283 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4284 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004285 }
drhac7c3ac2012-02-11 19:23:48 +00004286
4287 /* If this process is running as root, make sure that the SHM file
4288 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004289 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004290 */
drhed466822012-05-31 13:10:49 +00004291 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004292
4293 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004294 ** If not, truncate the file to zero length.
4295 */
4296 rc = SQLITE_OK;
4297 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4298 if( robust_ftruncate(pShmNode->h, 0) ){
4299 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004300 }
4301 }
drh66dfec8b2011-06-01 20:01:49 +00004302 if( rc==SQLITE_OK ){
4303 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4304 }
4305 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004306 }
drhd9e5c4f2010-05-12 18:01:39 +00004307 }
4308
drhd91c68f2010-05-14 14:52:25 +00004309 /* Make the new connection a child of the unixShmNode */
4310 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004311#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004312 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004313#endif
drhd91c68f2010-05-14 14:52:25 +00004314 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004315 pDbFd->pShm = p;
4316 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004317
4318 /* The reference count on pShmNode has already been incremented under
4319 ** the cover of the unixEnterMutex() mutex and the pointer from the
4320 ** new (struct unixShm) object to the pShmNode has been set. All that is
4321 ** left to do is to link the new object into the linked list starting
4322 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4323 ** mutex.
4324 */
4325 sqlite3_mutex_enter(pShmNode->mutex);
4326 p->pNext = pShmNode->pFirst;
4327 pShmNode->pFirst = p;
4328 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004329 return SQLITE_OK;
4330
4331 /* Jump here on any error */
4332shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004333 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004334 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004335 unixLeaveMutex();
4336 return rc;
4337}
4338
4339/*
danda9fe0c2010-07-13 18:44:03 +00004340** This function is called to obtain a pointer to region iRegion of the
4341** shared-memory associated with the database file fd. Shared-memory regions
4342** are numbered starting from zero. Each shared-memory region is szRegion
4343** bytes in size.
4344**
4345** If an error occurs, an error code is returned and *pp is set to NULL.
4346**
4347** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4348** region has not been allocated (by any client, including one running in a
4349** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4350** bExtend is non-zero and the requested shared-memory region has not yet
4351** been allocated, it is allocated by this function.
4352**
4353** If the shared-memory region has already been allocated or is allocated by
4354** this call as described above, then it is mapped into this processes
4355** address space (if it is not already), *pp is set to point to the mapped
4356** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004357*/
danda9fe0c2010-07-13 18:44:03 +00004358static int unixShmMap(
4359 sqlite3_file *fd, /* Handle open on database file */
4360 int iRegion, /* Region to retrieve */
4361 int szRegion, /* Size of regions */
4362 int bExtend, /* True to extend file if necessary */
4363 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004364){
danda9fe0c2010-07-13 18:44:03 +00004365 unixFile *pDbFd = (unixFile*)fd;
4366 unixShm *p;
4367 unixShmNode *pShmNode;
4368 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004369 int nShmPerMap = unixShmRegionPerMap();
4370 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004371
danda9fe0c2010-07-13 18:44:03 +00004372 /* If the shared-memory file has not yet been opened, open it now. */
4373 if( pDbFd->pShm==0 ){
4374 rc = unixOpenSharedMemory(pDbFd);
4375 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004376 }
drhd9e5c4f2010-05-12 18:01:39 +00004377
danda9fe0c2010-07-13 18:44:03 +00004378 p = pDbFd->pShm;
4379 pShmNode = p->pShmNode;
4380 sqlite3_mutex_enter(pShmNode->mutex);
4381 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004382 assert( pShmNode->pInode==pDbFd->pInode );
4383 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4384 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004385
dan781e34c2014-03-20 08:59:47 +00004386 /* Minimum number of regions required to be mapped. */
4387 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4388
4389 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004390 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004391 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004392 struct stat sStat; /* Used by fstat() */
4393
4394 pShmNode->szRegion = szRegion;
4395
drh3cb93392011-03-12 18:10:44 +00004396 if( pShmNode->h>=0 ){
4397 /* The requested region is not mapped into this processes address space.
4398 ** Check to see if it has been allocated (i.e. if the wal-index file is
4399 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004400 */
drh3cb93392011-03-12 18:10:44 +00004401 if( osFstat(pShmNode->h, &sStat) ){
4402 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004403 goto shmpage_out;
4404 }
drh3cb93392011-03-12 18:10:44 +00004405
4406 if( sStat.st_size<nByte ){
4407 /* The requested memory region does not exist. If bExtend is set to
4408 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004409 */
dan47a2b4a2013-04-26 16:09:29 +00004410 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004411 goto shmpage_out;
4412 }
dan47a2b4a2013-04-26 16:09:29 +00004413
4414 /* Alternatively, if bExtend is true, extend the file. Do this by
4415 ** writing a single byte to the end of each (OS) page being
4416 ** allocated or extended. Technically, we need only write to the
4417 ** last page in order to extend the file. But writing to all new
4418 ** pages forces the OS to allocate them immediately, which reduces
4419 ** the chances of SIGBUS while accessing the mapped region later on.
4420 */
4421 else{
4422 static const int pgsz = 4096;
4423 int iPg;
4424
4425 /* Write to the last byte of each newly allocated or extended page */
4426 assert( (nByte % pgsz)==0 );
4427 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4428 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4429 const char *zFile = pShmNode->zFilename;
4430 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4431 goto shmpage_out;
4432 }
4433 }
drh3cb93392011-03-12 18:10:44 +00004434 }
4435 }
danda9fe0c2010-07-13 18:44:03 +00004436 }
4437
4438 /* Map the requested memory region into this processes address space. */
4439 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004440 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004441 );
4442 if( !apNew ){
4443 rc = SQLITE_IOERR_NOMEM;
4444 goto shmpage_out;
4445 }
4446 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004447 while( pShmNode->nRegion<nReqRegion ){
4448 int nMap = szRegion*nShmPerMap;
4449 int i;
drh3cb93392011-03-12 18:10:44 +00004450 void *pMem;
4451 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004452 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004453 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004454 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004455 );
4456 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004457 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004458 goto shmpage_out;
4459 }
4460 }else{
4461 pMem = sqlite3_malloc(szRegion);
4462 if( pMem==0 ){
4463 rc = SQLITE_NOMEM;
4464 goto shmpage_out;
4465 }
4466 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004467 }
dan781e34c2014-03-20 08:59:47 +00004468
4469 for(i=0; i<nShmPerMap; i++){
4470 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4471 }
4472 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004473 }
4474 }
4475
4476shmpage_out:
4477 if( pShmNode->nRegion>iRegion ){
4478 *pp = pShmNode->apRegion[iRegion];
4479 }else{
4480 *pp = 0;
4481 }
drh66dfec8b2011-06-01 20:01:49 +00004482 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004483 sqlite3_mutex_leave(pShmNode->mutex);
4484 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004485}
4486
4487/*
drhd9e5c4f2010-05-12 18:01:39 +00004488** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004489**
4490** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4491** different here than in posix. In xShmLock(), one can go from unlocked
4492** to shared and back or from unlocked to exclusive and back. But one may
4493** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004494*/
4495static int unixShmLock(
4496 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004497 int ofst, /* First lock to acquire or release */
4498 int n, /* Number of locks to acquire or release */
4499 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004500){
drh73b64e42010-05-30 19:55:15 +00004501 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4502 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4503 unixShm *pX; /* For looping over all siblings */
4504 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4505 int rc = SQLITE_OK; /* Result code */
4506 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004507
drhd91c68f2010-05-14 14:52:25 +00004508 assert( pShmNode==pDbFd->pInode->pShmNode );
4509 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004510 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004511 assert( n>=1 );
4512 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4513 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4514 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4515 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4516 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004517 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4518 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004519
drhc99597c2010-05-31 01:41:15 +00004520 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004521 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004522 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004523 if( flags & SQLITE_SHM_UNLOCK ){
4524 u16 allMask = 0; /* Mask of locks held by siblings */
4525
4526 /* See if any siblings hold this same lock */
4527 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4528 if( pX==p ) continue;
4529 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4530 allMask |= pX->sharedMask;
4531 }
4532
4533 /* Unlock the system-level locks */
4534 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004535 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004536 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004537 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004538 }
drh73b64e42010-05-30 19:55:15 +00004539
4540 /* Undo the local locks */
4541 if( rc==SQLITE_OK ){
4542 p->exclMask &= ~mask;
4543 p->sharedMask &= ~mask;
4544 }
4545 }else if( flags & SQLITE_SHM_SHARED ){
4546 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4547
4548 /* Find out which shared locks are already held by sibling connections.
4549 ** If any sibling already holds an exclusive lock, go ahead and return
4550 ** SQLITE_BUSY.
4551 */
4552 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004553 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004554 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004555 break;
4556 }
4557 allShared |= pX->sharedMask;
4558 }
4559
4560 /* Get shared locks at the system level, if necessary */
4561 if( rc==SQLITE_OK ){
4562 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004563 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004564 }else{
drh73b64e42010-05-30 19:55:15 +00004565 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004566 }
drhd9e5c4f2010-05-12 18:01:39 +00004567 }
drh73b64e42010-05-30 19:55:15 +00004568
4569 /* Get the local shared locks */
4570 if( rc==SQLITE_OK ){
4571 p->sharedMask |= mask;
4572 }
4573 }else{
4574 /* Make sure no sibling connections hold locks that will block this
4575 ** lock. If any do, return SQLITE_BUSY right away.
4576 */
4577 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004578 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4579 rc = SQLITE_BUSY;
4580 break;
4581 }
4582 }
4583
4584 /* Get the exclusive locks at the system level. Then if successful
4585 ** also mark the local connection as being locked.
4586 */
4587 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004588 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004589 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004590 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004591 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004592 }
drhd9e5c4f2010-05-12 18:01:39 +00004593 }
4594 }
drhd91c68f2010-05-14 14:52:25 +00004595 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004596 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
4597 p->id, getpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004598 return rc;
4599}
4600
drh286a2882010-05-20 23:51:06 +00004601/*
4602** Implement a memory barrier or memory fence on shared memory.
4603**
4604** All loads and stores begun before the barrier must complete before
4605** any load or store begun after the barrier.
4606*/
4607static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004608 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004609){
drhff828942010-06-26 21:34:06 +00004610 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004611 unixEnterMutex();
4612 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004613}
4614
dan18801912010-06-14 14:07:50 +00004615/*
danda9fe0c2010-07-13 18:44:03 +00004616** Close a connection to shared-memory. Delete the underlying
4617** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004618**
4619** If there is no shared memory associated with the connection then this
4620** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004621*/
danda9fe0c2010-07-13 18:44:03 +00004622static int unixShmUnmap(
4623 sqlite3_file *fd, /* The underlying database file */
4624 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004625){
danda9fe0c2010-07-13 18:44:03 +00004626 unixShm *p; /* The connection to be closed */
4627 unixShmNode *pShmNode; /* The underlying shared-memory file */
4628 unixShm **pp; /* For looping over sibling connections */
4629 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004630
danda9fe0c2010-07-13 18:44:03 +00004631 pDbFd = (unixFile*)fd;
4632 p = pDbFd->pShm;
4633 if( p==0 ) return SQLITE_OK;
4634 pShmNode = p->pShmNode;
4635
4636 assert( pShmNode==pDbFd->pInode->pShmNode );
4637 assert( pShmNode->pInode==pDbFd->pInode );
4638
4639 /* Remove connection p from the set of connections associated
4640 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004641 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004642 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4643 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004644
danda9fe0c2010-07-13 18:44:03 +00004645 /* Free the connection p */
4646 sqlite3_free(p);
4647 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004648 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004649
4650 /* If pShmNode->nRef has reached 0, then close the underlying
4651 ** shared-memory file, too */
4652 unixEnterMutex();
4653 assert( pShmNode->nRef>0 );
4654 pShmNode->nRef--;
4655 if( pShmNode->nRef==0 ){
drh036ac7f2011-08-08 23:18:05 +00004656 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
danda9fe0c2010-07-13 18:44:03 +00004657 unixShmPurge(pDbFd);
4658 }
4659 unixLeaveMutex();
4660
4661 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004662}
drh286a2882010-05-20 23:51:06 +00004663
danda9fe0c2010-07-13 18:44:03 +00004664
drhd9e5c4f2010-05-12 18:01:39 +00004665#else
drh6b017cc2010-06-14 18:01:46 +00004666# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004667# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004668# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004669# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004670#endif /* #ifndef SQLITE_OMIT_WAL */
4671
mistachkine98844f2013-08-24 00:59:24 +00004672#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004673/*
danaef49d72013-03-25 16:28:54 +00004674** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004675*/
danf23da962013-03-23 21:00:41 +00004676static void unixUnmapfile(unixFile *pFd){
4677 assert( pFd->nFetchOut==0 );
4678 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004679 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004680 pFd->pMapRegion = 0;
4681 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004682 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004683 }
4684}
dan5d8a1372013-03-19 19:28:06 +00004685
danaef49d72013-03-25 16:28:54 +00004686/*
dane6ecd662013-04-01 17:56:59 +00004687** Attempt to set the size of the memory mapping maintained by file
4688** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4689**
4690** If successful, this function sets the following variables:
4691**
4692** unixFile.pMapRegion
4693** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004694** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004695**
4696** If unsuccessful, an error message is logged via sqlite3_log() and
4697** the three variables above are zeroed. In this case SQLite should
4698** continue accessing the database using the xRead() and xWrite()
4699** methods.
4700*/
4701static void unixRemapfile(
4702 unixFile *pFd, /* File descriptor object */
4703 i64 nNew /* Required mapping size */
4704){
dan4ff7bc42013-04-02 12:04:09 +00004705 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004706 int h = pFd->h; /* File descriptor open on db file */
4707 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004708 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004709 u8 *pNew = 0; /* Location of new mapping */
4710 int flags = PROT_READ; /* Flags to pass to mmap() */
4711
4712 assert( pFd->nFetchOut==0 );
4713 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004714 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004715 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004716 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004717 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004718
4719 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4720
4721 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004722#if HAVE_MREMAP
4723 i64 nReuse = pFd->mmapSize;
4724#else
danbc760632014-03-20 09:42:09 +00004725 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004726 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004727#endif
dane6ecd662013-04-01 17:56:59 +00004728 u8 *pReq = &pOrig[nReuse];
4729
4730 /* Unmap any pages of the existing mapping that cannot be reused. */
4731 if( nReuse!=nOrig ){
4732 osMunmap(pReq, nOrig-nReuse);
4733 }
4734
4735#if HAVE_MREMAP
4736 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004737 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004738#else
4739 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4740 if( pNew!=MAP_FAILED ){
4741 if( pNew!=pReq ){
4742 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004743 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004744 }else{
4745 pNew = pOrig;
4746 }
4747 }
4748#endif
4749
dan48ccef82013-04-02 20:55:01 +00004750 /* The attempt to extend the existing mapping failed. Free it. */
4751 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004752 osMunmap(pOrig, nReuse);
4753 }
4754 }
4755
4756 /* If pNew is still NULL, try to create an entirely new mapping. */
4757 if( pNew==0 ){
4758 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004759 }
4760
dan4ff7bc42013-04-02 12:04:09 +00004761 if( pNew==MAP_FAILED ){
4762 pNew = 0;
4763 nNew = 0;
4764 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4765
4766 /* If the mmap() above failed, assume that all subsequent mmap() calls
4767 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4768 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004769 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004770 }
dane6ecd662013-04-01 17:56:59 +00004771 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004772 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004773}
4774
4775/*
danaef49d72013-03-25 16:28:54 +00004776** Memory map or remap the file opened by file-descriptor pFd (if the file
4777** is already mapped, the existing mapping is replaced by the new). Or, if
4778** there already exists a mapping for this file, and there are still
4779** outstanding xFetch() references to it, this function is a no-op.
4780**
4781** If parameter nByte is non-negative, then it is the requested size of
4782** the mapping to create. Otherwise, if nByte is less than zero, then the
4783** requested size is the size of the file on disk. The actual size of the
4784** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004785** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004786**
4787** SQLITE_OK is returned if no error occurs (even if the mapping is not
4788** recreated as a result of outstanding references) or an SQLite error
4789** code otherwise.
4790*/
danf23da962013-03-23 21:00:41 +00004791static int unixMapfile(unixFile *pFd, i64 nByte){
4792 i64 nMap = nByte;
4793 int rc;
daneb97b292013-03-20 14:26:59 +00004794
danf23da962013-03-23 21:00:41 +00004795 assert( nMap>=0 || pFd->nFetchOut==0 );
4796 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4797
4798 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004799 struct stat statbuf; /* Low-level file information */
4800 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004801 if( rc!=SQLITE_OK ){
4802 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004803 }
drh3044b512014-06-16 16:41:52 +00004804 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004805 }
drh9b4c59f2013-04-15 17:03:42 +00004806 if( nMap>pFd->mmapSizeMax ){
4807 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004808 }
4809
danf23da962013-03-23 21:00:41 +00004810 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004811 if( nMap>0 ){
4812 unixRemapfile(pFd, nMap);
4813 }else{
danb7e3a322013-03-25 20:30:13 +00004814 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004815 }
4816 }
4817
danf23da962013-03-23 21:00:41 +00004818 return SQLITE_OK;
4819}
mistachkine98844f2013-08-24 00:59:24 +00004820#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004821
danaef49d72013-03-25 16:28:54 +00004822/*
4823** If possible, return a pointer to a mapping of file fd starting at offset
4824** iOff. The mapping must be valid for at least nAmt bytes.
4825**
4826** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4827** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4828** Finally, if an error does occur, return an SQLite error code. The final
4829** value of *pp is undefined in this case.
4830**
4831** If this function does return a pointer, the caller must eventually
4832** release the reference by calling unixUnfetch().
4833*/
danf23da962013-03-23 21:00:41 +00004834static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004835#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004836 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004837#endif
danf23da962013-03-23 21:00:41 +00004838 *pp = 0;
4839
drh9b4c59f2013-04-15 17:03:42 +00004840#if SQLITE_MAX_MMAP_SIZE>0
4841 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004842 if( pFd->pMapRegion==0 ){
4843 int rc = unixMapfile(pFd, -1);
4844 if( rc!=SQLITE_OK ) return rc;
4845 }
4846 if( pFd->mmapSize >= iOff+nAmt ){
4847 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4848 pFd->nFetchOut++;
4849 }
4850 }
drh6e0b6d52013-04-09 16:19:20 +00004851#endif
danf23da962013-03-23 21:00:41 +00004852 return SQLITE_OK;
4853}
4854
danaef49d72013-03-25 16:28:54 +00004855/*
dandf737fe2013-03-25 17:00:24 +00004856** If the third argument is non-NULL, then this function releases a
4857** reference obtained by an earlier call to unixFetch(). The second
4858** argument passed to this function must be the same as the corresponding
4859** argument that was passed to the unixFetch() invocation.
4860**
4861** Or, if the third argument is NULL, then this function is being called
4862** to inform the VFS layer that, according to POSIX, any existing mapping
4863** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004864*/
dandf737fe2013-03-25 17:00:24 +00004865static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004866#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004867 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004868 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004869
danaef49d72013-03-25 16:28:54 +00004870 /* If p==0 (unmap the entire file) then there must be no outstanding
4871 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4872 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004873 assert( (p==0)==(pFd->nFetchOut==0) );
4874
dandf737fe2013-03-25 17:00:24 +00004875 /* If p!=0, it must match the iOff value. */
4876 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4877
danf23da962013-03-23 21:00:41 +00004878 if( p ){
4879 pFd->nFetchOut--;
4880 }else{
4881 unixUnmapfile(pFd);
4882 }
4883
4884 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004885#else
4886 UNUSED_PARAMETER(fd);
4887 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004888 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004889#endif
danf23da962013-03-23 21:00:41 +00004890 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004891}
4892
4893/*
drh734c9862008-11-28 15:37:20 +00004894** Here ends the implementation of all sqlite3_file methods.
4895**
4896********************** End sqlite3_file Methods *******************************
4897******************************************************************************/
4898
4899/*
drh6b9d6dd2008-12-03 19:34:47 +00004900** This division contains definitions of sqlite3_io_methods objects that
4901** implement various file locking strategies. It also contains definitions
4902** of "finder" functions. A finder-function is used to locate the appropriate
4903** sqlite3_io_methods object for a particular database file. The pAppData
4904** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4905** the correct finder-function for that VFS.
4906**
4907** Most finder functions return a pointer to a fixed sqlite3_io_methods
4908** object. The only interesting finder-function is autolockIoFinder, which
4909** looks at the filesystem type and tries to guess the best locking
4910** strategy from that.
4911**
drh1875f7a2008-12-08 18:19:17 +00004912** For finder-funtion F, two objects are created:
4913**
4914** (1) The real finder-function named "FImpt()".
4915**
dane946c392009-08-22 11:39:46 +00004916** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004917**
4918**
4919** A pointer to the F pointer is used as the pAppData value for VFS
4920** objects. We have to do this instead of letting pAppData point
4921** directly at the finder-function since C90 rules prevent a void*
4922** from be cast into a function pointer.
4923**
drh6b9d6dd2008-12-03 19:34:47 +00004924**
drh7708e972008-11-29 00:56:52 +00004925** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004926**
drh7708e972008-11-29 00:56:52 +00004927** * A constant sqlite3_io_methods object call METHOD that has locking
4928** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4929**
4930** * An I/O method finder function called FINDER that returns a pointer
4931** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004932*/
drhd9e5c4f2010-05-12 18:01:39 +00004933#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
drh7708e972008-11-29 00:56:52 +00004934static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004935 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004936 CLOSE, /* xClose */ \
4937 unixRead, /* xRead */ \
4938 unixWrite, /* xWrite */ \
4939 unixTruncate, /* xTruncate */ \
4940 unixSync, /* xSync */ \
4941 unixFileSize, /* xFileSize */ \
4942 LOCK, /* xLock */ \
4943 UNLOCK, /* xUnlock */ \
4944 CKLOCK, /* xCheckReservedLock */ \
4945 unixFileControl, /* xFileControl */ \
4946 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004947 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drh6b017cc2010-06-14 18:01:46 +00004948 unixShmMap, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004949 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004950 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004951 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004952 unixFetch, /* xFetch */ \
4953 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004954}; \
drh0c2694b2009-09-03 16:23:44 +00004955static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4956 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004957 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004958} \
drh0c2694b2009-09-03 16:23:44 +00004959static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004960 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004961
4962/*
4963** Here are all of the sqlite3_io_methods objects for each of the
4964** locking strategies. Functions that return pointers to these methods
4965** are also created.
4966*/
4967IOMETHODS(
4968 posixIoFinder, /* Finder function name */
4969 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004970 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004971 unixClose, /* xClose method */
4972 unixLock, /* xLock method */
4973 unixUnlock, /* xUnlock method */
4974 unixCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004975)
drh7708e972008-11-29 00:56:52 +00004976IOMETHODS(
4977 nolockIoFinder, /* Finder function name */
4978 nolockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004979 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004980 nolockClose, /* xClose method */
4981 nolockLock, /* xLock method */
4982 nolockUnlock, /* xUnlock method */
4983 nolockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004984)
drh7708e972008-11-29 00:56:52 +00004985IOMETHODS(
4986 dotlockIoFinder, /* Finder function name */
4987 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004988 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004989 dotlockClose, /* xClose method */
4990 dotlockLock, /* xLock method */
4991 dotlockUnlock, /* xUnlock method */
4992 dotlockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00004993)
drh7708e972008-11-29 00:56:52 +00004994
chw78a13182009-04-07 05:35:03 +00004995#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00004996IOMETHODS(
4997 flockIoFinder, /* Finder function name */
4998 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00004999 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005000 flockClose, /* xClose method */
5001 flockLock, /* xLock method */
5002 flockUnlock, /* xUnlock method */
5003 flockCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005004)
drh7708e972008-11-29 00:56:52 +00005005#endif
5006
drh6c7d5c52008-11-21 20:32:33 +00005007#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005008IOMETHODS(
5009 semIoFinder, /* Finder function name */
5010 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005011 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005012 semClose, /* xClose method */
5013 semLock, /* xLock method */
5014 semUnlock, /* xUnlock method */
5015 semCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005016)
aswiftaebf4132008-11-21 00:10:35 +00005017#endif
drh7708e972008-11-29 00:56:52 +00005018
drhd2cb50b2009-01-09 21:41:17 +00005019#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005020IOMETHODS(
5021 afpIoFinder, /* Finder function name */
5022 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005023 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005024 afpClose, /* xClose method */
5025 afpLock, /* xLock method */
5026 afpUnlock, /* xUnlock method */
5027 afpCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005028)
drh715ff302008-12-03 22:32:44 +00005029#endif
5030
5031/*
5032** The proxy locking method is a "super-method" in the sense that it
5033** opens secondary file descriptors for the conch and lock files and
5034** it uses proxy, dot-file, AFP, and flock() locking methods on those
5035** secondary files. For this reason, the division that implements
5036** proxy locking is located much further down in the file. But we need
5037** to go ahead and define the sqlite3_io_methods and finder function
5038** for proxy locking here. So we forward declare the I/O methods.
5039*/
drhd2cb50b2009-01-09 21:41:17 +00005040#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005041static int proxyClose(sqlite3_file*);
5042static int proxyLock(sqlite3_file*, int);
5043static int proxyUnlock(sqlite3_file*, int);
5044static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005045IOMETHODS(
5046 proxyIoFinder, /* Finder function name */
5047 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005048 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005049 proxyClose, /* xClose method */
5050 proxyLock, /* xLock method */
5051 proxyUnlock, /* xUnlock method */
5052 proxyCheckReservedLock /* xCheckReservedLock method */
drh1875f7a2008-12-08 18:19:17 +00005053)
aswiftaebf4132008-11-21 00:10:35 +00005054#endif
drh7708e972008-11-29 00:56:52 +00005055
drh7ed97b92010-01-20 13:07:21 +00005056/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5057#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5058IOMETHODS(
5059 nfsIoFinder, /* Finder function name */
5060 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005061 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005062 unixClose, /* xClose method */
5063 unixLock, /* xLock method */
5064 nfsUnlock, /* xUnlock method */
5065 unixCheckReservedLock /* xCheckReservedLock method */
5066)
5067#endif
drh7708e972008-11-29 00:56:52 +00005068
drhd2cb50b2009-01-09 21:41:17 +00005069#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005070/*
drh6b9d6dd2008-12-03 19:34:47 +00005071** This "finder" function attempts to determine the best locking strategy
5072** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005073** object that implements that strategy.
5074**
5075** This is for MacOSX only.
5076*/
drh1875f7a2008-12-08 18:19:17 +00005077static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005078 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005079 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005080){
5081 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005082 const char *zFilesystem; /* Filesystem type name */
5083 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005084 } aMap[] = {
5085 { "hfs", &posixIoMethods },
5086 { "ufs", &posixIoMethods },
5087 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005088 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005089 { "webdav", &nolockIoMethods },
5090 { 0, 0 }
5091 };
5092 int i;
5093 struct statfs fsInfo;
5094 struct flock lockInfo;
5095
5096 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005097 /* If filePath==NULL that means we are dealing with a transient file
5098 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005099 return &nolockIoMethods;
5100 }
5101 if( statfs(filePath, &fsInfo) != -1 ){
5102 if( fsInfo.f_flags & MNT_RDONLY ){
5103 return &nolockIoMethods;
5104 }
5105 for(i=0; aMap[i].zFilesystem; i++){
5106 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5107 return aMap[i].pMethods;
5108 }
5109 }
5110 }
5111
5112 /* Default case. Handles, amongst others, "nfs".
5113 ** Test byte-range lock using fcntl(). If the call succeeds,
5114 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005115 */
drh7708e972008-11-29 00:56:52 +00005116 lockInfo.l_len = 1;
5117 lockInfo.l_start = 0;
5118 lockInfo.l_whence = SEEK_SET;
5119 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005120 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005121 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5122 return &nfsIoMethods;
5123 } else {
5124 return &posixIoMethods;
5125 }
drh7708e972008-11-29 00:56:52 +00005126 }else{
5127 return &dotlockIoMethods;
5128 }
5129}
drh0c2694b2009-09-03 16:23:44 +00005130static const sqlite3_io_methods
5131 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005132
drhd2cb50b2009-01-09 21:41:17 +00005133#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005134
chw78a13182009-04-07 05:35:03 +00005135#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5136/*
5137** This "finder" function attempts to determine the best locking strategy
5138** for the database file "filePath". It then returns the sqlite3_io_methods
5139** object that implements that strategy.
5140**
5141** This is for VXWorks only.
5142*/
5143static const sqlite3_io_methods *autolockIoFinderImpl(
5144 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005145 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005146){
5147 struct flock lockInfo;
5148
5149 if( !filePath ){
5150 /* If filePath==NULL that means we are dealing with a transient file
5151 ** that does not need to be locked. */
5152 return &nolockIoMethods;
5153 }
5154
5155 /* Test if fcntl() is supported and use POSIX style locks.
5156 ** Otherwise fall back to the named semaphore method.
5157 */
5158 lockInfo.l_len = 1;
5159 lockInfo.l_start = 0;
5160 lockInfo.l_whence = SEEK_SET;
5161 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005162 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005163 return &posixIoMethods;
5164 }else{
5165 return &semIoMethods;
5166 }
5167}
drh0c2694b2009-09-03 16:23:44 +00005168static const sqlite3_io_methods
5169 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005170
5171#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5172
drh7708e972008-11-29 00:56:52 +00005173/*
5174** An abstract type for a pointer to a IO method finder function:
5175*/
drh0c2694b2009-09-03 16:23:44 +00005176typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005177
aswiftaebf4132008-11-21 00:10:35 +00005178
drh734c9862008-11-28 15:37:20 +00005179/****************************************************************************
5180**************************** sqlite3_vfs methods ****************************
5181**
5182** This division contains the implementation of methods on the
5183** sqlite3_vfs object.
5184*/
5185
danielk1977a3d4c882007-03-23 10:08:38 +00005186/*
danielk1977e339d652008-06-28 11:23:00 +00005187** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005188*/
5189static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005190 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005191 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005192 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005193 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005194 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005195){
drh7708e972008-11-29 00:56:52 +00005196 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005197 unixFile *pNew = (unixFile *)pId;
5198 int rc = SQLITE_OK;
5199
drh8af6c222010-05-14 12:43:01 +00005200 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005201
dan00157392010-10-05 11:33:15 +00005202 /* Usually the path zFilename should not be a relative pathname. The
5203 ** exception is when opening the proxy "conch" file in builds that
5204 ** include the special Apple locking styles.
5205 */
dan00157392010-10-05 11:33:15 +00005206#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005207 assert( zFilename==0 || zFilename[0]=='/'
5208 || pVfs->pAppData==(void*)&autolockIoFinder );
5209#else
5210 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005211#endif
dan00157392010-10-05 11:33:15 +00005212
drhb07028f2011-10-14 21:49:18 +00005213 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005214 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005215
drh308c2a52010-05-14 11:30:18 +00005216 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005217 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005218 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005219 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005220 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005221#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005222 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005223#endif
drhc02a43a2012-01-10 23:18:38 +00005224 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5225 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005226 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005227 }
drh503a6862013-03-01 01:07:17 +00005228 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005229 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005230 }
drh339eb0b2008-03-07 15:34:11 +00005231
drh6c7d5c52008-11-21 20:32:33 +00005232#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005233 pNew->pId = vxworksFindFileId(zFilename);
5234 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005235 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005236 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005237 }
5238#endif
5239
drhc02a43a2012-01-10 23:18:38 +00005240 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005241 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005242 }else{
drh0c2694b2009-09-03 16:23:44 +00005243 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005244#if SQLITE_ENABLE_LOCKING_STYLE
5245 /* Cache zFilename in the locking context (AFP and dotlock override) for
5246 ** proxyLock activation is possible (remote proxy is based on db name)
5247 ** zFilename remains valid until file is closed, to support */
5248 pNew->lockingContext = (void*)zFilename;
5249#endif
drhda0e7682008-07-30 15:27:54 +00005250 }
danielk1977e339d652008-06-28 11:23:00 +00005251
drh7ed97b92010-01-20 13:07:21 +00005252 if( pLockingStyle == &posixIoMethods
5253#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5254 || pLockingStyle == &nfsIoMethods
5255#endif
5256 ){
drh7708e972008-11-29 00:56:52 +00005257 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005258 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005259 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005260 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005261 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005262 ** in two scenarios:
5263 **
5264 ** (a) A call to fstat() failed.
5265 ** (b) A malloc failed.
5266 **
5267 ** Scenario (b) may only occur if the process is holding no other
5268 ** file descriptors open on the same file. If there were other file
5269 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005270 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005271 ** handle h - as it is guaranteed that no posix locks will be released
5272 ** by doing so.
5273 **
5274 ** If scenario (a) caused the error then things are not so safe. The
5275 ** implicit assumption here is that if fstat() fails, things are in
5276 ** such bad shape that dropping a lock or two doesn't matter much.
5277 */
drh0e9365c2011-03-02 02:08:13 +00005278 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005279 h = -1;
5280 }
drh7708e972008-11-29 00:56:52 +00005281 unixLeaveMutex();
5282 }
danielk1977e339d652008-06-28 11:23:00 +00005283
drhd2cb50b2009-01-09 21:41:17 +00005284#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005285 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005286 /* AFP locking uses the file path so it needs to be included in
5287 ** the afpLockingContext.
5288 */
5289 afpLockingContext *pCtx;
5290 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5291 if( pCtx==0 ){
5292 rc = SQLITE_NOMEM;
5293 }else{
5294 /* NB: zFilename exists and remains valid until the file is closed
5295 ** according to requirement F11141. So we do not need to make a
5296 ** copy of the filename. */
5297 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005298 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005299 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005300 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005301 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005302 if( rc!=SQLITE_OK ){
5303 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005304 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005305 h = -1;
5306 }
drh7708e972008-11-29 00:56:52 +00005307 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005308 }
drh7708e972008-11-29 00:56:52 +00005309 }
5310#endif
danielk1977e339d652008-06-28 11:23:00 +00005311
drh7708e972008-11-29 00:56:52 +00005312 else if( pLockingStyle == &dotlockIoMethods ){
5313 /* Dotfile locking uses the file path so it needs to be included in
5314 ** the dotlockLockingContext
5315 */
5316 char *zLockFile;
5317 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005318 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005319 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005320 zLockFile = (char *)sqlite3_malloc(nFilename);
5321 if( zLockFile==0 ){
5322 rc = SQLITE_NOMEM;
5323 }else{
5324 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005325 }
drh7708e972008-11-29 00:56:52 +00005326 pNew->lockingContext = zLockFile;
5327 }
danielk1977e339d652008-06-28 11:23:00 +00005328
drh6c7d5c52008-11-21 20:32:33 +00005329#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005330 else if( pLockingStyle == &semIoMethods ){
5331 /* Named semaphore locking uses the file path so it needs to be
5332 ** included in the semLockingContext
5333 */
5334 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005335 rc = findInodeInfo(pNew, &pNew->pInode);
5336 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5337 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005338 int n;
drh2238dcc2009-08-27 17:56:20 +00005339 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005340 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005341 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005342 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005343 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5344 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005345 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005346 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005347 }
chw97185482008-11-17 08:05:31 +00005348 }
drh7708e972008-11-29 00:56:52 +00005349 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005350 }
drh7708e972008-11-29 00:56:52 +00005351#endif
aswift5b1a2562008-08-22 00:22:35 +00005352
5353 pNew->lastErrno = 0;
drh6c7d5c52008-11-21 20:32:33 +00005354#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005355 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005356 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005357 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005358 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005359 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005360 }
chw97185482008-11-17 08:05:31 +00005361#endif
danielk1977e339d652008-06-28 11:23:00 +00005362 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005363 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005364 }else{
drh7708e972008-11-29 00:56:52 +00005365 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005366 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005367 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005368 }
danielk1977e339d652008-06-28 11:23:00 +00005369 return rc;
drh054889e2005-11-30 03:20:31 +00005370}
drh9c06c952005-11-26 00:25:00 +00005371
danielk1977ad94b582007-08-20 06:44:22 +00005372/*
drh8b3cf822010-06-01 21:02:51 +00005373** Return the name of a directory in which to put temporary files.
5374** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005375*/
drh7234c6d2010-06-19 15:10:09 +00005376static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005377 static const char *azDirs[] = {
5378 0,
aswiftaebf4132008-11-21 00:10:35 +00005379 0,
mistachkind95a3d32013-08-30 21:52:38 +00005380 0,
danielk197717b90b52008-06-06 11:11:25 +00005381 "/var/tmp",
5382 "/usr/tmp",
5383 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005384 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005385 };
drh8b3cf822010-06-01 21:02:51 +00005386 unsigned int i;
5387 struct stat buf;
5388 const char *zDir = 0;
5389
5390 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005391 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5392 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005393 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005394 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005395 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005396 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005397 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005398 break;
5399 }
5400 return zDir;
5401}
5402
5403/*
5404** Create a temporary file name in zBuf. zBuf must be allocated
5405** by the calling process and must be big enough to hold at least
5406** pVfs->mxPathname bytes.
5407*/
5408static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005409 static const unsigned char zChars[] =
5410 "abcdefghijklmnopqrstuvwxyz"
5411 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5412 "0123456789";
drh41022642008-11-21 00:24:42 +00005413 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005414 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005415
5416 /* It's odd to simulate an io-error here, but really this is just
5417 ** using the io-error infrastructure to test that SQLite handles this
5418 ** function failing.
5419 */
5420 SimulateIOError( return SQLITE_IOERR );
5421
drh7234c6d2010-06-19 15:10:09 +00005422 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005423 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005424
5425 /* Check that the output buffer is large enough for the temporary file
5426 ** name. If it is not, return SQLITE_ERROR.
5427 */
drhc02a43a2012-01-10 23:18:38 +00005428 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005429 return SQLITE_ERROR;
5430 }
5431
5432 do{
drhc02a43a2012-01-10 23:18:38 +00005433 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005434 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005435 sqlite3_randomness(15, &zBuf[j]);
5436 for(i=0; i<15; i++, j++){
5437 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5438 }
5439 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005440 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005441 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005442 return SQLITE_OK;
5443}
5444
drhd2cb50b2009-01-09 21:41:17 +00005445#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005446/*
5447** Routine to transform a unixFile into a proxy-locking unixFile.
5448** Implementation in the proxy-lock division, but used by unixOpen()
5449** if SQLITE_PREFER_PROXY_LOCKING is defined.
5450*/
5451static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005452#endif
drhc66d5b62008-12-03 22:48:32 +00005453
dan08da86a2009-08-21 17:18:03 +00005454/*
5455** Search for an unused file descriptor that was opened on the database
5456** file (not a journal or master-journal file) identified by pathname
5457** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5458** argument to this function.
5459**
5460** Such a file descriptor may exist if a database connection was closed
5461** but the associated file descriptor could not be closed because some
5462** other file descriptor open on the same file is holding a file-lock.
5463** Refer to comments in the unixClose() function and the lengthy comment
5464** describing "Posix Advisory Locking" at the start of this file for
5465** further details. Also, ticket #4018.
5466**
5467** If a suitable file descriptor is found, then it is returned. If no
5468** such file descriptor is located, -1 is returned.
5469*/
dane946c392009-08-22 11:39:46 +00005470static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5471 UnixUnusedFd *pUnused = 0;
5472
5473 /* Do not search for an unused file descriptor on vxworks. Not because
5474 ** vxworks would not benefit from the change (it might, we're not sure),
5475 ** but because no way to test it is currently available. It is better
5476 ** not to risk breaking vxworks support for the sake of such an obscure
5477 ** feature. */
5478#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005479 struct stat sStat; /* Results of stat() call */
5480
5481 /* A stat() call may fail for various reasons. If this happens, it is
5482 ** almost certain that an open() call on the same path will also fail.
5483 ** For this reason, if an error occurs in the stat() call here, it is
5484 ** ignored and -1 is returned. The caller will try to open a new file
5485 ** descriptor on the same path, fail, and return an error to SQLite.
5486 **
5487 ** Even if a subsequent open() call does succeed, the consequences of
5488 ** not searching for a resusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005489 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005490 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005491
5492 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005493 pInode = inodeList;
5494 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5495 || pInode->fileId.ino!=sStat.st_ino) ){
5496 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005497 }
drh8af6c222010-05-14 12:43:01 +00005498 if( pInode ){
dane946c392009-08-22 11:39:46 +00005499 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005500 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005501 pUnused = *pp;
5502 if( pUnused ){
5503 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005504 }
5505 }
5506 unixLeaveMutex();
5507 }
dane946c392009-08-22 11:39:46 +00005508#endif /* if !OS_VXWORKS */
5509 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005510}
danielk197717b90b52008-06-06 11:11:25 +00005511
5512/*
danddb0ac42010-07-14 14:48:58 +00005513** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005514** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005515** and a value suitable for passing as the third argument to open(2) is
5516** written to *pMode. If an IO error occurs, an SQLite error code is
5517** returned and the value of *pMode is not modified.
5518**
drh8c815d12012-02-13 20:16:37 +00005519** In most cases cases, this routine sets *pMode to 0, which will become
5520** an indication to robust_open() to create the file using
5521** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5522** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005523** this function queries the file-system for the permissions on the
5524** corresponding database file and sets *pMode to this value. Whenever
5525** possible, WAL and journal files are created using the same permissions
5526** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005527**
5528** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5529** original filename is unavailable. But 8_3_NAMES is only used for
5530** FAT filesystems and permissions do not matter there, so just use
5531** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005532*/
5533static int findCreateFileMode(
5534 const char *zPath, /* Path of file (possibly) being created */
5535 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005536 mode_t *pMode, /* OUT: Permissions to open file with */
5537 uid_t *pUid, /* OUT: uid to set on the file */
5538 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005539){
5540 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005541 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005542 *pUid = 0;
5543 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005544 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005545 char zDb[MAX_PATHNAME+1]; /* Database file path */
5546 int nDb; /* Number of valid bytes in zDb */
5547 struct stat sStat; /* Output of stat() on database file */
5548
dana0c989d2010-11-05 18:07:37 +00005549 /* zPath is a path to a WAL or journal file. The following block derives
5550 ** the path to the associated database file from zPath. This block handles
5551 ** the following naming conventions:
5552 **
5553 ** "<path to db>-journal"
5554 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005555 ** "<path to db>-journalNN"
5556 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005557 **
drhd337c5b2011-10-20 18:23:35 +00005558 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005559 ** used by the test_multiplex.c module.
5560 */
5561 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005562#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005563 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005564 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005565#else
5566 while( zPath[nDb]!='-' ){
5567 assert( nDb>0 );
5568 assert( zPath[nDb]!='\n' );
5569 nDb--;
5570 }
5571#endif
danddb0ac42010-07-14 14:48:58 +00005572 memcpy(zDb, zPath, nDb);
5573 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005574
drh58384f12011-07-28 00:14:45 +00005575 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005576 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005577 *pUid = sStat.st_uid;
5578 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005579 }else{
5580 rc = SQLITE_IOERR_FSTAT;
5581 }
5582 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5583 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005584 }
5585 return rc;
5586}
5587
5588/*
danielk1977ad94b582007-08-20 06:44:22 +00005589** Open the file zPath.
5590**
danielk1977b4b47412007-08-17 15:53:36 +00005591** Previously, the SQLite OS layer used three functions in place of this
5592** one:
5593**
5594** sqlite3OsOpenReadWrite();
5595** sqlite3OsOpenReadOnly();
5596** sqlite3OsOpenExclusive();
5597**
5598** These calls correspond to the following combinations of flags:
5599**
5600** ReadWrite() -> (READWRITE | CREATE)
5601** ReadOnly() -> (READONLY)
5602** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5603**
5604** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5605** true, the file was configured to be automatically deleted when the
5606** file handle closed. To achieve the same effect using this new
5607** interface, add the DELETEONCLOSE flag to those specified above for
5608** OpenExclusive().
5609*/
5610static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005611 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5612 const char *zPath, /* Pathname of file to be opened */
5613 sqlite3_file *pFile, /* The file descriptor to be filled in */
5614 int flags, /* Input flags to control the opening */
5615 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005616){
dan08da86a2009-08-21 17:18:03 +00005617 unixFile *p = (unixFile *)pFile;
5618 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005619 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005620 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005621 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005622 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005623 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005624
5625 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5626 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5627 int isCreate = (flags & SQLITE_OPEN_CREATE);
5628 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5629 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005630#if SQLITE_ENABLE_LOCKING_STYLE
5631 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5632#endif
drh3d4435b2011-08-26 20:55:50 +00005633#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5634 struct statfs fsInfo;
5635#endif
danielk1977b4b47412007-08-17 15:53:36 +00005636
danielk1977fee2d252007-08-18 10:59:19 +00005637 /* If creating a master or main-file journal, this function will open
5638 ** a file-descriptor on the directory too. The first time unixSync()
5639 ** is called the directory file descriptor will be fsync()ed and close()d.
5640 */
drh0059eae2011-08-08 23:48:40 +00005641 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005642 eType==SQLITE_OPEN_MASTER_JOURNAL
5643 || eType==SQLITE_OPEN_MAIN_JOURNAL
5644 || eType==SQLITE_OPEN_WAL
5645 ));
danielk1977fee2d252007-08-18 10:59:19 +00005646
danielk197717b90b52008-06-06 11:11:25 +00005647 /* If argument zPath is a NULL pointer, this function is required to open
5648 ** a temporary file. Use this buffer to store the file name in.
5649 */
drhc02a43a2012-01-10 23:18:38 +00005650 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005651 const char *zName = zPath;
5652
danielk1977fee2d252007-08-18 10:59:19 +00005653 /* Check the following statements are true:
5654 **
5655 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5656 ** (b) if CREATE is set, then READWRITE must also be set, and
5657 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005658 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005659 */
danielk1977b4b47412007-08-17 15:53:36 +00005660 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005661 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005662 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005663 assert(isDelete==0 || isCreate);
5664
danddb0ac42010-07-14 14:48:58 +00005665 /* The main DB, main journal, WAL file and master journal are never
5666 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005667 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5668 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5669 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005670 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005671
danielk1977fee2d252007-08-18 10:59:19 +00005672 /* Assert that the upper layer has set one of the "file-type" flags. */
5673 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5674 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5675 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005676 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005677 );
5678
drhb00d8622014-01-01 15:18:36 +00005679 /* Detect a pid change and reset the PRNG. There is a race condition
5680 ** here such that two or more threads all trying to open databases at
5681 ** the same instant might all reset the PRNG. But multiple resets
5682 ** are harmless.
5683 */
5684 if( randomnessPid!=getpid() ){
5685 randomnessPid = getpid();
5686 sqlite3_randomness(0,0);
5687 }
5688
dan08da86a2009-08-21 17:18:03 +00005689 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005690
dan08da86a2009-08-21 17:18:03 +00005691 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005692 UnixUnusedFd *pUnused;
5693 pUnused = findReusableFd(zName, flags);
5694 if( pUnused ){
5695 fd = pUnused->fd;
5696 }else{
dan6aa657f2009-08-24 18:57:58 +00005697 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005698 if( !pUnused ){
5699 return SQLITE_NOMEM;
5700 }
5701 }
5702 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005703
5704 /* Database filenames are double-zero terminated if they are not
5705 ** URIs with parameters. Hence, they can always be passed into
5706 ** sqlite3_uri_parameter(). */
5707 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5708
dan08da86a2009-08-21 17:18:03 +00005709 }else if( !zName ){
5710 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005711 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005712 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005713 if( rc!=SQLITE_OK ){
5714 return rc;
5715 }
5716 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005717
5718 /* Generated temporary filenames are always double-zero terminated
5719 ** for use by sqlite3_uri_parameter(). */
5720 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005721 }
5722
dan08da86a2009-08-21 17:18:03 +00005723 /* Determine the value of the flags parameter passed to POSIX function
5724 ** open(). These must be calculated even if open() is not called, as
5725 ** they may be stored as part of the file handle and used by the
5726 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005727 if( isReadonly ) openFlags |= O_RDONLY;
5728 if( isReadWrite ) openFlags |= O_RDWR;
5729 if( isCreate ) openFlags |= O_CREAT;
5730 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5731 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005732
danielk1977b4b47412007-08-17 15:53:36 +00005733 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005734 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005735 uid_t uid; /* Userid for the file */
5736 gid_t gid; /* Groupid for the file */
5737 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005738 if( rc!=SQLITE_OK ){
5739 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005740 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005741 return rc;
5742 }
drhad4f1e52011-03-04 15:43:57 +00005743 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005744 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005745 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5746 /* Failed to open the file for read/write access. Try read-only. */
5747 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005748 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005749 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005750 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005751 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005752 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005753 }
5754 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005755 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005756 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005757 }
drhac7c3ac2012-02-11 19:23:48 +00005758
5759 /* If this process is running as root and if creating a new rollback
5760 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005761 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005762 */
5763 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005764 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005765 }
danielk1977b4b47412007-08-17 15:53:36 +00005766 }
dan08da86a2009-08-21 17:18:03 +00005767 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005768 if( pOutFlags ){
5769 *pOutFlags = flags;
5770 }
5771
dane946c392009-08-22 11:39:46 +00005772 if( p->pUnused ){
5773 p->pUnused->fd = fd;
5774 p->pUnused->flags = flags;
5775 }
5776
danielk1977b4b47412007-08-17 15:53:36 +00005777 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005778#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005779 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005780#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5781 zPath = sqlite3_mprintf("%s", zName);
5782 if( zPath==0 ){
5783 robust_close(p, fd, __LINE__);
5784 return SQLITE_NOMEM;
5785 }
chw97185482008-11-17 08:05:31 +00005786#else
drh036ac7f2011-08-08 23:18:05 +00005787 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005788#endif
danielk1977b4b47412007-08-17 15:53:36 +00005789 }
drh41022642008-11-21 00:24:42 +00005790#if SQLITE_ENABLE_LOCKING_STYLE
5791 else{
dan08da86a2009-08-21 17:18:03 +00005792 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005793 }
5794#endif
5795
drhda0e7682008-07-30 15:27:54 +00005796 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005797
drh7ed97b92010-01-20 13:07:21 +00005798
5799#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005800 if( fstatfs(fd, &fsInfo) == -1 ){
5801 ((unixFile*)pFile)->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005802 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005803 return SQLITE_IOERR_ACCESS;
5804 }
5805 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5806 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5807 }
5808#endif
drhc02a43a2012-01-10 23:18:38 +00005809
5810 /* Set up appropriate ctrlFlags */
5811 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5812 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5813 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5814 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5815 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5816
drh7ed97b92010-01-20 13:07:21 +00005817#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005818#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005819 isAutoProxy = 1;
5820#endif
5821 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005822 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5823 int useProxy = 0;
5824
dan08da86a2009-08-21 17:18:03 +00005825 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5826 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005827 if( envforce!=NULL ){
5828 useProxy = atoi(envforce)>0;
5829 }else{
aswiftaebf4132008-11-21 00:10:35 +00005830 if( statfs(zPath, &fsInfo) == -1 ){
dane946c392009-08-22 11:39:46 +00005831 /* In theory, the close(fd) call is sub-optimal. If the file opened
5832 ** with fd is a database file, and there are other connections open
5833 ** on that file that are currently holding advisory locks on it,
5834 ** then the call to close() will cancel those locks. In practice,
5835 ** we're assuming that statfs() doesn't fail very often. At least
5836 ** not while other file descriptors opened by the same process on
5837 ** the same file are working. */
5838 p->lastErrno = errno;
drh0e9365c2011-03-02 02:08:13 +00005839 robust_close(p, fd, __LINE__);
dane946c392009-08-22 11:39:46 +00005840 rc = SQLITE_IOERR_ACCESS;
5841 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005842 }
5843 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5844 }
5845 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005846 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005847 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005848 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005849 if( rc!=SQLITE_OK ){
5850 /* Use unixClose to clean up the resources added in fillInUnixFile
5851 ** and clear all the structure's references. Specifically,
5852 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5853 */
5854 unixClose(pFile);
5855 return rc;
5856 }
aswiftaebf4132008-11-21 00:10:35 +00005857 }
dane946c392009-08-22 11:39:46 +00005858 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005859 }
5860 }
5861#endif
5862
drhc02a43a2012-01-10 23:18:38 +00005863 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5864
dane946c392009-08-22 11:39:46 +00005865open_finished:
5866 if( rc!=SQLITE_OK ){
5867 sqlite3_free(p->pUnused);
5868 }
5869 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005870}
5871
dane946c392009-08-22 11:39:46 +00005872
danielk1977b4b47412007-08-17 15:53:36 +00005873/*
danielk1977fee2d252007-08-18 10:59:19 +00005874** Delete the file at zPath. If the dirSync argument is true, fsync()
5875** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005876*/
drh6b9d6dd2008-12-03 19:34:47 +00005877static int unixDelete(
5878 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5879 const char *zPath, /* Name of file to be deleted */
5880 int dirSync /* If true, fsync() directory after deleting file */
5881){
danielk1977fee2d252007-08-18 10:59:19 +00005882 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005883 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005884 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005885 if( osUnlink(zPath)==(-1) ){
5886 if( errno==ENOENT ){
5887 rc = SQLITE_IOERR_DELETE_NOENT;
5888 }else{
drhb4308162012-11-09 21:40:02 +00005889 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005890 }
drhb4308162012-11-09 21:40:02 +00005891 return rc;
drh5d4feff2010-07-14 01:45:22 +00005892 }
danielk1977d39fa702008-10-16 13:27:40 +00005893#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005894 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005895 int fd;
drh90315a22011-08-10 01:52:12 +00005896 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005897 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005898#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005899 if( fsync(fd)==-1 )
5900#else
5901 if( fsync(fd) )
5902#endif
5903 {
dane18d4952011-02-21 11:46:24 +00005904 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005905 }
drh0e9365c2011-03-02 02:08:13 +00005906 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005907 }else if( rc==SQLITE_CANTOPEN ){
5908 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005909 }
5910 }
danielk1977d138dd82008-10-15 16:02:48 +00005911#endif
danielk1977fee2d252007-08-18 10:59:19 +00005912 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005913}
5914
danielk197790949c22007-08-17 16:50:38 +00005915/*
mistachkin48864df2013-03-21 21:20:32 +00005916** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005917** test performed depends on the value of flags:
5918**
5919** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5920** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5921** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5922**
5923** Otherwise return 0.
5924*/
danielk1977861f7452008-06-05 11:39:11 +00005925static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005926 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5927 const char *zPath, /* Path of the file to examine */
5928 int flags, /* What do we want to learn about the zPath file? */
5929 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005930){
rse25c0d1a2007-09-20 08:38:14 +00005931 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005932 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005933 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005934 switch( flags ){
5935 case SQLITE_ACCESS_EXISTS:
5936 amode = F_OK;
5937 break;
5938 case SQLITE_ACCESS_READWRITE:
5939 amode = W_OK|R_OK;
5940 break;
drh50d3f902007-08-27 21:10:36 +00005941 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005942 amode = R_OK;
5943 break;
5944
5945 default:
5946 assert(!"Invalid flags argument");
5947 }
drh99ab3b12011-03-02 15:09:07 +00005948 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005949 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5950 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005951 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005952 *pResOut = 0;
5953 }
5954 }
danielk1977861f7452008-06-05 11:39:11 +00005955 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005956}
5957
danielk1977b4b47412007-08-17 15:53:36 +00005958
5959/*
5960** Turn a relative pathname into a full pathname. The relative path
5961** is stored as a nul-terminated string in the buffer pointed to by
5962** zPath.
5963**
5964** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5965** (in this case, MAX_PATHNAME bytes). The full-path is written to
5966** this buffer before returning.
5967*/
danielk1977adfb9b02007-09-17 07:02:56 +00005968static int unixFullPathname(
5969 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5970 const char *zPath, /* Possibly relative input path */
5971 int nOut, /* Size of output buffer in bytes */
5972 char *zOut /* Output buffer */
5973){
danielk1977843e65f2007-09-01 16:16:15 +00005974
5975 /* It's odd to simulate an io-error here, but really this is just
5976 ** using the io-error infrastructure to test that SQLite handles this
5977 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00005978 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00005979 */
5980 SimulateIOError( return SQLITE_ERROR );
5981
drh153c62c2007-08-24 03:51:33 +00005982 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00005983 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00005984
drh3c7f2dc2007-12-06 13:26:20 +00005985 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00005986 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00005987 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005988 }else{
5989 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00005990 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00005991 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005992 }
drhea678832008-12-10 19:26:22 +00005993 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00005994 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005995 }
5996 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005997}
5998
drh0ccebe72005-06-07 22:22:50 +00005999
drh761df872006-12-21 01:29:22 +00006000#ifndef SQLITE_OMIT_LOAD_EXTENSION
6001/*
6002** Interfaces for opening a shared library, finding entry points
6003** within the shared library, and closing the shared library.
6004*/
6005#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006006static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6007 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006008 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6009}
danielk197795c8a542007-09-01 06:51:27 +00006010
6011/*
6012** SQLite calls this function immediately after a call to unixDlSym() or
6013** unixDlOpen() fails (returns a null pointer). If a more detailed error
6014** message is available, it is written to zBufOut. If no error message
6015** is available, zBufOut is left unmodified and SQLite uses a default
6016** error message.
6017*/
danielk1977397d65f2008-11-19 11:35:39 +00006018static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006019 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006020 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006021 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006022 zErr = dlerror();
6023 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006024 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006025 }
drh6c7d5c52008-11-21 20:32:33 +00006026 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006027}
drh1875f7a2008-12-08 18:19:17 +00006028static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6029 /*
6030 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6031 ** cast into a pointer to a function. And yet the library dlsym() routine
6032 ** returns a void* which is really a pointer to a function. So how do we
6033 ** use dlsym() with -pedantic-errors?
6034 **
6035 ** Variable x below is defined to be a pointer to a function taking
6036 ** parameters void* and const char* and returning a pointer to a function.
6037 ** We initialize x by assigning it a pointer to the dlsym() function.
6038 ** (That assignment requires a cast.) Then we call the function that
6039 ** x points to.
6040 **
6041 ** This work-around is unlikely to work correctly on any system where
6042 ** you really cannot cast a function pointer into void*. But then, on the
6043 ** other hand, dlsym() will not work on such a system either, so we have
6044 ** not really lost anything.
6045 */
6046 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006047 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006048 x = (void(*(*)(void*,const char*))(void))dlsym;
6049 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006050}
danielk1977397d65f2008-11-19 11:35:39 +00006051static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6052 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006053 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006054}
danielk1977b4b47412007-08-17 15:53:36 +00006055#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6056 #define unixDlOpen 0
6057 #define unixDlError 0
6058 #define unixDlSym 0
6059 #define unixDlClose 0
6060#endif
6061
6062/*
danielk197790949c22007-08-17 16:50:38 +00006063** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006064*/
danielk1977397d65f2008-11-19 11:35:39 +00006065static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6066 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006067 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006068
drhbbd42a62004-05-22 17:41:58 +00006069 /* We have to initialize zBuf to prevent valgrind from reporting
6070 ** errors. The reports issued by valgrind are incorrect - we would
6071 ** prefer that the randomness be increased by making use of the
6072 ** uninitialized space in zBuf - but valgrind errors tend to worry
6073 ** some users. Rather than argue, it seems easier just to initialize
6074 ** the whole array and silence valgrind, even if that means less randomness
6075 ** in the random seed.
6076 **
6077 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006078 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006079 ** tests repeatable.
6080 */
danielk1977b4b47412007-08-17 15:53:36 +00006081 memset(zBuf, 0, nBuf);
drhb00d8622014-01-01 15:18:36 +00006082 randomnessPid = getpid();
drhbbd42a62004-05-22 17:41:58 +00006083#if !defined(SQLITE_TEST)
6084 {
drhb00d8622014-01-01 15:18:36 +00006085 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006086 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006087 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006088 time_t t;
6089 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006090 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006091 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6092 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6093 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006094 }else{
drhc18b4042012-02-10 03:10:27 +00006095 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006096 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006097 }
drhbbd42a62004-05-22 17:41:58 +00006098 }
6099#endif
drh72cbd072008-10-14 17:58:38 +00006100 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006101}
6102
danielk1977b4b47412007-08-17 15:53:36 +00006103
drhbbd42a62004-05-22 17:41:58 +00006104/*
6105** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006106** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006107** The return value is the number of microseconds of sleep actually
6108** requested from the underlying operating system, a number which
6109** might be greater than or equal to the argument, but not less
6110** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006111*/
danielk1977397d65f2008-11-19 11:35:39 +00006112static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006113#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006114 struct timespec sp;
6115
6116 sp.tv_sec = microseconds / 1000000;
6117 sp.tv_nsec = (microseconds % 1000000) * 1000;
6118 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006119 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006120 return microseconds;
6121#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006122 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006123 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006124 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006125#else
danielk1977b4b47412007-08-17 15:53:36 +00006126 int seconds = (microseconds+999999)/1000000;
6127 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006128 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006129 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006130#endif
drh88f474a2006-01-02 20:00:12 +00006131}
6132
6133/*
drh6b9d6dd2008-12-03 19:34:47 +00006134** The following variable, if set to a non-zero value, is interpreted as
6135** the number of seconds since 1970 and is used to set the result of
6136** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006137*/
6138#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006139int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006140#endif
6141
6142/*
drhb7e8ea22010-05-03 14:32:30 +00006143** Find the current time (in Universal Coordinated Time). Write into *piNow
6144** the current time and date as a Julian Day number times 86_400_000. In
6145** other words, write into *piNow the number of milliseconds since the Julian
6146** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6147** proleptic Gregorian calendar.
6148**
drh31702252011-10-12 23:13:43 +00006149** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6150** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006151*/
6152static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6153 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006154 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006155#if defined(NO_GETTOD)
6156 time_t t;
6157 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006158 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006159#elif OS_VXWORKS
6160 struct timespec sNow;
6161 clock_gettime(CLOCK_REALTIME, &sNow);
6162 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6163#else
6164 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006165 if( gettimeofday(&sNow, 0)==0 ){
6166 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6167 }else{
6168 rc = SQLITE_ERROR;
6169 }
drhb7e8ea22010-05-03 14:32:30 +00006170#endif
6171
6172#ifdef SQLITE_TEST
6173 if( sqlite3_current_time ){
6174 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6175 }
6176#endif
6177 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006178 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006179}
6180
6181/*
drhbbd42a62004-05-22 17:41:58 +00006182** Find the current time (in Universal Coordinated Time). Write the
6183** current time and date as a Julian Day number into *prNow and
6184** return 0. Return 1 if the time and date cannot be found.
6185*/
danielk1977397d65f2008-11-19 11:35:39 +00006186static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006187 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006188 int rc;
drhff828942010-06-26 21:34:06 +00006189 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006190 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006191 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006192 return rc;
drhbbd42a62004-05-22 17:41:58 +00006193}
danielk1977b4b47412007-08-17 15:53:36 +00006194
drh6b9d6dd2008-12-03 19:34:47 +00006195/*
6196** We added the xGetLastError() method with the intention of providing
6197** better low-level error messages when operating-system problems come up
6198** during SQLite operation. But so far, none of that has been implemented
6199** in the core. So this routine is never called. For now, it is merely
6200** a place-holder.
6201*/
danielk1977397d65f2008-11-19 11:35:39 +00006202static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6203 UNUSED_PARAMETER(NotUsed);
6204 UNUSED_PARAMETER(NotUsed2);
6205 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006206 return 0;
6207}
6208
drhf2424c52010-04-26 00:04:55 +00006209
6210/*
drh734c9862008-11-28 15:37:20 +00006211************************ End of sqlite3_vfs methods ***************************
6212******************************************************************************/
6213
drh715ff302008-12-03 22:32:44 +00006214/******************************************************************************
6215************************** Begin Proxy Locking ********************************
6216**
6217** Proxy locking is a "uber-locking-method" in this sense: It uses the
6218** other locking methods on secondary lock files. Proxy locking is a
6219** meta-layer over top of the primitive locking implemented above. For
6220** this reason, the division that implements of proxy locking is deferred
6221** until late in the file (here) after all of the other I/O methods have
6222** been defined - so that the primitive locking methods are available
6223** as services to help with the implementation of proxy locking.
6224**
6225****
6226**
6227** The default locking schemes in SQLite use byte-range locks on the
6228** database file to coordinate safe, concurrent access by multiple readers
6229** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6230** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6231** as POSIX read & write locks over fixed set of locations (via fsctl),
6232** on AFP and SMB only exclusive byte-range locks are available via fsctl
6233** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6234** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6235** address in the shared range is taken for a SHARED lock, the entire
6236** shared range is taken for an EXCLUSIVE lock):
6237**
drhf2f105d2012-08-20 15:53:54 +00006238** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006239** RESERVED_BYTE 0x40000001
6240** SHARED_RANGE 0x40000002 -> 0x40000200
6241**
6242** This works well on the local file system, but shows a nearly 100x
6243** slowdown in read performance on AFP because the AFP client disables
6244** the read cache when byte-range locks are present. Enabling the read
6245** cache exposes a cache coherency problem that is present on all OS X
6246** supported network file systems. NFS and AFP both observe the
6247** close-to-open semantics for ensuring cache coherency
6248** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6249** address the requirements for concurrent database access by multiple
6250** readers and writers
6251** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6252**
6253** To address the performance and cache coherency issues, proxy file locking
6254** changes the way database access is controlled by limiting access to a
6255** single host at a time and moving file locks off of the database file
6256** and onto a proxy file on the local file system.
6257**
6258**
6259** Using proxy locks
6260** -----------------
6261**
6262** C APIs
6263**
6264** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
6265** <proxy_path> | ":auto:");
6266** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
6267**
6268**
6269** SQL pragmas
6270**
6271** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6272** PRAGMA [database.]lock_proxy_file
6273**
6274** Specifying ":auto:" means that if there is a conch file with a matching
6275** host ID in it, the proxy path in the conch file will be used, otherwise
6276** a proxy path based on the user's temp dir
6277** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6278** actual proxy file name is generated from the name and path of the
6279** database file. For example:
6280**
6281** For database path "/Users/me/foo.db"
6282** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6283**
6284** Once a lock proxy is configured for a database connection, it can not
6285** be removed, however it may be switched to a different proxy path via
6286** the above APIs (assuming the conch file is not being held by another
6287** connection or process).
6288**
6289**
6290** How proxy locking works
6291** -----------------------
6292**
6293** Proxy file locking relies primarily on two new supporting files:
6294**
6295** * conch file to limit access to the database file to a single host
6296** at a time
6297**
6298** * proxy file to act as a proxy for the advisory locks normally
6299** taken on the database
6300**
6301** The conch file - to use a proxy file, sqlite must first "hold the conch"
6302** by taking an sqlite-style shared lock on the conch file, reading the
6303** contents and comparing the host's unique host ID (see below) and lock
6304** proxy path against the values stored in the conch. The conch file is
6305** stored in the same directory as the database file and the file name
6306** is patterned after the database file name as ".<databasename>-conch".
6307** If the conch file does not exist, or it's contents do not match the
6308** host ID and/or proxy path, then the lock is escalated to an exclusive
6309** lock and the conch file contents is updated with the host ID and proxy
6310** path and the lock is downgraded to a shared lock again. If the conch
6311** is held by another process (with a shared lock), the exclusive lock
6312** will fail and SQLITE_BUSY is returned.
6313**
6314** The proxy file - a single-byte file used for all advisory file locks
6315** normally taken on the database file. This allows for safe sharing
6316** of the database file for multiple readers and writers on the same
6317** host (the conch ensures that they all use the same local lock file).
6318**
drh715ff302008-12-03 22:32:44 +00006319** Requesting the lock proxy does not immediately take the conch, it is
6320** only taken when the first request to lock database file is made.
6321** This matches the semantics of the traditional locking behavior, where
6322** opening a connection to a database file does not take a lock on it.
6323** The shared lock and an open file descriptor are maintained until
6324** the connection to the database is closed.
6325**
6326** The proxy file and the lock file are never deleted so they only need
6327** to be created the first time they are used.
6328**
6329** Configuration options
6330** ---------------------
6331**
6332** SQLITE_PREFER_PROXY_LOCKING
6333**
6334** Database files accessed on non-local file systems are
6335** automatically configured for proxy locking, lock files are
6336** named automatically using the same logic as
6337** PRAGMA lock_proxy_file=":auto:"
6338**
6339** SQLITE_PROXY_DEBUG
6340**
6341** Enables the logging of error messages during host id file
6342** retrieval and creation
6343**
drh715ff302008-12-03 22:32:44 +00006344** LOCKPROXYDIR
6345**
6346** Overrides the default directory used for lock proxy files that
6347** are named automatically via the ":auto:" setting
6348**
6349** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6350**
6351** Permissions to use when creating a directory for storing the
6352** lock proxy files, only used when LOCKPROXYDIR is not set.
6353**
6354**
6355** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6356** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6357** force proxy locking to be used for every database file opened, and 0
6358** will force automatic proxy locking to be disabled for all database
6359** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
6360** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6361*/
6362
6363/*
6364** Proxy locking is only available on MacOSX
6365*/
drhd2cb50b2009-01-09 21:41:17 +00006366#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006367
drh715ff302008-12-03 22:32:44 +00006368/*
6369** The proxyLockingContext has the path and file structures for the remote
6370** and local proxy files in it
6371*/
6372typedef struct proxyLockingContext proxyLockingContext;
6373struct proxyLockingContext {
6374 unixFile *conchFile; /* Open conch file */
6375 char *conchFilePath; /* Name of the conch file */
6376 unixFile *lockProxy; /* Open proxy lock file */
6377 char *lockProxyPath; /* Name of the proxy lock file */
6378 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006379 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh715ff302008-12-03 22:32:44 +00006380 void *oldLockingContext; /* Original lockingcontext to restore on close */
6381 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6382};
6383
drh7ed97b92010-01-20 13:07:21 +00006384/*
6385** The proxy lock file path for the database at dbPath is written into lPath,
6386** which must point to valid, writable memory large enough for a maxLen length
6387** file path.
drh715ff302008-12-03 22:32:44 +00006388*/
drh715ff302008-12-03 22:32:44 +00006389static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6390 int len;
6391 int dbLen;
6392 int i;
6393
6394#ifdef LOCKPROXYDIR
6395 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6396#else
6397# ifdef _CS_DARWIN_USER_TEMP_DIR
6398 {
drh7ed97b92010-01-20 13:07:21 +00006399 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006400 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
6401 lPath, errno, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006402 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006403 }
drh7ed97b92010-01-20 13:07:21 +00006404 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006405 }
6406# else
6407 len = strlcpy(lPath, "/tmp/", maxLen);
6408# endif
6409#endif
6410
6411 if( lPath[len-1]!='/' ){
6412 len = strlcat(lPath, "/", maxLen);
6413 }
6414
6415 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006416 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006417 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006418 char c = dbPath[i];
6419 lPath[i+len] = (c=='/')?'_':c;
6420 }
6421 lPath[i+len]='\0';
6422 strlcat(lPath, ":auto:", maxLen);
drh308c2a52010-05-14 11:30:18 +00006423 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
drh715ff302008-12-03 22:32:44 +00006424 return SQLITE_OK;
6425}
6426
drh7ed97b92010-01-20 13:07:21 +00006427/*
6428 ** Creates the lock file and any missing directories in lockPath
6429 */
6430static int proxyCreateLockPath(const char *lockPath){
6431 int i, len;
6432 char buf[MAXPATHLEN];
6433 int start = 0;
6434
6435 assert(lockPath!=NULL);
6436 /* try to create all the intermediate directories */
6437 len = (int)strlen(lockPath);
6438 buf[0] = lockPath[0];
6439 for( i=1; i<len; i++ ){
6440 if( lockPath[i] == '/' && (i - start > 0) ){
6441 /* only mkdir if leaf dir != "." or "/" or ".." */
6442 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6443 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6444 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006445 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006446 int err=errno;
6447 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006448 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006449 "'%s' proxy lock path=%s pid=%d\n",
drh308c2a52010-05-14 11:30:18 +00006450 buf, strerror(err), lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006451 return err;
6452 }
6453 }
6454 }
6455 start=i+1;
6456 }
6457 buf[i] = lockPath[i];
6458 }
drh308c2a52010-05-14 11:30:18 +00006459 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
drh7ed97b92010-01-20 13:07:21 +00006460 return 0;
6461}
6462
drh715ff302008-12-03 22:32:44 +00006463/*
6464** Create a new VFS file descriptor (stored in memory obtained from
6465** sqlite3_malloc) and open the file named "path" in the file descriptor.
6466**
6467** The caller is responsible not only for closing the file descriptor
6468** but also for freeing the memory associated with the file descriptor.
6469*/
drh7ed97b92010-01-20 13:07:21 +00006470static int proxyCreateUnixFile(
6471 const char *path, /* path for the new unixFile */
6472 unixFile **ppFile, /* unixFile created and returned by ref */
6473 int islockfile /* if non zero missing dirs will be created */
6474) {
6475 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006476 unixFile *pNew;
6477 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006478 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006479 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006480 int terrno = 0;
6481 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006482
drh7ed97b92010-01-20 13:07:21 +00006483 /* 1. first try to open/create the file
6484 ** 2. if that fails, and this is a lock file (not-conch), try creating
6485 ** the parent directories and then try again.
6486 ** 3. if that fails, try to open the file read-only
6487 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6488 */
6489 pUnused = findReusableFd(path, openFlags);
6490 if( pUnused ){
6491 fd = pUnused->fd;
6492 }else{
6493 pUnused = sqlite3_malloc(sizeof(*pUnused));
6494 if( !pUnused ){
6495 return SQLITE_NOMEM;
6496 }
6497 }
6498 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006499 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006500 terrno = errno;
6501 if( fd<0 && errno==ENOENT && islockfile ){
6502 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006503 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006504 }
6505 }
6506 }
6507 if( fd<0 ){
6508 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006509 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006510 terrno = errno;
6511 }
6512 if( fd<0 ){
6513 if( islockfile ){
6514 return SQLITE_BUSY;
6515 }
6516 switch (terrno) {
6517 case EACCES:
6518 return SQLITE_PERM;
6519 case EIO:
6520 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6521 default:
drh9978c972010-02-23 17:36:32 +00006522 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006523 }
6524 }
6525
6526 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6527 if( pNew==NULL ){
6528 rc = SQLITE_NOMEM;
6529 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006530 }
6531 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006532 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006533 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006534 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006535 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006536 pUnused->fd = fd;
6537 pUnused->flags = openFlags;
6538 pNew->pUnused = pUnused;
6539
drhc02a43a2012-01-10 23:18:38 +00006540 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006541 if( rc==SQLITE_OK ){
6542 *ppFile = pNew;
6543 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006544 }
drh7ed97b92010-01-20 13:07:21 +00006545end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006546 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006547 sqlite3_free(pNew);
6548 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006549 return rc;
6550}
6551
drh7ed97b92010-01-20 13:07:21 +00006552#ifdef SQLITE_TEST
6553/* simulate multiple hosts by creating unique hostid file paths */
6554int sqlite3_hostid_num = 0;
6555#endif
6556
6557#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6558
drh0ab216a2010-07-02 17:10:40 +00006559/* Not always defined in the headers as it ought to be */
6560extern int gethostuuid(uuid_t id, const struct timespec *wait);
6561
drh7ed97b92010-01-20 13:07:21 +00006562/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6563** bytes of writable memory.
6564*/
6565static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006566 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6567 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe8b0c9b2010-09-25 14:13:17 +00006568#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
6569 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
drh29ecd8a2010-12-21 00:16:40 +00006570 {
6571 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
6572 if( gethostuuid(pHostID, &timeout) ){
6573 int err = errno;
6574 if( pError ){
6575 *pError = err;
6576 }
6577 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006578 }
drh7ed97b92010-01-20 13:07:21 +00006579 }
drh3d4435b2011-08-26 20:55:50 +00006580#else
6581 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006582#endif
drh7ed97b92010-01-20 13:07:21 +00006583#ifdef SQLITE_TEST
6584 /* simulate multiple hosts by creating unique hostid file paths */
6585 if( sqlite3_hostid_num != 0){
6586 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6587 }
6588#endif
6589
6590 return SQLITE_OK;
6591}
6592
6593/* The conch file contains the header, host id and lock file path
6594 */
6595#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6596#define PROXY_HEADERLEN 1 /* conch file header length */
6597#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6598#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6599
6600/*
6601** Takes an open conch file, copies the contents to a new path and then moves
6602** it back. The newly created file's file descriptor is assigned to the
6603** conch file structure and finally the original conch file descriptor is
6604** closed. Returns zero if successful.
6605*/
6606static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6607 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6608 unixFile *conchFile = pCtx->conchFile;
6609 char tPath[MAXPATHLEN];
6610 char buf[PROXY_MAXCONCHLEN];
6611 char *cPath = pCtx->conchFilePath;
6612 size_t readLen = 0;
6613 size_t pathLen = 0;
6614 char errmsg[64] = "";
6615 int fd = -1;
6616 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006617 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006618
6619 /* create a new path by replace the trailing '-conch' with '-break' */
6620 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6621 if( pathLen>MAXPATHLEN || pathLen<6 ||
6622 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006623 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006624 goto end_breaklock;
6625 }
6626 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006627 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006628 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006629 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006630 goto end_breaklock;
6631 }
6632 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006633 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006634 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006635 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006636 goto end_breaklock;
6637 }
drhe562be52011-03-02 18:01:10 +00006638 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006639 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006640 goto end_breaklock;
6641 }
6642 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006643 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006644 goto end_breaklock;
6645 }
6646 rc = 0;
6647 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006648 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006649 conchFile->h = fd;
6650 conchFile->openFlags = O_RDWR | O_CREAT;
6651
6652end_breaklock:
6653 if( rc ){
6654 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006655 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006656 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006657 }
6658 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6659 }
6660 return rc;
6661}
6662
6663/* Take the requested lock on the conch file and break a stale lock if the
6664** host id matches.
6665*/
6666static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6667 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6668 unixFile *conchFile = pCtx->conchFile;
6669 int rc = SQLITE_OK;
6670 int nTries = 0;
6671 struct timespec conchModTime;
6672
drh3d4435b2011-08-26 20:55:50 +00006673 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006674 do {
6675 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6676 nTries ++;
6677 if( rc==SQLITE_BUSY ){
6678 /* If the lock failed (busy):
6679 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6680 * 2nd try: fail if the mod time changed or host id is different, wait
6681 * 10 sec and try again
6682 * 3rd try: break the lock unless the mod time has changed.
6683 */
6684 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006685 if( osFstat(conchFile->h, &buf) ){
drh7ed97b92010-01-20 13:07:21 +00006686 pFile->lastErrno = errno;
6687 return SQLITE_IOERR_LOCK;
6688 }
6689
6690 if( nTries==1 ){
6691 conchModTime = buf.st_mtimespec;
6692 usleep(500000); /* wait 0.5 sec and try the lock again*/
6693 continue;
6694 }
6695
6696 assert( nTries>1 );
6697 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6698 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6699 return SQLITE_BUSY;
6700 }
6701
6702 if( nTries==2 ){
6703 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006704 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006705 if( len<0 ){
6706 pFile->lastErrno = errno;
6707 return SQLITE_IOERR_LOCK;
6708 }
6709 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6710 /* don't break the lock if the host id doesn't match */
6711 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6712 return SQLITE_BUSY;
6713 }
6714 }else{
6715 /* don't break the lock on short read or a version mismatch */
6716 return SQLITE_BUSY;
6717 }
6718 usleep(10000000); /* wait 10 sec and try the lock again */
6719 continue;
6720 }
6721
6722 assert( nTries==3 );
6723 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6724 rc = SQLITE_OK;
6725 if( lockType==EXCLUSIVE_LOCK ){
6726 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
6727 }
6728 if( !rc ){
6729 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6730 }
6731 }
6732 }
6733 } while( rc==SQLITE_BUSY && nTries<3 );
6734
6735 return rc;
6736}
6737
6738/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006739** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6740** lockPath means that the lockPath in the conch file will be used if the
6741** host IDs match, or a new lock path will be generated automatically
6742** and written to the conch file.
6743*/
6744static int proxyTakeConch(unixFile *pFile){
6745 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6746
drh7ed97b92010-01-20 13:07:21 +00006747 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006748 return SQLITE_OK;
6749 }else{
6750 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006751 uuid_t myHostID;
6752 int pError = 0;
6753 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006754 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006755 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006756 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006757 int createConch = 0;
6758 int hostIdMatch = 0;
6759 int readLen = 0;
6760 int tryOldLockPath = 0;
6761 int forceNewLockPath = 0;
6762
drh308c2a52010-05-14 11:30:18 +00006763 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
6764 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00006765
drh7ed97b92010-01-20 13:07:21 +00006766 rc = proxyGetHostID(myHostID, &pError);
6767 if( (rc&0xff)==SQLITE_IOERR ){
6768 pFile->lastErrno = pError;
6769 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006770 }
drh7ed97b92010-01-20 13:07:21 +00006771 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006772 if( rc!=SQLITE_OK ){
6773 goto end_takeconch;
6774 }
drh7ed97b92010-01-20 13:07:21 +00006775 /* read the existing conch file */
6776 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6777 if( readLen<0 ){
6778 /* I/O error: lastErrno set by seekAndRead */
6779 pFile->lastErrno = conchFile->lastErrno;
6780 rc = SQLITE_IOERR_READ;
6781 goto end_takeconch;
6782 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6783 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6784 /* a short read or version format mismatch means we need to create a new
6785 ** conch file.
6786 */
6787 createConch = 1;
6788 }
6789 /* if the host id matches and the lock path already exists in the conch
6790 ** we'll try to use the path there, if we can't open that path, we'll
6791 ** retry with a new auto-generated path
6792 */
6793 do { /* in case we need to try again for an :auto: named lock file */
6794
6795 if( !createConch && !forceNewLockPath ){
6796 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6797 PROXY_HOSTIDLEN);
6798 /* if the conch has data compare the contents */
6799 if( !pCtx->lockProxyPath ){
6800 /* for auto-named local lock file, just check the host ID and we'll
6801 ** use the local lock file path that's already in there
6802 */
6803 if( hostIdMatch ){
6804 size_t pathLen = (readLen - PROXY_PATHINDEX);
6805
6806 if( pathLen>=MAXPATHLEN ){
6807 pathLen=MAXPATHLEN-1;
6808 }
6809 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6810 lockPath[pathLen] = 0;
6811 tempLockPath = lockPath;
6812 tryOldLockPath = 1;
6813 /* create a copy of the lock path if the conch is taken */
6814 goto end_takeconch;
6815 }
6816 }else if( hostIdMatch
6817 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6818 readLen-PROXY_PATHINDEX)
6819 ){
6820 /* conch host and lock path match */
6821 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006822 }
drh7ed97b92010-01-20 13:07:21 +00006823 }
6824
6825 /* if the conch isn't writable and doesn't match, we can't take it */
6826 if( (conchFile->openFlags&O_RDWR) == 0 ){
6827 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006828 goto end_takeconch;
6829 }
drh7ed97b92010-01-20 13:07:21 +00006830
6831 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006832 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006833 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6834 tempLockPath = lockPath;
6835 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006836 }
drh7ed97b92010-01-20 13:07:21 +00006837
6838 /* update conch with host and path (this will fail if other process
6839 ** has a shared lock already), if the host id matches, use the big
6840 ** stick.
drh715ff302008-12-03 22:32:44 +00006841 */
drh7ed97b92010-01-20 13:07:21 +00006842 futimes(conchFile->h, NULL);
6843 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006844 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006845 /* We are trying for an exclusive lock but another thread in this
6846 ** same process is still holding a shared lock. */
6847 rc = SQLITE_BUSY;
6848 } else {
6849 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006850 }
drh715ff302008-12-03 22:32:44 +00006851 }else{
drh7ed97b92010-01-20 13:07:21 +00006852 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006853 }
drh7ed97b92010-01-20 13:07:21 +00006854 if( rc==SQLITE_OK ){
6855 char writeBuffer[PROXY_MAXCONCHLEN];
6856 int writeSize = 0;
6857
6858 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6859 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6860 if( pCtx->lockProxyPath!=NULL ){
6861 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
6862 }else{
6863 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6864 }
6865 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006866 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006867 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6868 fsync(conchFile->h);
6869 /* If we created a new conch file (not just updated the contents of a
6870 ** valid conch file), try to match the permissions of the database
6871 */
6872 if( rc==SQLITE_OK && createConch ){
6873 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006874 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006875 if( err==0 ){
6876 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6877 S_IROTH|S_IWOTH);
6878 /* try to match the database file R/W permissions, ignore failure */
6879#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006880 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006881#else
drhff812312011-02-23 13:33:46 +00006882 do{
drhe562be52011-03-02 18:01:10 +00006883 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006884 }while( rc==(-1) && errno==EINTR );
6885 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006886 int code = errno;
6887 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6888 cmode, code, strerror(code));
6889 } else {
6890 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6891 }
6892 }else{
6893 int code = errno;
6894 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6895 err, code, strerror(code));
6896#endif
6897 }
drh715ff302008-12-03 22:32:44 +00006898 }
6899 }
drh7ed97b92010-01-20 13:07:21 +00006900 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6901
6902 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006903 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006904 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006905 int fd;
drh7ed97b92010-01-20 13:07:21 +00006906 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006907 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006908 }
6909 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006910 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006911 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006912 if( fd>=0 ){
6913 pFile->h = fd;
6914 }else{
drh9978c972010-02-23 17:36:32 +00006915 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006916 during locking */
6917 }
6918 }
6919 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6920 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6921 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6922 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6923 /* we couldn't create the proxy lock file with the old lock file path
6924 ** so try again via auto-naming
6925 */
6926 forceNewLockPath = 1;
6927 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006928 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006929 }
6930 }
6931 if( rc==SQLITE_OK ){
6932 /* Need to make a copy of path if we extracted the value
6933 ** from the conch file or the path was allocated on the stack
6934 */
6935 if( tempLockPath ){
6936 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6937 if( !pCtx->lockProxyPath ){
6938 rc = SQLITE_NOMEM;
6939 }
6940 }
6941 }
6942 if( rc==SQLITE_OK ){
6943 pCtx->conchHeld = 1;
6944
6945 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6946 afpLockingContext *afpCtx;
6947 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6948 afpCtx->dbPath = pCtx->lockProxyPath;
6949 }
6950 } else {
6951 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6952 }
drh308c2a52010-05-14 11:30:18 +00006953 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6954 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006955 return rc;
drh308c2a52010-05-14 11:30:18 +00006956 } while (1); /* in case we need to retry the :auto: lock file -
6957 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006958 }
6959}
6960
6961/*
6962** If pFile holds a lock on a conch file, then release that lock.
6963*/
6964static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00006965 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00006966 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
6967 unixFile *conchFile; /* Name of the conch file */
6968
6969 pCtx = (proxyLockingContext *)pFile->lockingContext;
6970 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00006971 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00006972 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh308c2a52010-05-14 11:30:18 +00006973 getpid()));
drh7ed97b92010-01-20 13:07:21 +00006974 if( pCtx->conchHeld>0 ){
6975 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6976 }
drh715ff302008-12-03 22:32:44 +00006977 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00006978 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
6979 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00006980 return rc;
6981}
6982
6983/*
6984** Given the name of a database file, compute the name of its conch file.
6985** Store the conch filename in memory obtained from sqlite3_malloc().
6986** Make *pConchPath point to the new name. Return SQLITE_OK on success
6987** or SQLITE_NOMEM if unable to obtain memory.
6988**
6989** The caller is responsible for ensuring that the allocated memory
6990** space is eventually freed.
6991**
6992** *pConchPath is set to NULL if a memory allocation error occurs.
6993*/
6994static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
6995 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00006996 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00006997 char *conchPath; /* buffer in which to construct conch name */
6998
6999 /* Allocate space for the conch filename and initialize the name to
7000 ** the name of the original database file. */
7001 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7002 if( conchPath==0 ){
7003 return SQLITE_NOMEM;
7004 }
7005 memcpy(conchPath, dbPath, len+1);
7006
7007 /* now insert a "." before the last / character */
7008 for( i=(len-1); i>=0; i-- ){
7009 if( conchPath[i]=='/' ){
7010 i++;
7011 break;
7012 }
7013 }
7014 conchPath[i]='.';
7015 while ( i<len ){
7016 conchPath[i+1]=dbPath[i];
7017 i++;
7018 }
7019
7020 /* append the "-conch" suffix to the file */
7021 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007022 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007023
7024 return SQLITE_OK;
7025}
7026
7027
7028/* Takes a fully configured proxy locking-style unix file and switches
7029** the local lock file path
7030*/
7031static int switchLockProxyPath(unixFile *pFile, const char *path) {
7032 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7033 char *oldPath = pCtx->lockProxyPath;
7034 int rc = SQLITE_OK;
7035
drh308c2a52010-05-14 11:30:18 +00007036 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007037 return SQLITE_BUSY;
7038 }
7039
7040 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7041 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7042 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7043 return SQLITE_OK;
7044 }else{
7045 unixFile *lockProxy = pCtx->lockProxy;
7046 pCtx->lockProxy=NULL;
7047 pCtx->conchHeld = 0;
7048 if( lockProxy!=NULL ){
7049 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7050 if( rc ) return rc;
7051 sqlite3_free(lockProxy);
7052 }
7053 sqlite3_free(oldPath);
7054 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7055 }
7056
7057 return rc;
7058}
7059
7060/*
7061** pFile is a file that has been opened by a prior xOpen call. dbPath
7062** is a string buffer at least MAXPATHLEN+1 characters in size.
7063**
7064** This routine find the filename associated with pFile and writes it
7065** int dbPath.
7066*/
7067static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007068#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007069 if( pFile->pMethod == &afpIoMethods ){
7070 /* afp style keeps a reference to the db path in the filePath field
7071 ** of the struct */
drhea678832008-12-10 19:26:22 +00007072 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007073 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
7074 } else
drh715ff302008-12-03 22:32:44 +00007075#endif
7076 if( pFile->pMethod == &dotlockIoMethods ){
7077 /* dot lock style uses the locking context to store the dot lock
7078 ** file path */
7079 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7080 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7081 }else{
7082 /* all other styles use the locking context to store the db file path */
7083 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007084 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007085 }
7086 return SQLITE_OK;
7087}
7088
7089/*
7090** Takes an already filled in unix file and alters it so all file locking
7091** will be performed on the local proxy lock file. The following fields
7092** are preserved in the locking context so that they can be restored and
7093** the unix structure properly cleaned up at close time:
7094** ->lockingContext
7095** ->pMethod
7096*/
7097static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7098 proxyLockingContext *pCtx;
7099 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7100 char *lockPath=NULL;
7101 int rc = SQLITE_OK;
7102
drh308c2a52010-05-14 11:30:18 +00007103 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007104 return SQLITE_BUSY;
7105 }
7106 proxyGetDbPathForUnixFile(pFile, dbPath);
7107 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7108 lockPath=NULL;
7109 }else{
7110 lockPath=(char *)path;
7111 }
7112
drh308c2a52010-05-14 11:30:18 +00007113 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
7114 (lockPath ? lockPath : ":auto:"), getpid()));
drh715ff302008-12-03 22:32:44 +00007115
7116 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7117 if( pCtx==0 ){
7118 return SQLITE_NOMEM;
7119 }
7120 memset(pCtx, 0, sizeof(*pCtx));
7121
7122 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7123 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007124 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7125 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7126 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7127 ** (c) the file system is read-only, then enable no-locking access.
7128 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7129 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7130 */
7131 struct statfs fsInfo;
7132 struct stat conchInfo;
7133 int goLockless = 0;
7134
drh99ab3b12011-03-02 15:09:07 +00007135 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007136 int err = errno;
7137 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7138 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7139 }
7140 }
7141 if( goLockless ){
7142 pCtx->conchHeld = -1; /* read only FS/ lockless */
7143 rc = SQLITE_OK;
7144 }
7145 }
drh715ff302008-12-03 22:32:44 +00007146 }
7147 if( rc==SQLITE_OK && lockPath ){
7148 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7149 }
7150
7151 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007152 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7153 if( pCtx->dbPath==NULL ){
7154 rc = SQLITE_NOMEM;
7155 }
7156 }
7157 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007158 /* all memory is allocated, proxys are created and assigned,
7159 ** switch the locking context and pMethod then return.
7160 */
drh715ff302008-12-03 22:32:44 +00007161 pCtx->oldLockingContext = pFile->lockingContext;
7162 pFile->lockingContext = pCtx;
7163 pCtx->pOldMethod = pFile->pMethod;
7164 pFile->pMethod = &proxyIoMethods;
7165 }else{
7166 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007167 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007168 sqlite3_free(pCtx->conchFile);
7169 }
drhd56b1212010-08-11 06:14:15 +00007170 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007171 sqlite3_free(pCtx->conchFilePath);
7172 sqlite3_free(pCtx);
7173 }
drh308c2a52010-05-14 11:30:18 +00007174 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7175 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007176 return rc;
7177}
7178
7179
7180/*
7181** This routine handles sqlite3_file_control() calls that are specific
7182** to proxy locking.
7183*/
7184static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7185 switch( op ){
7186 case SQLITE_GET_LOCKPROXYFILE: {
7187 unixFile *pFile = (unixFile*)id;
7188 if( pFile->pMethod == &proxyIoMethods ){
7189 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7190 proxyTakeConch(pFile);
7191 if( pCtx->lockProxyPath ){
7192 *(const char **)pArg = pCtx->lockProxyPath;
7193 }else{
7194 *(const char **)pArg = ":auto: (not held)";
7195 }
7196 } else {
7197 *(const char **)pArg = NULL;
7198 }
7199 return SQLITE_OK;
7200 }
7201 case SQLITE_SET_LOCKPROXYFILE: {
7202 unixFile *pFile = (unixFile*)id;
7203 int rc = SQLITE_OK;
7204 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7205 if( pArg==NULL || (const char *)pArg==0 ){
7206 if( isProxyStyle ){
7207 /* turn off proxy locking - not supported */
7208 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7209 }else{
7210 /* turn off proxy locking - already off - NOOP */
7211 rc = SQLITE_OK;
7212 }
7213 }else{
7214 const char *proxyPath = (const char *)pArg;
7215 if( isProxyStyle ){
7216 proxyLockingContext *pCtx =
7217 (proxyLockingContext*)pFile->lockingContext;
7218 if( !strcmp(pArg, ":auto:")
7219 || (pCtx->lockProxyPath &&
7220 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7221 ){
7222 rc = SQLITE_OK;
7223 }else{
7224 rc = switchLockProxyPath(pFile, proxyPath);
7225 }
7226 }else{
7227 /* turn on proxy file locking */
7228 rc = proxyTransformUnixFile(pFile, proxyPath);
7229 }
7230 }
7231 return rc;
7232 }
7233 default: {
7234 assert( 0 ); /* The call assures that only valid opcodes are sent */
7235 }
7236 }
7237 /*NOTREACHED*/
7238 return SQLITE_ERROR;
7239}
7240
7241/*
7242** Within this division (the proxying locking implementation) the procedures
7243** above this point are all utilities. The lock-related methods of the
7244** proxy-locking sqlite3_io_method object follow.
7245*/
7246
7247
7248/*
7249** This routine checks if there is a RESERVED lock held on the specified
7250** file by this or any other process. If such a lock is held, set *pResOut
7251** to a non-zero value otherwise *pResOut is set to zero. The return value
7252** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7253*/
7254static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7255 unixFile *pFile = (unixFile*)id;
7256 int rc = proxyTakeConch(pFile);
7257 if( rc==SQLITE_OK ){
7258 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007259 if( pCtx->conchHeld>0 ){
7260 unixFile *proxy = pCtx->lockProxy;
7261 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7262 }else{ /* conchHeld < 0 is lockless */
7263 pResOut=0;
7264 }
drh715ff302008-12-03 22:32:44 +00007265 }
7266 return rc;
7267}
7268
7269/*
drh308c2a52010-05-14 11:30:18 +00007270** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007271** of the following:
7272**
7273** (1) SHARED_LOCK
7274** (2) RESERVED_LOCK
7275** (3) PENDING_LOCK
7276** (4) EXCLUSIVE_LOCK
7277**
7278** Sometimes when requesting one lock state, additional lock states
7279** are inserted in between. The locking might fail on one of the later
7280** transitions leaving the lock state different from what it started but
7281** still short of its goal. The following chart shows the allowed
7282** transitions and the inserted intermediate states:
7283**
7284** UNLOCKED -> SHARED
7285** SHARED -> RESERVED
7286** SHARED -> (PENDING) -> EXCLUSIVE
7287** RESERVED -> (PENDING) -> EXCLUSIVE
7288** PENDING -> EXCLUSIVE
7289**
7290** This routine will only increase a lock. Use the sqlite3OsUnlock()
7291** routine to lower a locking level.
7292*/
drh308c2a52010-05-14 11:30:18 +00007293static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007294 unixFile *pFile = (unixFile*)id;
7295 int rc = proxyTakeConch(pFile);
7296 if( rc==SQLITE_OK ){
7297 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007298 if( pCtx->conchHeld>0 ){
7299 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007300 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7301 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007302 }else{
7303 /* conchHeld < 0 is lockless */
7304 }
drh715ff302008-12-03 22:32:44 +00007305 }
7306 return rc;
7307}
7308
7309
7310/*
drh308c2a52010-05-14 11:30:18 +00007311** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007312** must be either NO_LOCK or SHARED_LOCK.
7313**
7314** If the locking level of the file descriptor is already at or below
7315** the requested locking level, this routine is a no-op.
7316*/
drh308c2a52010-05-14 11:30:18 +00007317static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007318 unixFile *pFile = (unixFile*)id;
7319 int rc = proxyTakeConch(pFile);
7320 if( rc==SQLITE_OK ){
7321 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007322 if( pCtx->conchHeld>0 ){
7323 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007324 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7325 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007326 }else{
7327 /* conchHeld < 0 is lockless */
7328 }
drh715ff302008-12-03 22:32:44 +00007329 }
7330 return rc;
7331}
7332
7333/*
7334** Close a file that uses proxy locks.
7335*/
7336static int proxyClose(sqlite3_file *id) {
7337 if( id ){
7338 unixFile *pFile = (unixFile*)id;
7339 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7340 unixFile *lockProxy = pCtx->lockProxy;
7341 unixFile *conchFile = pCtx->conchFile;
7342 int rc = SQLITE_OK;
7343
7344 if( lockProxy ){
7345 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7346 if( rc ) return rc;
7347 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7348 if( rc ) return rc;
7349 sqlite3_free(lockProxy);
7350 pCtx->lockProxy = 0;
7351 }
7352 if( conchFile ){
7353 if( pCtx->conchHeld ){
7354 rc = proxyReleaseConch(pFile);
7355 if( rc ) return rc;
7356 }
7357 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7358 if( rc ) return rc;
7359 sqlite3_free(conchFile);
7360 }
drhd56b1212010-08-11 06:14:15 +00007361 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007362 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007363 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007364 /* restore the original locking context and pMethod then close it */
7365 pFile->lockingContext = pCtx->oldLockingContext;
7366 pFile->pMethod = pCtx->pOldMethod;
7367 sqlite3_free(pCtx);
7368 return pFile->pMethod->xClose(id);
7369 }
7370 return SQLITE_OK;
7371}
7372
7373
7374
drhd2cb50b2009-01-09 21:41:17 +00007375#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007376/*
7377** The proxy locking style is intended for use with AFP filesystems.
7378** And since AFP is only supported on MacOSX, the proxy locking is also
7379** restricted to MacOSX.
7380**
7381**
7382******************* End of the proxy lock implementation **********************
7383******************************************************************************/
7384
drh734c9862008-11-28 15:37:20 +00007385/*
danielk1977e339d652008-06-28 11:23:00 +00007386** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007387**
7388** This routine registers all VFS implementations for unix-like operating
7389** systems. This routine, and the sqlite3_os_end() routine that follows,
7390** should be the only routines in this file that are visible from other
7391** files.
drh6b9d6dd2008-12-03 19:34:47 +00007392**
7393** This routine is called once during SQLite initialization and by a
7394** single thread. The memory allocation and mutex subsystems have not
7395** necessarily been initialized when this routine is called, and so they
7396** should not be used.
drh153c62c2007-08-24 03:51:33 +00007397*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007398int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007399 /*
7400 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007401 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7402 ** to the "finder" function. (pAppData is a pointer to a pointer because
7403 ** silly C90 rules prohibit a void* from being cast to a function pointer
7404 ** and so we have to go through the intermediate pointer to avoid problems
7405 ** when compiling with -pedantic-errors on GCC.)
7406 **
7407 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007408 ** finder-function. The finder-function returns a pointer to the
7409 ** sqlite_io_methods object that implements the desired locking
7410 ** behaviors. See the division above that contains the IOMETHODS
7411 ** macro for addition information on finder-functions.
7412 **
7413 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7414 ** object. But the "autolockIoFinder" available on MacOSX does a little
7415 ** more than that; it looks at the filesystem type that hosts the
7416 ** database file and tries to choose an locking method appropriate for
7417 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007418 */
drh7708e972008-11-29 00:56:52 +00007419 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007420 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007421 sizeof(unixFile), /* szOsFile */ \
7422 MAX_PATHNAME, /* mxPathname */ \
7423 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007424 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007425 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007426 unixOpen, /* xOpen */ \
7427 unixDelete, /* xDelete */ \
7428 unixAccess, /* xAccess */ \
7429 unixFullPathname, /* xFullPathname */ \
7430 unixDlOpen, /* xDlOpen */ \
7431 unixDlError, /* xDlError */ \
7432 unixDlSym, /* xDlSym */ \
7433 unixDlClose, /* xDlClose */ \
7434 unixRandomness, /* xRandomness */ \
7435 unixSleep, /* xSleep */ \
7436 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007437 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007438 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007439 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007440 unixGetSystemCall, /* xGetSystemCall */ \
7441 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007442 }
7443
drh6b9d6dd2008-12-03 19:34:47 +00007444 /*
7445 ** All default VFSes for unix are contained in the following array.
7446 **
7447 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7448 ** by the SQLite core when the VFS is registered. So the following
7449 ** array cannot be const.
7450 */
danielk1977e339d652008-06-28 11:23:00 +00007451 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007452#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007453 UNIXVFS("unix", autolockIoFinder ),
7454#else
7455 UNIXVFS("unix", posixIoFinder ),
7456#endif
7457 UNIXVFS("unix-none", nolockIoFinder ),
7458 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007459 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007460#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007461 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007462#endif
7463#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007464 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007465#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007466 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007467#endif
chw78a13182009-04-07 05:35:03 +00007468#endif
drhd2cb50b2009-01-09 21:41:17 +00007469#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007470 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007471 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007472 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007473#endif
drh153c62c2007-08-24 03:51:33 +00007474 };
drh6b9d6dd2008-12-03 19:34:47 +00007475 unsigned int i; /* Loop counter */
7476
drh2aa5a002011-04-13 13:42:25 +00007477 /* Double-check that the aSyscall[] array has been constructed
7478 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007479 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007480
drh6b9d6dd2008-12-03 19:34:47 +00007481 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007482 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007483 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007484 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007485 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007486}
danielk1977e339d652008-06-28 11:23:00 +00007487
7488/*
drh6b9d6dd2008-12-03 19:34:47 +00007489** Shutdown the operating system interface.
7490**
7491** Some operating systems might need to do some cleanup in this routine,
7492** to release dynamically allocated objects. But not on unix.
7493** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007494*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007495int sqlite3_os_end(void){
7496 return SQLITE_OK;
7497}
drhdce8bdb2007-08-16 13:01:44 +00007498
danielk197729bafea2008-06-26 10:41:19 +00007499#endif /* SQLITE_OS_UNIX */