blob: d0924a511b165826147f039d9de654f9e6e1f657 [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/*
drh9cbe6352005-11-29 03:13:21 +000075** standard include files.
76*/
77#include <sys/types.h>
78#include <sys/stat.h>
79#include <fcntl.h>
80#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000081#include <time.h>
drh19e2d372005-08-29 23:00:03 +000082#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000083#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000084#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000085# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000086#endif
drh1da88f02011-12-17 16:09:16 +000087
drhe89b2912015-03-03 20:42:01 +000088#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +000090# include <sys/file.h>
91# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +000092#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000093
drhe89b2912015-03-03 20:42:01 +000094#if OS_VXWORKS
95# include <sys/ioctl.h>
96# include <semaphore.h>
97# include <limits.h>
98#endif /* OS_VXWORKS */
99
100#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000101# include <sys/mount.h>
102#endif
103
drhdbe4b882011-06-20 18:00:17 +0000104#ifdef HAVE_UTIME
105# include <utime.h>
106#endif
107
drh9cbe6352005-11-29 03:13:21 +0000108/*
drh7ed97b92010-01-20 13:07:21 +0000109** Allowed values of unixFile.fsFlags
110*/
111#define SQLITE_FSFLAGS_IS_MSDOS 0x1
112
113/*
drhf1a221e2006-01-15 17:27:17 +0000114** If we are to be thread-safe, include the pthreads header and define
115** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000116*/
drhd677b3d2007-08-20 22:48:41 +0000117#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000118# include <pthread.h>
119# define SQLITE_UNIX_THREADS 1
120#endif
121
122/*
123** Default permissions when creating a new file
124*/
125#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
126# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
127#endif
128
danielk1977b4b47412007-08-17 15:53:36 +0000129/*
drh5adc60b2012-04-14 13:25:11 +0000130** Default permissions when creating auto proxy dir
131*/
aswiftaebf4132008-11-21 00:10:35 +0000132#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
133# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
134#endif
135
136/*
danielk1977b4b47412007-08-17 15:53:36 +0000137** Maximum supported path-length.
138*/
139#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000140
drh91eb93c2015-03-03 19:56:20 +0000141/* Always cast the getpid() return type for compatibility with
142** kernel modules in VxWorks. */
143#define osGetpid(X) (pid_t)getpid()
144
drh734c9862008-11-28 15:37:20 +0000145/*
drh734c9862008-11-28 15:37:20 +0000146** Only set the lastErrno if the error code is a real error and not
147** a normal expected return code of SQLITE_BUSY or SQLITE_OK
148*/
149#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
150
drhd91c68f2010-05-14 14:52:25 +0000151/* Forward references */
152typedef struct unixShm unixShm; /* Connection shared memory */
153typedef struct unixShmNode unixShmNode; /* Shared memory instance */
154typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
155typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000156
157/*
dane946c392009-08-22 11:39:46 +0000158** Sometimes, after a file handle is closed by SQLite, the file descriptor
159** cannot be closed immediately. In these cases, instances of the following
160** structure are used to store the file descriptor while waiting for an
161** opportunity to either close or reuse it.
162*/
dane946c392009-08-22 11:39:46 +0000163struct UnixUnusedFd {
164 int fd; /* File descriptor to close */
165 int flags; /* Flags this file descriptor was opened with */
166 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
167};
168
169/*
drh9b35ea62008-11-29 02:20:26 +0000170** The unixFile structure is subclass of sqlite3_file specific to the unix
171** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000172*/
drh054889e2005-11-30 03:20:31 +0000173typedef struct unixFile unixFile;
174struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000175 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000176 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000177 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000178 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000179 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000180 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000181 int lastErrno; /* The unix errno from last I/O error */
182 void *lockingContext; /* Locking style specific state */
183 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000184 const char *zPath; /* Name of the file */
185 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000186 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000187#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000188 int nFetchOut; /* Number of outstanding xFetch refs */
189 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000190 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
191 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000192 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000193#endif
drh537dddf2012-10-26 13:46:24 +0000194#ifdef __QNXNTO__
195 int sectorSize; /* Device sector size */
196 int deviceCharacteristics; /* Precomputed device characteristics */
197#endif
drh08c6d442009-02-09 17:34:07 +0000198#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000199 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000200#endif
drh7ed97b92010-01-20 13:07:21 +0000201#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000202 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000203#endif
204#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000205 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000206#endif
drhd3d8c042012-05-29 17:02:40 +0000207#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000208 /* The next group of variables are used to track whether or not the
209 ** transaction counter in bytes 24-27 of database files are updated
210 ** whenever any part of the database changes. An assertion fault will
211 ** occur if a file is updated without also updating the transaction
212 ** counter. This test is made to avoid new problems similar to the
213 ** one described by ticket #3584.
214 */
215 unsigned char transCntrChng; /* True if the transaction counter changed */
216 unsigned char dbUpdate; /* True if any part of database file changed */
217 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000218
drh8f941bc2009-01-14 23:03:40 +0000219#endif
danf23da962013-03-23 21:00:41 +0000220
danielk1977967a4a12007-08-20 14:23:44 +0000221#ifdef SQLITE_TEST
222 /* In test mode, increase the size of this structure a bit so that
223 ** it is larger than the struct CrashFile defined in test6.c.
224 */
225 char aPadding[32];
226#endif
drh9cbe6352005-11-29 03:13:21 +0000227};
228
drhb00d8622014-01-01 15:18:36 +0000229/* This variable holds the process id (pid) from when the xRandomness()
230** method was called. If xOpen() is called from a different process id,
231** indicating that a fork() has occurred, the PRNG will be reset.
232*/
drh8cd5b252015-03-02 22:06:43 +0000233static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000234
drh0ccebe72005-06-07 22:22:50 +0000235/*
drha7e61d82011-03-12 17:02:57 +0000236** Allowed values for the unixFile.ctrlFlags bitmask:
237*/
drhf0b190d2011-07-26 16:03:07 +0000238#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
239#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
240#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000241#ifndef SQLITE_DISABLE_DIRSYNC
242# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
243#else
244# define UNIXFILE_DIRSYNC 0x00
245#endif
drhcb15f352011-12-23 01:04:17 +0000246#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000247#define UNIXFILE_DELETE 0x20 /* Delete on close */
248#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
249#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000250#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drhbbf76ee2015-03-10 20:22:35 +0000251#define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
drha7e61d82011-03-12 17:02:57 +0000252
253/*
drh198bf392006-01-06 21:52:49 +0000254** Include code that is common to all os_*.c files
255*/
256#include "os_common.h"
257
258/*
drh0ccebe72005-06-07 22:22:50 +0000259** Define various macros that are missing from some systems.
260*/
drhbbd42a62004-05-22 17:41:58 +0000261#ifndef O_LARGEFILE
262# define O_LARGEFILE 0
263#endif
264#ifdef SQLITE_DISABLE_LFS
265# undef O_LARGEFILE
266# define O_LARGEFILE 0
267#endif
268#ifndef O_NOFOLLOW
269# define O_NOFOLLOW 0
270#endif
271#ifndef O_BINARY
272# define O_BINARY 0
273#endif
274
275/*
drh2b4b5962005-06-15 17:47:55 +0000276** The threadid macro resolves to the thread-id or to 0. Used for
277** testing and debugging only.
278*/
drhd677b3d2007-08-20 22:48:41 +0000279#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000280#define threadid pthread_self()
281#else
282#define threadid 0
283#endif
284
drh99ab3b12011-03-02 15:09:07 +0000285/*
dane6ecd662013-04-01 17:56:59 +0000286** HAVE_MREMAP defaults to true on Linux and false everywhere else.
287*/
288#if !defined(HAVE_MREMAP)
289# if defined(__linux__) && defined(_GNU_SOURCE)
290# define HAVE_MREMAP 1
291# else
292# define HAVE_MREMAP 0
293# endif
294#endif
295
296/*
dan2ee53412014-09-06 16:49:40 +0000297** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
298** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
299*/
300#ifdef __ANDROID__
301# define lseek lseek64
302#endif
303
304/*
drh9a3baf12011-04-25 18:01:27 +0000305** Different Unix systems declare open() in different ways. Same use
306** open(const char*,int,mode_t). Others use open(const char*,int,...).
307** The difference is important when using a pointer to the function.
308**
309** The safest way to deal with the problem is to always use this wrapper
310** which always has the same well-defined interface.
311*/
312static int posixOpen(const char *zFile, int flags, int mode){
313 return open(zFile, flags, mode);
314}
315
drhed466822012-05-31 13:10:49 +0000316/*
317** On some systems, calls to fchown() will trigger a message in a security
318** log if they come from non-root processes. So avoid calling fchown() if
319** we are not running as root.
320*/
321static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000322#if OS_VXWORKS
323 return 0;
324#else
drhed466822012-05-31 13:10:49 +0000325 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000326#endif
drhed466822012-05-31 13:10:49 +0000327}
328
drh90315a22011-08-10 01:52:12 +0000329/* Forward reference */
330static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000331static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000332
drh9a3baf12011-04-25 18:01:27 +0000333/*
drh99ab3b12011-03-02 15:09:07 +0000334** Many system calls are accessed through pointer-to-functions so that
335** they may be overridden at runtime to facilitate fault injection during
336** testing and sandboxing. The following array holds the names and pointers
337** to all overrideable system calls.
338*/
339static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000340 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000341 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
342 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000343} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000344 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
345#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000346
drh58ad5802011-03-23 22:02:23 +0000347 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osClose ((int(*)(int))aSyscall[1].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
352
drh58ad5802011-03-23 22:02:23 +0000353 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
355
drh58ad5802011-03-23 22:02:23 +0000356 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000357#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
358
359/*
360** The DJGPP compiler environment looks mostly like Unix, but it
361** lacks the fcntl() system call. So redefine fcntl() to be something
362** that always succeeds. This means that locking does not occur under
363** DJGPP. But it is DOS - what did you expect?
364*/
365#ifdef __DJGPP__
366 { "fstat", 0, 0 },
367#define osFstat(a,b,c) 0
368#else
drh58ad5802011-03-23 22:02:23 +0000369 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
371#endif
372
drh58ad5802011-03-23 22:02:23 +0000373 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000378
drh58ad5802011-03-23 22:02:23 +0000379 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000380#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
381
drhe89b2912015-03-03 20:42:01 +0000382#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000383 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000384#else
drh58ad5802011-03-23 22:02:23 +0000385 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000386#endif
387#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
388
389#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000390 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000393#endif
394#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
395
drh58ad5802011-03-23 22:02:23 +0000396 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000397#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
398
drhe89b2912015-03-03 20:42:01 +0000399#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000400 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000401#else
drh58ad5802011-03-23 22:02:23 +0000402 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000403#endif
404#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
405 aSyscall[12].pCurrent)
406
407#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000409#else
drh58ad5802011-03-23 22:02:23 +0000410 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000411#endif
412#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
413 aSyscall[13].pCurrent)
414
drh58ad5802011-03-23 22:02:23 +0000415 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000416#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000417
418#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000419 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000420#else
drh58ad5802011-03-23 22:02:23 +0000421 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000422#endif
dan0fd7d862011-03-29 10:04:23 +0000423#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000424
drh036ac7f2011-08-08 23:18:05 +0000425 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
426#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
427
drh90315a22011-08-10 01:52:12 +0000428 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
429#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
430
drh9ef6bc42011-11-04 02:24:02 +0000431 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
432#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
433
434 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
435#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
436
drhed466822012-05-31 13:10:49 +0000437 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000438#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000439
dan4dd51442013-08-26 14:30:25 +0000440#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000441 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
442#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
443
drhd1ab8062013-03-25 20:50:25 +0000444 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
445#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
446
dane6ecd662013-04-01 17:56:59 +0000447#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000448 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
449#else
450 { "mremap", (sqlite3_syscall_ptr)0, 0 },
451#endif
452#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000453 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
454#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
455
dan702eec12014-06-23 10:04:58 +0000456#endif
457
drhe562be52011-03-02 18:01:10 +0000458}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000459
460/*
461** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000462** "unix" VFSes. Return SQLITE_OK opon successfully updating the
463** system call pointer, or SQLITE_NOTFOUND if there is no configurable
464** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000465*/
466static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000467 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
468 const char *zName, /* Name of system call to override */
469 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000470){
drh58ad5802011-03-23 22:02:23 +0000471 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000472 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000473
474 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000475 if( zName==0 ){
476 /* If no zName is given, restore all system calls to their default
477 ** settings and return NULL
478 */
dan51438a72011-04-02 17:00:47 +0000479 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000480 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
481 if( aSyscall[i].pDefault ){
482 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000483 }
484 }
485 }else{
486 /* If zName is specified, operate on only the one system call
487 ** specified.
488 */
489 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
490 if( strcmp(zName, aSyscall[i].zName)==0 ){
491 if( aSyscall[i].pDefault==0 ){
492 aSyscall[i].pDefault = aSyscall[i].pCurrent;
493 }
drh1df30962011-03-02 19:06:42 +0000494 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000495 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
496 aSyscall[i].pCurrent = pNewFunc;
497 break;
498 }
499 }
500 }
501 return rc;
502}
503
drh1df30962011-03-02 19:06:42 +0000504/*
505** Return the value of a system call. Return NULL if zName is not a
506** recognized system call name. NULL is also returned if the system call
507** is currently undefined.
508*/
drh58ad5802011-03-23 22:02:23 +0000509static sqlite3_syscall_ptr unixGetSystemCall(
510 sqlite3_vfs *pNotUsed,
511 const char *zName
512){
513 unsigned int i;
514
515 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000516 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
517 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
518 }
519 return 0;
520}
521
522/*
523** Return the name of the first system call after zName. If zName==NULL
524** then return the name of the first system call. Return NULL if zName
525** is the last system call or if zName is not the name of a valid
526** system call.
527*/
528static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000529 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000530
531 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000532 if( zName ){
533 for(i=0; i<ArraySize(aSyscall)-1; i++){
534 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000535 }
536 }
dan0fd7d862011-03-29 10:04:23 +0000537 for(i++; i<ArraySize(aSyscall); i++){
538 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000539 }
540 return 0;
541}
542
drhad4f1e52011-03-04 15:43:57 +0000543/*
drh77a3fdc2013-08-30 14:24:12 +0000544** Do not accept any file descriptor less than this value, in order to avoid
545** opening database file using file descriptors that are commonly used for
546** standard input, output, and error.
547*/
548#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
549# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
550#endif
551
552/*
drh8c815d12012-02-13 20:16:37 +0000553** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000554** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000555**
556** If the file creation mode "m" is 0 then set it to the default for
557** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
558** 0644) as modified by the system umask. If m is not 0, then
559** make the file creation mode be exactly m ignoring the umask.
560**
561** The m parameter will be non-zero only when creating -wal, -journal,
562** and -shm files. We want those files to have *exactly* the same
563** permissions as their original database, unadulterated by the umask.
564** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
565** transaction crashes and leaves behind hot journals, then any
566** process that is able to write to the database will also be able to
567** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000568*/
drh8c815d12012-02-13 20:16:37 +0000569static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000570 int fd;
drhe1186ab2013-01-04 20:45:13 +0000571 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000572 while(1){
drh5adc60b2012-04-14 13:25:11 +0000573#if defined(O_CLOEXEC)
574 fd = osOpen(z,f|O_CLOEXEC,m2);
575#else
576 fd = osOpen(z,f,m2);
577#endif
drh5128d002013-08-30 06:20:23 +0000578 if( fd<0 ){
579 if( errno==EINTR ) continue;
580 break;
581 }
drh77a3fdc2013-08-30 14:24:12 +0000582 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000583 osClose(fd);
584 sqlite3_log(SQLITE_WARNING,
585 "attempt to open \"%s\" as file descriptor %d", z, fd);
586 fd = -1;
587 if( osOpen("/dev/null", f, m)<0 ) break;
588 }
drhe1186ab2013-01-04 20:45:13 +0000589 if( fd>=0 ){
590 if( m!=0 ){
591 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000592 if( osFstat(fd, &statbuf)==0
593 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000594 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000595 ){
drhe1186ab2013-01-04 20:45:13 +0000596 osFchmod(fd, m);
597 }
598 }
drh5adc60b2012-04-14 13:25:11 +0000599#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000600 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000601#endif
drhe1186ab2013-01-04 20:45:13 +0000602 }
drh5adc60b2012-04-14 13:25:11 +0000603 return fd;
drhad4f1e52011-03-04 15:43:57 +0000604}
danielk197713adf8a2004-06-03 16:08:41 +0000605
drh107886a2008-11-21 22:21:50 +0000606/*
dan9359c7b2009-08-21 08:29:10 +0000607** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000608** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000609** vxworksFileId objects used by this file, all of which may be
610** shared by multiple threads.
611**
612** Function unixMutexHeld() is used to assert() that the global mutex
613** is held when required. This function is only used as part of assert()
614** statements. e.g.
615**
616** unixEnterMutex()
617** assert( unixMutexHeld() );
618** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000619*/
620static void unixEnterMutex(void){
621 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
622}
623static void unixLeaveMutex(void){
624 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
625}
dan9359c7b2009-08-21 08:29:10 +0000626#ifdef SQLITE_DEBUG
627static int unixMutexHeld(void) {
628 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
629}
630#endif
drh107886a2008-11-21 22:21:50 +0000631
drh734c9862008-11-28 15:37:20 +0000632
drh30ddce62011-10-15 00:16:30 +0000633#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000634/*
635** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000636** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000637** integer lock-type.
638*/
drh308c2a52010-05-14 11:30:18 +0000639static const char *azFileLock(int eFileLock){
640 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000641 case NO_LOCK: return "NONE";
642 case SHARED_LOCK: return "SHARED";
643 case RESERVED_LOCK: return "RESERVED";
644 case PENDING_LOCK: return "PENDING";
645 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000646 }
647 return "ERROR";
648}
649#endif
650
651#ifdef SQLITE_LOCK_TRACE
652/*
653** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000654**
drh734c9862008-11-28 15:37:20 +0000655** This routine is used for troubleshooting locks on multithreaded
656** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
657** command-line option on the compiler. This code is normally
658** turned off.
659*/
660static int lockTrace(int fd, int op, struct flock *p){
661 char *zOpName, *zType;
662 int s;
663 int savedErrno;
664 if( op==F_GETLK ){
665 zOpName = "GETLK";
666 }else if( op==F_SETLK ){
667 zOpName = "SETLK";
668 }else{
drh99ab3b12011-03-02 15:09:07 +0000669 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000670 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
671 return s;
672 }
673 if( p->l_type==F_RDLCK ){
674 zType = "RDLCK";
675 }else if( p->l_type==F_WRLCK ){
676 zType = "WRLCK";
677 }else if( p->l_type==F_UNLCK ){
678 zType = "UNLCK";
679 }else{
680 assert( 0 );
681 }
682 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000683 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000684 savedErrno = errno;
685 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
686 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
687 (int)p->l_pid, s);
688 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
689 struct flock l2;
690 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000691 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000692 if( l2.l_type==F_RDLCK ){
693 zType = "RDLCK";
694 }else if( l2.l_type==F_WRLCK ){
695 zType = "WRLCK";
696 }else if( l2.l_type==F_UNLCK ){
697 zType = "UNLCK";
698 }else{
699 assert( 0 );
700 }
701 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
702 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
703 }
704 errno = savedErrno;
705 return s;
706}
drh99ab3b12011-03-02 15:09:07 +0000707#undef osFcntl
708#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000709#endif /* SQLITE_LOCK_TRACE */
710
drhff812312011-02-23 13:33:46 +0000711/*
712** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000713**
drhe6d41732015-02-21 00:49:00 +0000714** All calls to ftruncate() within this file should be made through
715** this wrapper. On the Android platform, bypassing the logic below
716** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000717*/
drhff812312011-02-23 13:33:46 +0000718static int robust_ftruncate(int h, sqlite3_int64 sz){
719 int rc;
dan2ee53412014-09-06 16:49:40 +0000720#ifdef __ANDROID__
721 /* On Android, ftruncate() always uses 32-bit offsets, even if
722 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000723 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000724 ** such attempts. */
725 if( sz>(sqlite3_int64)0x7FFFFFFF ){
726 rc = SQLITE_OK;
727 }else
728#endif
drh99ab3b12011-03-02 15:09:07 +0000729 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000730 return rc;
731}
drh734c9862008-11-28 15:37:20 +0000732
733/*
734** This routine translates a standard POSIX errno code into something
735** useful to the clients of the sqlite3 functions. Specifically, it is
736** intended to translate a variety of "try again" errors into SQLITE_BUSY
737** and a variety of "please close the file descriptor NOW" errors into
738** SQLITE_IOERR
739**
740** Errors during initialization of locks, or file system support for locks,
741** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
742*/
743static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
744 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000745#if 0
746 /* At one point this code was not commented out. In theory, this branch
747 ** should never be hit, as this function should only be called after
748 ** a locking-related function (i.e. fcntl()) has returned non-zero with
749 ** the value of errno as the first argument. Since a system call has failed,
750 ** errno should be non-zero.
751 **
752 ** Despite this, if errno really is zero, we still don't want to return
753 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
754 ** propagated back to the caller. Commenting this branch out means errno==0
755 ** will be handled by the "default:" case below.
756 */
drh734c9862008-11-28 15:37:20 +0000757 case 0:
758 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000759#endif
760
drh734c9862008-11-28 15:37:20 +0000761 case EAGAIN:
762 case ETIMEDOUT:
763 case EBUSY:
764 case EINTR:
765 case ENOLCK:
766 /* random NFS retry error, unless during file system support
767 * introspection, in which it actually means what it says */
768 return SQLITE_BUSY;
769
770 case EACCES:
771 /* EACCES is like EAGAIN during locking operations, but not any other time*/
772 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000773 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
774 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
775 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000776 return SQLITE_BUSY;
777 }
778 /* else fall through */
779 case EPERM:
780 return SQLITE_PERM;
781
drh734c9862008-11-28 15:37:20 +0000782#if EOPNOTSUPP!=ENOTSUP
783 case EOPNOTSUPP:
784 /* something went terribly awry, unless during file system support
785 * introspection, in which it actually means what it says */
786#endif
787#ifdef ENOTSUP
788 case ENOTSUP:
789 /* invalid fd, unless during file system support introspection, in which
790 * it actually means what it says */
791#endif
792 case EIO:
793 case EBADF:
794 case EINVAL:
795 case ENOTCONN:
796 case ENODEV:
797 case ENXIO:
798 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000799#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000800 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000801#endif
drh734c9862008-11-28 15:37:20 +0000802 case ENOSYS:
803 /* these should force the client to close the file and reconnect */
804
805 default:
806 return sqliteIOErr;
807 }
808}
809
810
drh734c9862008-11-28 15:37:20 +0000811/******************************************************************************
812****************** Begin Unique File ID Utility Used By VxWorks ***************
813**
814** On most versions of unix, we can get a unique ID for a file by concatenating
815** the device number and the inode number. But this does not work on VxWorks.
816** On VxWorks, a unique file id must be based on the canonical filename.
817**
818** A pointer to an instance of the following structure can be used as a
819** unique file ID in VxWorks. Each instance of this structure contains
820** a copy of the canonical filename. There is also a reference count.
821** The structure is reclaimed when the number of pointers to it drops to
822** zero.
823**
824** There are never very many files open at one time and lookups are not
825** a performance-critical path, so it is sufficient to put these
826** structures on a linked list.
827*/
828struct vxworksFileId {
829 struct vxworksFileId *pNext; /* Next in a list of them all */
830 int nRef; /* Number of references to this one */
831 int nName; /* Length of the zCanonicalName[] string */
832 char *zCanonicalName; /* Canonical filename */
833};
834
835#if OS_VXWORKS
836/*
drh9b35ea62008-11-29 02:20:26 +0000837** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000838** variable:
839*/
840static struct vxworksFileId *vxworksFileList = 0;
841
842/*
843** Simplify a filename into its canonical form
844** by making the following changes:
845**
846** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000847** * convert /./ into just /
848** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000849**
850** Changes are made in-place. Return the new name length.
851**
852** The original filename is in z[0..n-1]. Return the number of
853** characters in the simplified name.
854*/
855static int vxworksSimplifyName(char *z, int n){
856 int i, j;
857 while( n>1 && z[n-1]=='/' ){ n--; }
858 for(i=j=0; i<n; i++){
859 if( z[i]=='/' ){
860 if( z[i+1]=='/' ) continue;
861 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
862 i += 1;
863 continue;
864 }
865 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
866 while( j>0 && z[j-1]!='/' ){ j--; }
867 if( j>0 ){ j--; }
868 i += 2;
869 continue;
870 }
871 }
872 z[j++] = z[i];
873 }
874 z[j] = 0;
875 return j;
876}
877
878/*
879** Find a unique file ID for the given absolute pathname. Return
880** a pointer to the vxworksFileId object. This pointer is the unique
881** file ID.
882**
883** The nRef field of the vxworksFileId object is incremented before
884** the object is returned. A new vxworksFileId object is created
885** and added to the global list if necessary.
886**
887** If a memory allocation error occurs, return NULL.
888*/
889static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
890 struct vxworksFileId *pNew; /* search key and new file ID */
891 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
892 int n; /* Length of zAbsoluteName string */
893
894 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000895 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000896 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
897 if( pNew==0 ) return 0;
898 pNew->zCanonicalName = (char*)&pNew[1];
899 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
900 n = vxworksSimplifyName(pNew->zCanonicalName, n);
901
902 /* Search for an existing entry that matching the canonical name.
903 ** If found, increment the reference count and return a pointer to
904 ** the existing file ID.
905 */
906 unixEnterMutex();
907 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
908 if( pCandidate->nName==n
909 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
910 ){
911 sqlite3_free(pNew);
912 pCandidate->nRef++;
913 unixLeaveMutex();
914 return pCandidate;
915 }
916 }
917
918 /* No match was found. We will make a new file ID */
919 pNew->nRef = 1;
920 pNew->nName = n;
921 pNew->pNext = vxworksFileList;
922 vxworksFileList = pNew;
923 unixLeaveMutex();
924 return pNew;
925}
926
927/*
928** Decrement the reference count on a vxworksFileId object. Free
929** the object when the reference count reaches zero.
930*/
931static void vxworksReleaseFileId(struct vxworksFileId *pId){
932 unixEnterMutex();
933 assert( pId->nRef>0 );
934 pId->nRef--;
935 if( pId->nRef==0 ){
936 struct vxworksFileId **pp;
937 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
938 assert( *pp==pId );
939 *pp = pId->pNext;
940 sqlite3_free(pId);
941 }
942 unixLeaveMutex();
943}
944#endif /* OS_VXWORKS */
945/*************** End of Unique File ID Utility Used By VxWorks ****************
946******************************************************************************/
947
948
949/******************************************************************************
950*************************** Posix Advisory Locking ****************************
951**
drh9b35ea62008-11-29 02:20:26 +0000952** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000953** section 6.5.2.2 lines 483 through 490 specify that when a process
954** sets or clears a lock, that operation overrides any prior locks set
955** by the same process. It does not explicitly say so, but this implies
956** that it overrides locks set by the same process using a different
957** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000958**
959** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000960** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
961**
962** Suppose ./file1 and ./file2 are really the same file (because
963** one is a hard or symbolic link to the other) then if you set
964** an exclusive lock on fd1, then try to get an exclusive lock
965** on fd2, it works. I would have expected the second lock to
966** fail since there was already a lock on the file due to fd1.
967** But not so. Since both locks came from the same process, the
968** second overrides the first, even though they were on different
969** file descriptors opened on different file names.
970**
drh734c9862008-11-28 15:37:20 +0000971** This means that we cannot use POSIX locks to synchronize file access
972** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000973** to synchronize access for threads in separate processes, but not
974** threads within the same process.
975**
976** To work around the problem, SQLite has to manage file locks internally
977** on its own. Whenever a new database is opened, we have to find the
978** specific inode of the database file (the inode is determined by the
979** st_dev and st_ino fields of the stat structure that fstat() fills in)
980** and check for locks already existing on that inode. When locks are
981** created or removed, we have to look at our own internal record of the
982** locks to see if another thread has previously set a lock on that same
983** inode.
984**
drh9b35ea62008-11-29 02:20:26 +0000985** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
986** For VxWorks, we have to use the alternative unique ID system based on
987** canonical filename and implemented in the previous division.)
988**
danielk1977ad94b582007-08-20 06:44:22 +0000989** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000990** descriptor. It is now a structure that holds the integer file
991** descriptor and a pointer to a structure that describes the internal
992** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000993** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000994** point to the same locking structure. The locking structure keeps
995** a reference count (so we will know when to delete it) and a "cnt"
996** field that tells us its internal lock status. cnt==0 means the
997** file is unlocked. cnt==-1 means the file has an exclusive lock.
998** cnt>0 means there are cnt shared locks on the file.
999**
1000** Any attempt to lock or unlock a file first checks the locking
1001** structure. The fcntl() system call is only invoked to set a
1002** POSIX lock if the internal lock structure transitions between
1003** a locked and an unlocked state.
1004**
drh734c9862008-11-28 15:37:20 +00001005** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001006**
1007** If you close a file descriptor that points to a file that has locks,
1008** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001009** released. To work around this problem, each unixInodeInfo object
1010** maintains a count of the number of pending locks on tha inode.
1011** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001012** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001013** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001014** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001015** be closed and that list is walked (and cleared) when the last lock
1016** clears.
1017**
drh9b35ea62008-11-29 02:20:26 +00001018** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001019**
drh9b35ea62008-11-29 02:20:26 +00001020** Many older versions of linux use the LinuxThreads library which is
1021** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001022** A cannot be modified or overridden by a different thread B.
1023** Only thread A can modify the lock. Locking behavior is correct
1024** if the appliation uses the newer Native Posix Thread Library (NPTL)
1025** on linux - with NPTL a lock created by thread A can override locks
1026** in thread B. But there is no way to know at compile-time which
1027** threading library is being used. So there is no way to know at
1028** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001029** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001030** current process.
drh5fdae772004-06-29 03:29:00 +00001031**
drh8af6c222010-05-14 12:43:01 +00001032** SQLite used to support LinuxThreads. But support for LinuxThreads
1033** was dropped beginning with version 3.7.0. SQLite will still work with
1034** LinuxThreads provided that (1) there is no more than one connection
1035** per database file in the same process and (2) database connections
1036** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001037*/
1038
1039/*
1040** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001041** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001042*/
1043struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001044 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001045#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001046 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001047#else
drh107886a2008-11-21 22:21:50 +00001048 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001049#endif
1050};
1051
1052/*
drhbbd42a62004-05-22 17:41:58 +00001053** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001054** inode. Or, on LinuxThreads, there is one of these structures for
1055** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001056**
danielk1977ad94b582007-08-20 06:44:22 +00001057** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001058** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001059** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001060*/
drh8af6c222010-05-14 12:43:01 +00001061struct unixInodeInfo {
1062 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001063 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001064 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1065 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001066 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001067 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1068 int nLock; /* Number of outstanding file locks */
1069 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1070 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1071 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001072#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001073 unsigned long long sharedByte; /* for AFP simulated shared lock */
1074#endif
drh6c7d5c52008-11-21 20:32:33 +00001075#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001076 sem_t *pSem; /* Named POSIX semaphore */
1077 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001078#endif
drhbbd42a62004-05-22 17:41:58 +00001079};
1080
drhda0e7682008-07-30 15:27:54 +00001081/*
drh8af6c222010-05-14 12:43:01 +00001082** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001083*/
drhd91c68f2010-05-14 14:52:25 +00001084static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001085
drh5fdae772004-06-29 03:29:00 +00001086/*
dane18d4952011-02-21 11:46:24 +00001087**
1088** This function - unixLogError_x(), is only ever called via the macro
1089** unixLogError().
1090**
1091** It is invoked after an error occurs in an OS function and errno has been
1092** set. It logs a message using sqlite3_log() containing the current value of
1093** errno and, if possible, the human-readable equivalent from strerror() or
1094** strerror_r().
1095**
1096** The first argument passed to the macro should be the error code that
1097** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1098** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001099** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001100** if any.
1101*/
drh0e9365c2011-03-02 02:08:13 +00001102#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1103static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001104 int errcode, /* SQLite error code */
1105 const char *zFunc, /* Name of OS function that failed */
1106 const char *zPath, /* File path associated with error */
1107 int iLine /* Source line number where error occurred */
1108){
1109 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001110 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001111
1112 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1113 ** the strerror() function to obtain the human-readable error message
1114 ** equivalent to errno. Otherwise, use strerror_r().
1115 */
1116#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1117 char aErr[80];
1118 memset(aErr, 0, sizeof(aErr));
1119 zErr = aErr;
1120
1121 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001122 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001123 ** returns a pointer to a buffer containing the error message. That pointer
1124 ** may point to aErr[], or it may point to some static storage somewhere.
1125 ** Otherwise, assume that the system provides the POSIX version of
1126 ** strerror_r(), which always writes an error message into aErr[].
1127 **
1128 ** If the code incorrectly assumes that it is the POSIX version that is
1129 ** available, the error message will often be an empty string. Not a
1130 ** huge problem. Incorrectly concluding that the GNU version is available
1131 ** could lead to a segfault though.
1132 */
1133#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1134 zErr =
1135# endif
drh0e9365c2011-03-02 02:08:13 +00001136 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001137
1138#elif SQLITE_THREADSAFE
1139 /* This is a threadsafe build, but strerror_r() is not available. */
1140 zErr = "";
1141#else
1142 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001143 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001144#endif
1145
drh0e9365c2011-03-02 02:08:13 +00001146 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001147 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001148 "os_unix.c:%d: (%d) %s(%s) - %s",
1149 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001150 );
1151
1152 return errcode;
1153}
1154
drh0e9365c2011-03-02 02:08:13 +00001155/*
1156** Close a file descriptor.
1157**
1158** We assume that close() almost always works, since it is only in a
1159** very sick application or on a very sick platform that it might fail.
1160** If it does fail, simply leak the file descriptor, but do log the
1161** error.
1162**
1163** Note that it is not safe to retry close() after EINTR since the
1164** file descriptor might have already been reused by another thread.
1165** So we don't even try to recover from an EINTR. Just log the error
1166** and move on.
1167*/
1168static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001169 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001170 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1171 pFile ? pFile->zPath : 0, lineno);
1172 }
1173}
dane18d4952011-02-21 11:46:24 +00001174
1175/*
drhe6d41732015-02-21 00:49:00 +00001176** Set the pFile->lastErrno. Do this in a subroutine as that provides
1177** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001178*/
1179static void storeLastErrno(unixFile *pFile, int error){
1180 pFile->lastErrno = error;
1181}
1182
1183/*
danb0ac3e32010-06-16 10:55:42 +00001184** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001185*/
drh0e9365c2011-03-02 02:08:13 +00001186static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001187 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001188 UnixUnusedFd *p;
1189 UnixUnusedFd *pNext;
1190 for(p=pInode->pUnused; p; p=pNext){
1191 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001192 robust_close(pFile, p->fd, __LINE__);
1193 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001194 }
drh0e9365c2011-03-02 02:08:13 +00001195 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001196}
1197
1198/*
drh8af6c222010-05-14 12:43:01 +00001199** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001200**
1201** The mutex entered using the unixEnterMutex() function must be held
1202** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001203*/
danb0ac3e32010-06-16 10:55:42 +00001204static void releaseInodeInfo(unixFile *pFile){
1205 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001206 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001207 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001208 pInode->nRef--;
1209 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001210 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001211 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001212 if( pInode->pPrev ){
1213 assert( pInode->pPrev->pNext==pInode );
1214 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001215 }else{
drh8af6c222010-05-14 12:43:01 +00001216 assert( inodeList==pInode );
1217 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001218 }
drh8af6c222010-05-14 12:43:01 +00001219 if( pInode->pNext ){
1220 assert( pInode->pNext->pPrev==pInode );
1221 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001222 }
drh8af6c222010-05-14 12:43:01 +00001223 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001224 }
drhbbd42a62004-05-22 17:41:58 +00001225 }
1226}
1227
1228/*
drh8af6c222010-05-14 12:43:01 +00001229** Given a file descriptor, locate the unixInodeInfo object that
1230** describes that file descriptor. Create a new one if necessary. The
1231** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001232**
dan9359c7b2009-08-21 08:29:10 +00001233** The mutex entered using the unixEnterMutex() function must be held
1234** when this function is called.
1235**
drh6c7d5c52008-11-21 20:32:33 +00001236** Return an appropriate error code.
1237*/
drh8af6c222010-05-14 12:43:01 +00001238static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001239 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001240 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001241){
1242 int rc; /* System call return code */
1243 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001244 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1245 struct stat statbuf; /* Low-level file information */
1246 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001247
dan9359c7b2009-08-21 08:29:10 +00001248 assert( unixMutexHeld() );
1249
drh6c7d5c52008-11-21 20:32:33 +00001250 /* Get low-level information about the file that we can used to
1251 ** create a unique name for the file.
1252 */
1253 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001256 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001257#ifdef EOVERFLOW
1258 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1259#endif
1260 return SQLITE_IOERR;
1261 }
1262
drheb0d74f2009-02-03 15:27:02 +00001263#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001264 /* On OS X on an msdos filesystem, the inode number is reported
1265 ** incorrectly for zero-size files. See ticket #3260. To work
1266 ** around this problem (we consider it a bug in OS X, not SQLite)
1267 ** we always increase the file size to 1 by writing a single byte
1268 ** prior to accessing the inode number. The one byte written is
1269 ** an ASCII 'S' character which also happens to be the first byte
1270 ** in the header of every SQLite database. In this way, if there
1271 ** is a race condition such that another thread has already populated
1272 ** the first page of the database, no damage is done.
1273 */
drh7ed97b92010-01-20 13:07:21 +00001274 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001275 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001276 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001277 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001278 return SQLITE_IOERR;
1279 }
drh99ab3b12011-03-02 15:09:07 +00001280 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001281 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001282 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001283 return SQLITE_IOERR;
1284 }
1285 }
drheb0d74f2009-02-03 15:27:02 +00001286#endif
drh6c7d5c52008-11-21 20:32:33 +00001287
drh8af6c222010-05-14 12:43:01 +00001288 memset(&fileId, 0, sizeof(fileId));
1289 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001290#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001291 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001292#else
drh8af6c222010-05-14 12:43:01 +00001293 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001294#endif
drh8af6c222010-05-14 12:43:01 +00001295 pInode = inodeList;
1296 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1297 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001298 }
drh8af6c222010-05-14 12:43:01 +00001299 if( pInode==0 ){
1300 pInode = sqlite3_malloc( sizeof(*pInode) );
1301 if( pInode==0 ){
1302 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001303 }
drh8af6c222010-05-14 12:43:01 +00001304 memset(pInode, 0, sizeof(*pInode));
1305 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1306 pInode->nRef = 1;
1307 pInode->pNext = inodeList;
1308 pInode->pPrev = 0;
1309 if( inodeList ) inodeList->pPrev = pInode;
1310 inodeList = pInode;
1311 }else{
1312 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001313 }
drh8af6c222010-05-14 12:43:01 +00001314 *ppInode = pInode;
1315 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001316}
drh6c7d5c52008-11-21 20:32:33 +00001317
drhb959a012013-12-07 12:29:22 +00001318/*
1319** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1320*/
1321static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001322#if OS_VXWORKS
1323 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1324#else
drhb959a012013-12-07 12:29:22 +00001325 struct stat buf;
1326 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001327 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001328#endif
drhb959a012013-12-07 12:29:22 +00001329}
1330
aswift5b1a2562008-08-22 00:22:35 +00001331
1332/*
drhfbc7e882013-04-11 01:16:15 +00001333** Check a unixFile that is a database. Verify the following:
1334**
1335** (1) There is exactly one hard link on the file
1336** (2) The file is not a symbolic link
1337** (3) The file has not been renamed or unlinked
1338**
1339** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1340*/
1341static void verifyDbFile(unixFile *pFile){
1342 struct stat buf;
1343 int rc;
drh3044b512014-06-16 16:41:52 +00001344 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1345 /* One or more of the following warnings have already been issued. Do not
1346 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001347 return;
1348 }
1349 rc = osFstat(pFile->h, &buf);
1350 if( rc!=0 ){
1351 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1352 pFile->ctrlFlags |= UNIXFILE_WARNED;
1353 return;
1354 }
drh3044b512014-06-16 16:41:52 +00001355 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001356 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1357 pFile->ctrlFlags |= UNIXFILE_WARNED;
1358 return;
1359 }
1360 if( buf.st_nlink>1 ){
1361 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1362 pFile->ctrlFlags |= UNIXFILE_WARNED;
1363 return;
1364 }
drhb959a012013-12-07 12:29:22 +00001365 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001366 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1367 pFile->ctrlFlags |= UNIXFILE_WARNED;
1368 return;
1369 }
1370}
1371
1372
1373/*
danielk197713adf8a2004-06-03 16:08:41 +00001374** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001375** file by this or any other process. If such a lock is held, set *pResOut
1376** to a non-zero value otherwise *pResOut is set to zero. The return value
1377** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001378*/
danielk1977861f7452008-06-05 11:39:11 +00001379static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001380 int rc = SQLITE_OK;
1381 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001382 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001383
danielk1977861f7452008-06-05 11:39:11 +00001384 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1385
drh054889e2005-11-30 03:20:31 +00001386 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001387 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001388
1389 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001390 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001391 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001392 }
1393
drh2ac3ee92004-06-07 16:27:46 +00001394 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001395 */
danielk197709480a92009-02-09 05:32:32 +00001396#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001397 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001398 struct flock lock;
1399 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001400 lock.l_start = RESERVED_BYTE;
1401 lock.l_len = 1;
1402 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001403 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1404 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001405 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001406 } else if( lock.l_type!=F_UNLCK ){
1407 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001408 }
1409 }
danielk197709480a92009-02-09 05:32:32 +00001410#endif
danielk197713adf8a2004-06-03 16:08:41 +00001411
drh6c7d5c52008-11-21 20:32:33 +00001412 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001413 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001414
aswift5b1a2562008-08-22 00:22:35 +00001415 *pResOut = reserved;
1416 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001417}
1418
1419/*
drha7e61d82011-03-12 17:02:57 +00001420** Attempt to set a system-lock on the file pFile. The lock is
1421** described by pLock.
1422**
drh77197112011-03-15 19:08:48 +00001423** If the pFile was opened read/write from unix-excl, then the only lock
1424** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001425** the first time any lock is attempted. All subsequent system locking
1426** operations become no-ops. Locking operations still happen internally,
1427** in order to coordinate access between separate database connections
1428** within this process, but all of that is handled in memory and the
1429** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001430**
1431** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1432** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1433** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001434**
1435** Zero is returned if the call completes successfully, or -1 if a call
1436** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001437*/
1438static int unixFileLock(unixFile *pFile, struct flock *pLock){
1439 int rc;
drh3cb93392011-03-12 18:10:44 +00001440 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001441 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001442 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001443 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1444 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1445 ){
drh3cb93392011-03-12 18:10:44 +00001446 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001447 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001448 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001449 lock.l_whence = SEEK_SET;
1450 lock.l_start = SHARED_FIRST;
1451 lock.l_len = SHARED_SIZE;
1452 lock.l_type = F_WRLCK;
1453 rc = osFcntl(pFile->h, F_SETLK, &lock);
1454 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001455 pInode->bProcessLock = 1;
1456 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001457 }else{
1458 rc = 0;
1459 }
1460 }else{
1461 rc = osFcntl(pFile->h, F_SETLK, pLock);
1462 }
1463 return rc;
1464}
1465
1466/*
drh308c2a52010-05-14 11:30:18 +00001467** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001468** of the following:
1469**
drh2ac3ee92004-06-07 16:27:46 +00001470** (1) SHARED_LOCK
1471** (2) RESERVED_LOCK
1472** (3) PENDING_LOCK
1473** (4) EXCLUSIVE_LOCK
1474**
drhb3e04342004-06-08 00:47:47 +00001475** Sometimes when requesting one lock state, additional lock states
1476** are inserted in between. The locking might fail on one of the later
1477** transitions leaving the lock state different from what it started but
1478** still short of its goal. The following chart shows the allowed
1479** transitions and the inserted intermediate states:
1480**
1481** UNLOCKED -> SHARED
1482** SHARED -> RESERVED
1483** SHARED -> (PENDING) -> EXCLUSIVE
1484** RESERVED -> (PENDING) -> EXCLUSIVE
1485** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001486**
drha6abd042004-06-09 17:37:22 +00001487** This routine will only increase a lock. Use the sqlite3OsUnlock()
1488** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001489*/
drh308c2a52010-05-14 11:30:18 +00001490static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001491 /* The following describes the implementation of the various locks and
1492 ** lock transitions in terms of the POSIX advisory shared and exclusive
1493 ** lock primitives (called read-locks and write-locks below, to avoid
1494 ** confusion with SQLite lock names). The algorithms are complicated
1495 ** slightly in order to be compatible with windows systems simultaneously
1496 ** accessing the same database file, in case that is ever required.
1497 **
1498 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1499 ** byte', each single bytes at well known offsets, and the 'shared byte
1500 ** range', a range of 510 bytes at a well known offset.
1501 **
1502 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1503 ** byte'. If this is successful, a random byte from the 'shared byte
1504 ** range' is read-locked and the lock on the 'pending byte' released.
1505 **
danielk197790ba3bd2004-06-25 08:32:25 +00001506 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1507 ** A RESERVED lock is implemented by grabbing a write-lock on the
1508 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001509 **
1510 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001511 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1512 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1513 ** obtained, but existing SHARED locks are allowed to persist. A process
1514 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1515 ** This property is used by the algorithm for rolling back a journal file
1516 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001517 **
danielk197790ba3bd2004-06-25 08:32:25 +00001518 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1519 ** implemented by obtaining a write-lock on the entire 'shared byte
1520 ** range'. Since all other locks require a read-lock on one of the bytes
1521 ** within this range, this ensures that no other locks are held on the
1522 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001523 **
1524 ** The reason a single byte cannot be used instead of the 'shared byte
1525 ** range' is that some versions of windows do not support read-locks. By
1526 ** locking a random byte from a range, concurrent SHARED locks may exist
1527 ** even if the locking primitive used is always a write-lock.
1528 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001529 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001530 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001531 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001533 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001534
drh054889e2005-11-30 03:20:31 +00001535 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001536 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1537 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001538 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1539 osGetpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001540
1541 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001542 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001543 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001544 */
drh308c2a52010-05-14 11:30:18 +00001545 if( pFile->eFileLock>=eFileLock ){
1546 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1547 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001548 return SQLITE_OK;
1549 }
1550
drh0c2694b2009-09-03 16:23:44 +00001551 /* Make sure the locking sequence is correct.
1552 ** (1) We never move from unlocked to anything higher than shared lock.
1553 ** (2) SQLite never explicitly requests a pendig lock.
1554 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001555 */
drh308c2a52010-05-14 11:30:18 +00001556 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1557 assert( eFileLock!=PENDING_LOCK );
1558 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001559
drh8af6c222010-05-14 12:43:01 +00001560 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001561 */
drh6c7d5c52008-11-21 20:32:33 +00001562 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001563 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001564
danielk1977ad94b582007-08-20 06:44:22 +00001565 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001566 ** handle that precludes the requested lock, return BUSY.
1567 */
drh8af6c222010-05-14 12:43:01 +00001568 if( (pFile->eFileLock!=pInode->eFileLock &&
1569 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001570 ){
1571 rc = SQLITE_BUSY;
1572 goto end_lock;
1573 }
1574
1575 /* If a SHARED lock is requested, and some thread using this PID already
1576 ** has a SHARED or RESERVED lock, then increment reference counts and
1577 ** return SQLITE_OK.
1578 */
drh308c2a52010-05-14 11:30:18 +00001579 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001580 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001581 assert( eFileLock==SHARED_LOCK );
1582 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001584 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001585 pInode->nShared++;
1586 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 goto end_lock;
1588 }
1589
danielk19779a1d0ab2004-06-01 14:09:28 +00001590
drh3cde3bb2004-06-12 02:17:14 +00001591 /* A PENDING lock is needed before acquiring a SHARED lock and before
1592 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1593 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001594 */
drh0c2694b2009-09-03 16:23:44 +00001595 lock.l_len = 1L;
1596 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001597 if( eFileLock==SHARED_LOCK
1598 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001599 ){
drh308c2a52010-05-14 11:30:18 +00001600 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001601 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001602 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001603 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001604 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001605 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001606 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001607 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001608 goto end_lock;
1609 }
drh3cde3bb2004-06-12 02:17:14 +00001610 }
1611
1612
1613 /* If control gets to this point, then actually go ahead and make
1614 ** operating system calls for the specified lock.
1615 */
drh308c2a52010-05-14 11:30:18 +00001616 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001617 assert( pInode->nShared==0 );
1618 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001619 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001620
drh2ac3ee92004-06-07 16:27:46 +00001621 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001622 lock.l_start = SHARED_FIRST;
1623 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001624 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001625 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001626 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001627 }
dan661d71a2011-03-30 19:08:03 +00001628
drh2ac3ee92004-06-07 16:27:46 +00001629 /* Drop the temporary PENDING lock */
1630 lock.l_start = PENDING_BYTE;
1631 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001633 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1634 /* This could happen with a network mount */
1635 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001636 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001637 }
dan661d71a2011-03-30 19:08:03 +00001638
1639 if( rc ){
1640 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001641 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001642 }
dan661d71a2011-03-30 19:08:03 +00001643 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001644 }else{
drh308c2a52010-05-14 11:30:18 +00001645 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001646 pInode->nLock++;
1647 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001648 }
drh8af6c222010-05-14 12:43:01 +00001649 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001650 /* We are trying for an exclusive lock but another thread in this
1651 ** same process is still holding a shared lock. */
1652 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001653 }else{
drh3cde3bb2004-06-12 02:17:14 +00001654 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001655 ** assumed that there is a SHARED or greater lock on the file
1656 ** already.
1657 */
drh308c2a52010-05-14 11:30:18 +00001658 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001659 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001660
1661 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1662 if( eFileLock==RESERVED_LOCK ){
1663 lock.l_start = RESERVED_BYTE;
1664 lock.l_len = 1L;
1665 }else{
1666 lock.l_start = SHARED_FIRST;
1667 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001668 }
dan661d71a2011-03-30 19:08:03 +00001669
1670 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001671 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001672 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001673 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001674 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001675 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001676 }
drhbbd42a62004-05-22 17:41:58 +00001677 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001678
drh8f941bc2009-01-14 23:03:40 +00001679
drhd3d8c042012-05-29 17:02:40 +00001680#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001681 /* Set up the transaction-counter change checking flags when
1682 ** transitioning from a SHARED to a RESERVED lock. The change
1683 ** from SHARED to RESERVED marks the beginning of a normal
1684 ** write operation (not a hot journal rollback).
1685 */
1686 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001687 && pFile->eFileLock<=SHARED_LOCK
1688 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001689 ){
1690 pFile->transCntrChng = 0;
1691 pFile->dbUpdate = 0;
1692 pFile->inNormalWrite = 1;
1693 }
1694#endif
1695
1696
danielk1977ecb2a962004-06-02 06:30:16 +00001697 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001698 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001699 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001700 }else if( eFileLock==EXCLUSIVE_LOCK ){
1701 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001702 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001703 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001704
1705end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001706 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001707 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1708 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001709 return rc;
1710}
1711
1712/*
dan08da86a2009-08-21 17:18:03 +00001713** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001714** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001715*/
1716static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001717 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001718 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001719 p->pNext = pInode->pUnused;
1720 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001721 pFile->h = -1;
1722 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001723}
1724
1725/*
drh308c2a52010-05-14 11:30:18 +00001726** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001727** must be either NO_LOCK or SHARED_LOCK.
1728**
1729** If the locking level of the file descriptor is already at or below
1730** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001731**
1732** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1733** the byte range is divided into 2 parts and the first part is unlocked then
1734** set to a read lock, then the other part is simply unlocked. This works
1735** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1736** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001737*/
drha7e61d82011-03-12 17:02:57 +00001738static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001739 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001740 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001741 struct flock lock;
1742 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001743
drh054889e2005-11-30 03:20:31 +00001744 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001745 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001746 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh91eb93c2015-03-03 19:56:20 +00001747 osGetpid()));
drha6abd042004-06-09 17:37:22 +00001748
drh308c2a52010-05-14 11:30:18 +00001749 assert( eFileLock<=SHARED_LOCK );
1750 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001751 return SQLITE_OK;
1752 }
drh6c7d5c52008-11-21 20:32:33 +00001753 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001754 pInode = pFile->pInode;
1755 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001756 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001757 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001758
drhd3d8c042012-05-29 17:02:40 +00001759#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001760 /* When reducing a lock such that other processes can start
1761 ** reading the database file again, make sure that the
1762 ** transaction counter was updated if any part of the database
1763 ** file changed. If the transaction counter is not updated,
1764 ** other connections to the same file might not realize that
1765 ** the file has changed and hence might not know to flush their
1766 ** cache. The use of a stale cache can lead to database corruption.
1767 */
drh8f941bc2009-01-14 23:03:40 +00001768 pFile->inNormalWrite = 0;
1769#endif
1770
drh7ed97b92010-01-20 13:07:21 +00001771 /* downgrading to a shared lock on NFS involves clearing the write lock
1772 ** before establishing the readlock - to avoid a race condition we downgrade
1773 ** the lock in 2 blocks, so that part of the range will be covered by a
1774 ** write lock until the rest is covered by a read lock:
1775 ** 1: [WWWWW]
1776 ** 2: [....W]
1777 ** 3: [RRRRW]
1778 ** 4: [RRRR.]
1779 */
drh308c2a52010-05-14 11:30:18 +00001780 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001781#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001782 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001783 assert( handleNFSUnlock==0 );
1784#endif
1785#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001786 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001787 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001788 off_t divSize = SHARED_SIZE - 1;
1789
1790 lock.l_type = F_UNLCK;
1791 lock.l_whence = SEEK_SET;
1792 lock.l_start = SHARED_FIRST;
1793 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001794 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001795 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001796 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001797 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001798 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001799 }
1800 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001801 }
drh7ed97b92010-01-20 13:07:21 +00001802 lock.l_type = F_RDLCK;
1803 lock.l_whence = SEEK_SET;
1804 lock.l_start = SHARED_FIRST;
1805 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001806 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001807 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001808 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1809 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001810 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001811 }
1812 goto end_unlock;
1813 }
1814 lock.l_type = F_UNLCK;
1815 lock.l_whence = SEEK_SET;
1816 lock.l_start = SHARED_FIRST+divSize;
1817 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001818 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001819 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001820 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001821 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001822 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001823 }
1824 goto end_unlock;
1825 }
drh30f776f2011-02-25 03:25:07 +00001826 }else
1827#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1828 {
drh7ed97b92010-01-20 13:07:21 +00001829 lock.l_type = F_RDLCK;
1830 lock.l_whence = SEEK_SET;
1831 lock.l_start = SHARED_FIRST;
1832 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001833 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001834 /* In theory, the call to unixFileLock() cannot fail because another
1835 ** process is holding an incompatible lock. If it does, this
1836 ** indicates that the other process is not following the locking
1837 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1838 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1839 ** an assert to fail). */
1840 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001841 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001842 goto end_unlock;
1843 }
drh9c105bb2004-10-02 20:38:28 +00001844 }
1845 }
drhbbd42a62004-05-22 17:41:58 +00001846 lock.l_type = F_UNLCK;
1847 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001848 lock.l_start = PENDING_BYTE;
1849 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001850 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001851 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001852 }else{
danea83bc62011-04-01 11:56:32 +00001853 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001854 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001855 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001856 }
drhbbd42a62004-05-22 17:41:58 +00001857 }
drh308c2a52010-05-14 11:30:18 +00001858 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001859 /* Decrement the shared lock counter. Release the lock using an
1860 ** OS call only when all threads in this same process have released
1861 ** the lock.
1862 */
drh8af6c222010-05-14 12:43:01 +00001863 pInode->nShared--;
1864 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001865 lock.l_type = F_UNLCK;
1866 lock.l_whence = SEEK_SET;
1867 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001868 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001869 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001870 }else{
danea83bc62011-04-01 11:56:32 +00001871 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001872 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001873 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001874 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001875 }
drha6abd042004-06-09 17:37:22 +00001876 }
1877
drhbbd42a62004-05-22 17:41:58 +00001878 /* Decrement the count of locks against this same file. When the
1879 ** count reaches zero, close any other file descriptors whose close
1880 ** was deferred because of outstanding locks.
1881 */
drh8af6c222010-05-14 12:43:01 +00001882 pInode->nLock--;
1883 assert( pInode->nLock>=0 );
1884 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001885 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001886 }
1887 }
drhf2f105d2012-08-20 15:53:54 +00001888
aswift5b1a2562008-08-22 00:22:35 +00001889end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001890 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001891 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001892 return rc;
drhbbd42a62004-05-22 17:41:58 +00001893}
1894
1895/*
drh308c2a52010-05-14 11:30:18 +00001896** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001897** must be either NO_LOCK or SHARED_LOCK.
1898**
1899** If the locking level of the file descriptor is already at or below
1900** the requested locking level, this routine is a no-op.
1901*/
drh308c2a52010-05-14 11:30:18 +00001902static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001903#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001904 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001905#endif
drha7e61d82011-03-12 17:02:57 +00001906 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001907}
1908
mistachkine98844f2013-08-24 00:59:24 +00001909#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001910static int unixMapfile(unixFile *pFd, i64 nByte);
1911static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001912#endif
danf23da962013-03-23 21:00:41 +00001913
drh7ed97b92010-01-20 13:07:21 +00001914/*
danielk1977e339d652008-06-28 11:23:00 +00001915** This function performs the parts of the "close file" operation
1916** common to all locking schemes. It closes the directory and file
1917** handles, if they are valid, and sets all fields of the unixFile
1918** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001919**
1920** It is *not* necessary to hold the mutex when this routine is called,
1921** even on VxWorks. A mutex will be acquired on VxWorks by the
1922** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001923*/
1924static int closeUnixFile(sqlite3_file *id){
1925 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001926#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001927 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001928#endif
dan661d71a2011-03-30 19:08:03 +00001929 if( pFile->h>=0 ){
1930 robust_close(pFile, pFile->h, __LINE__);
1931 pFile->h = -1;
1932 }
1933#if OS_VXWORKS
1934 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001935 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001936 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001937 }
1938 vxworksReleaseFileId(pFile->pId);
1939 pFile->pId = 0;
1940 }
1941#endif
drh0bdbc902014-06-16 18:35:06 +00001942#ifdef SQLITE_UNLINK_AFTER_CLOSE
1943 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1944 osUnlink(pFile->zPath);
1945 sqlite3_free(*(char**)&pFile->zPath);
1946 pFile->zPath = 0;
1947 }
1948#endif
dan661d71a2011-03-30 19:08:03 +00001949 OSTRACE(("CLOSE %-3d\n", pFile->h));
1950 OpenCounter(-1);
1951 sqlite3_free(pFile->pUnused);
1952 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001953 return SQLITE_OK;
1954}
1955
1956/*
danielk1977e3026632004-06-22 11:29:02 +00001957** Close a file.
1958*/
danielk197762079062007-08-15 17:08:46 +00001959static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001960 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001961 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001962 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001963 unixUnlock(id, NO_LOCK);
1964 unixEnterMutex();
1965
1966 /* unixFile.pInode is always valid here. Otherwise, a different close
1967 ** routine (e.g. nolockClose()) would be called instead.
1968 */
1969 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1970 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1971 /* If there are outstanding locks, do not actually close the file just
1972 ** yet because that would clear those locks. Instead, add the file
1973 ** descriptor to pInode->pUnused list. It will be automatically closed
1974 ** when the last lock is cleared.
1975 */
1976 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001977 }
dan661d71a2011-03-30 19:08:03 +00001978 releaseInodeInfo(pFile);
1979 rc = closeUnixFile(id);
1980 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001981 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001982}
1983
drh734c9862008-11-28 15:37:20 +00001984/************** End of the posix advisory lock implementation *****************
1985******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001986
drh734c9862008-11-28 15:37:20 +00001987/******************************************************************************
1988****************************** No-op Locking **********************************
1989**
1990** Of the various locking implementations available, this is by far the
1991** simplest: locking is ignored. No attempt is made to lock the database
1992** file for reading or writing.
1993**
1994** This locking mode is appropriate for use on read-only databases
1995** (ex: databases that are burned into CD-ROM, for example.) It can
1996** also be used if the application employs some external mechanism to
1997** prevent simultaneous access of the same database by two or more
1998** database connections. But there is a serious risk of database
1999** corruption if this locking mode is used in situations where multiple
2000** database connections are accessing the same database file at the same
2001** time and one or more of those connections are writing.
2002*/
drhbfe66312006-10-03 17:40:40 +00002003
drh734c9862008-11-28 15:37:20 +00002004static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2005 UNUSED_PARAMETER(NotUsed);
2006 *pResOut = 0;
2007 return SQLITE_OK;
2008}
drh734c9862008-11-28 15:37:20 +00002009static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2010 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2011 return SQLITE_OK;
2012}
drh734c9862008-11-28 15:37:20 +00002013static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2014 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2015 return SQLITE_OK;
2016}
2017
2018/*
drh9b35ea62008-11-29 02:20:26 +00002019** Close the file.
drh734c9862008-11-28 15:37:20 +00002020*/
2021static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002022 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002023}
2024
2025/******************* End of the no-op lock implementation *********************
2026******************************************************************************/
2027
2028/******************************************************************************
2029************************* Begin dot-file Locking ******************************
2030**
mistachkin48864df2013-03-21 21:20:32 +00002031** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002032** files (really a directory) to control access to the database. This works
2033** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002034**
2035** (1) There is zero concurrency. A single reader blocks all other
2036** connections from reading or writing the database.
2037**
2038** (2) An application crash or power loss can leave stale lock files
2039** sitting around that need to be cleared manually.
2040**
2041** Nevertheless, a dotlock is an appropriate locking mode for use if no
2042** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002043**
drh9ef6bc42011-11-04 02:24:02 +00002044** Dotfile locking works by creating a subdirectory in the same directory as
2045** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002046** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002047** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002048*/
2049
2050/*
2051** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002052** lock directory.
drh734c9862008-11-28 15:37:20 +00002053*/
2054#define DOTLOCK_SUFFIX ".lock"
2055
drh7708e972008-11-29 00:56:52 +00002056/*
2057** This routine checks if there is a RESERVED lock held on the specified
2058** file by this or any other process. If such a lock is held, set *pResOut
2059** to a non-zero value otherwise *pResOut is set to zero. The return value
2060** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2061**
2062** In dotfile locking, either a lock exists or it does not. So in this
2063** variation of CheckReservedLock(), *pResOut is set to true if any lock
2064** is held on the file and false if the file is unlocked.
2065*/
drh734c9862008-11-28 15:37:20 +00002066static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2067 int rc = SQLITE_OK;
2068 int reserved = 0;
2069 unixFile *pFile = (unixFile*)id;
2070
2071 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2072
2073 assert( pFile );
2074
2075 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002076 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002077 /* Either this connection or some other connection in the same process
2078 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002079 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002080 }else{
2081 /* The lock is held if and only if the lockfile exists */
2082 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002083 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002084 }
drh308c2a52010-05-14 11:30:18 +00002085 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002086 *pResOut = reserved;
2087 return rc;
2088}
2089
drh7708e972008-11-29 00:56:52 +00002090/*
drh308c2a52010-05-14 11:30:18 +00002091** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002092** of the following:
2093**
2094** (1) SHARED_LOCK
2095** (2) RESERVED_LOCK
2096** (3) PENDING_LOCK
2097** (4) EXCLUSIVE_LOCK
2098**
2099** Sometimes when requesting one lock state, additional lock states
2100** are inserted in between. The locking might fail on one of the later
2101** transitions leaving the lock state different from what it started but
2102** still short of its goal. The following chart shows the allowed
2103** transitions and the inserted intermediate states:
2104**
2105** UNLOCKED -> SHARED
2106** SHARED -> RESERVED
2107** SHARED -> (PENDING) -> EXCLUSIVE
2108** RESERVED -> (PENDING) -> EXCLUSIVE
2109** PENDING -> EXCLUSIVE
2110**
2111** This routine will only increase a lock. Use the sqlite3OsUnlock()
2112** routine to lower a locking level.
2113**
2114** With dotfile locking, we really only support state (4): EXCLUSIVE.
2115** But we track the other locking levels internally.
2116*/
drh308c2a52010-05-14 11:30:18 +00002117static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002118 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002119 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002120 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002121
drh7708e972008-11-29 00:56:52 +00002122
2123 /* If we have any lock, then the lock file already exists. All we have
2124 ** to do is adjust our internal record of the lock level.
2125 */
drh308c2a52010-05-14 11:30:18 +00002126 if( pFile->eFileLock > NO_LOCK ){
2127 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002128 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002129#ifdef HAVE_UTIME
2130 utime(zLockFile, NULL);
2131#else
drh734c9862008-11-28 15:37:20 +00002132 utimes(zLockFile, NULL);
2133#endif
drh7708e972008-11-29 00:56:52 +00002134 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002135 }
2136
2137 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002138 rc = osMkdir(zLockFile, 0777);
2139 if( rc<0 ){
2140 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002141 int tErrno = errno;
2142 if( EEXIST == tErrno ){
2143 rc = SQLITE_BUSY;
2144 } else {
2145 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2146 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002147 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002148 }
2149 }
drh7708e972008-11-29 00:56:52 +00002150 return rc;
drh734c9862008-11-28 15:37:20 +00002151 }
drh734c9862008-11-28 15:37:20 +00002152
2153 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002154 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002155 return rc;
2156}
2157
drh7708e972008-11-29 00:56:52 +00002158/*
drh308c2a52010-05-14 11:30:18 +00002159** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002160** must be either NO_LOCK or SHARED_LOCK.
2161**
2162** If the locking level of the file descriptor is already at or below
2163** the requested locking level, this routine is a no-op.
2164**
2165** When the locking level reaches NO_LOCK, delete the lock file.
2166*/
drh308c2a52010-05-14 11:30:18 +00002167static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002168 unixFile *pFile = (unixFile*)id;
2169 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002170 int rc;
drh734c9862008-11-28 15:37:20 +00002171
2172 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002173 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002174 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002175 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002176
2177 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002178 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002179 return SQLITE_OK;
2180 }
drh7708e972008-11-29 00:56:52 +00002181
2182 /* To downgrade to shared, simply update our internal notion of the
2183 ** lock state. No need to mess with the file on disk.
2184 */
drh308c2a52010-05-14 11:30:18 +00002185 if( eFileLock==SHARED_LOCK ){
2186 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002187 return SQLITE_OK;
2188 }
2189
drh7708e972008-11-29 00:56:52 +00002190 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002191 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002192 rc = osRmdir(zLockFile);
2193 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2194 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002195 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002196 rc = 0;
drh734c9862008-11-28 15:37:20 +00002197 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002198 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002199 }
2200 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002201 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002202 }
2203 return rc;
2204 }
drh308c2a52010-05-14 11:30:18 +00002205 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002206 return SQLITE_OK;
2207}
2208
2209/*
drh9b35ea62008-11-29 02:20:26 +00002210** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002211*/
2212static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002213 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002214 if( id ){
2215 unixFile *pFile = (unixFile*)id;
2216 dotlockUnlock(id, NO_LOCK);
2217 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002218 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002219 }
drh734c9862008-11-28 15:37:20 +00002220 return rc;
2221}
2222/****************** End of the dot-file lock implementation *******************
2223******************************************************************************/
2224
2225/******************************************************************************
2226************************** Begin flock Locking ********************************
2227**
2228** Use the flock() system call to do file locking.
2229**
drh6b9d6dd2008-12-03 19:34:47 +00002230** flock() locking is like dot-file locking in that the various
2231** fine-grain locking levels supported by SQLite are collapsed into
2232** a single exclusive lock. In other words, SHARED, RESERVED, and
2233** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2234** still works when you do this, but concurrency is reduced since
2235** only a single process can be reading the database at a time.
2236**
drhe89b2912015-03-03 20:42:01 +00002237** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002238*/
drhe89b2912015-03-03 20:42:01 +00002239#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002240
drh6b9d6dd2008-12-03 19:34:47 +00002241/*
drhff812312011-02-23 13:33:46 +00002242** Retry flock() calls that fail with EINTR
2243*/
2244#ifdef EINTR
2245static int robust_flock(int fd, int op){
2246 int rc;
2247 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2248 return rc;
2249}
2250#else
drh5c819272011-02-23 14:00:12 +00002251# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002252#endif
2253
2254
2255/*
drh6b9d6dd2008-12-03 19:34:47 +00002256** This routine checks if there is a RESERVED lock held on the specified
2257** file by this or any other process. If such a lock is held, set *pResOut
2258** to a non-zero value otherwise *pResOut is set to zero. The return value
2259** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2260*/
drh734c9862008-11-28 15:37:20 +00002261static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2262 int rc = SQLITE_OK;
2263 int reserved = 0;
2264 unixFile *pFile = (unixFile*)id;
2265
2266 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2267
2268 assert( pFile );
2269
2270 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002271 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002272 reserved = 1;
2273 }
2274
2275 /* Otherwise see if some other process holds it. */
2276 if( !reserved ){
2277 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002278 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002279 if( !lrc ){
2280 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002281 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002282 if ( lrc ) {
2283 int tErrno = errno;
2284 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002285 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002286 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002287 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002288 rc = lrc;
2289 }
2290 }
2291 } else {
2292 int tErrno = errno;
2293 reserved = 1;
2294 /* someone else might have it reserved */
2295 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2296 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002297 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002298 rc = lrc;
2299 }
2300 }
2301 }
drh308c2a52010-05-14 11:30:18 +00002302 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002303
2304#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2305 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2306 rc = SQLITE_OK;
2307 reserved=1;
2308 }
2309#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2310 *pResOut = reserved;
2311 return rc;
2312}
2313
drh6b9d6dd2008-12-03 19:34:47 +00002314/*
drh308c2a52010-05-14 11:30:18 +00002315** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002316** of the following:
2317**
2318** (1) SHARED_LOCK
2319** (2) RESERVED_LOCK
2320** (3) PENDING_LOCK
2321** (4) EXCLUSIVE_LOCK
2322**
2323** Sometimes when requesting one lock state, additional lock states
2324** are inserted in between. The locking might fail on one of the later
2325** transitions leaving the lock state different from what it started but
2326** still short of its goal. The following chart shows the allowed
2327** transitions and the inserted intermediate states:
2328**
2329** UNLOCKED -> SHARED
2330** SHARED -> RESERVED
2331** SHARED -> (PENDING) -> EXCLUSIVE
2332** RESERVED -> (PENDING) -> EXCLUSIVE
2333** PENDING -> EXCLUSIVE
2334**
2335** flock() only really support EXCLUSIVE locks. We track intermediate
2336** lock states in the sqlite3_file structure, but all locks SHARED or
2337** above are really EXCLUSIVE locks and exclude all other processes from
2338** access the file.
2339**
2340** This routine will only increase a lock. Use the sqlite3OsUnlock()
2341** routine to lower a locking level.
2342*/
drh308c2a52010-05-14 11:30:18 +00002343static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002344 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002345 unixFile *pFile = (unixFile*)id;
2346
2347 assert( pFile );
2348
2349 /* if we already have a lock, it is exclusive.
2350 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002351 if (pFile->eFileLock > NO_LOCK) {
2352 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002353 return SQLITE_OK;
2354 }
2355
2356 /* grab an exclusive lock */
2357
drhff812312011-02-23 13:33:46 +00002358 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002359 int tErrno = errno;
2360 /* didn't get, must be busy */
2361 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2362 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002363 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002364 }
2365 } else {
2366 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002367 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002368 }
drh308c2a52010-05-14 11:30:18 +00002369 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2370 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002371#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2372 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2373 rc = SQLITE_BUSY;
2374 }
2375#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2376 return rc;
2377}
2378
drh6b9d6dd2008-12-03 19:34:47 +00002379
2380/*
drh308c2a52010-05-14 11:30:18 +00002381** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002382** must be either NO_LOCK or SHARED_LOCK.
2383**
2384** If the locking level of the file descriptor is already at or below
2385** the requested locking level, this routine is a no-op.
2386*/
drh308c2a52010-05-14 11:30:18 +00002387static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002388 unixFile *pFile = (unixFile*)id;
2389
2390 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002391 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002392 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002393 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002394
2395 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002396 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002397 return SQLITE_OK;
2398 }
2399
2400 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002401 if (eFileLock==SHARED_LOCK) {
2402 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404 }
2405
2406 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002407 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002408#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002409 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002410#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002411 return SQLITE_IOERR_UNLOCK;
2412 }else{
drh308c2a52010-05-14 11:30:18 +00002413 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002414 return SQLITE_OK;
2415 }
2416}
2417
2418/*
2419** Close a file.
2420*/
2421static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002422 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002423 if( id ){
2424 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002425 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002426 }
drh5a05be12012-10-09 18:51:44 +00002427 return rc;
drh734c9862008-11-28 15:37:20 +00002428}
2429
2430#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2431
2432/******************* End of the flock lock implementation *********************
2433******************************************************************************/
2434
2435/******************************************************************************
2436************************ Begin Named Semaphore Locking ************************
2437**
2438** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002439**
2440** Semaphore locking is like dot-lock and flock in that it really only
2441** supports EXCLUSIVE locking. Only a single process can read or write
2442** the database file at a time. This reduces potential concurrency, but
2443** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002444*/
2445#if OS_VXWORKS
2446
drh6b9d6dd2008-12-03 19:34:47 +00002447/*
2448** This routine checks if there is a RESERVED lock held on the specified
2449** file by this or any other process. If such a lock is held, set *pResOut
2450** to a non-zero value otherwise *pResOut is set to zero. The return value
2451** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2452*/
drh8cd5b252015-03-02 22:06:43 +00002453static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002454 int rc = SQLITE_OK;
2455 int reserved = 0;
2456 unixFile *pFile = (unixFile*)id;
2457
2458 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2459
2460 assert( pFile );
2461
2462 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002463 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002464 reserved = 1;
2465 }
2466
2467 /* Otherwise see if some other process holds it. */
2468 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002469 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002470
2471 if( sem_trywait(pSem)==-1 ){
2472 int tErrno = errno;
2473 if( EAGAIN != tErrno ){
2474 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002475 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002476 } else {
2477 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002478 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002479 }
2480 }else{
2481 /* we could have it if we want it */
2482 sem_post(pSem);
2483 }
2484 }
drh308c2a52010-05-14 11:30:18 +00002485 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002486
2487 *pResOut = reserved;
2488 return rc;
2489}
2490
drh6b9d6dd2008-12-03 19:34:47 +00002491/*
drh308c2a52010-05-14 11:30:18 +00002492** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002493** of the following:
2494**
2495** (1) SHARED_LOCK
2496** (2) RESERVED_LOCK
2497** (3) PENDING_LOCK
2498** (4) EXCLUSIVE_LOCK
2499**
2500** Sometimes when requesting one lock state, additional lock states
2501** are inserted in between. The locking might fail on one of the later
2502** transitions leaving the lock state different from what it started but
2503** still short of its goal. The following chart shows the allowed
2504** transitions and the inserted intermediate states:
2505**
2506** UNLOCKED -> SHARED
2507** SHARED -> RESERVED
2508** SHARED -> (PENDING) -> EXCLUSIVE
2509** RESERVED -> (PENDING) -> EXCLUSIVE
2510** PENDING -> EXCLUSIVE
2511**
2512** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2513** lock states in the sqlite3_file structure, but all locks SHARED or
2514** above are really EXCLUSIVE locks and exclude all other processes from
2515** access the file.
2516**
2517** This routine will only increase a lock. Use the sqlite3OsUnlock()
2518** routine to lower a locking level.
2519*/
drh8cd5b252015-03-02 22:06:43 +00002520static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002521 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002522 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002523 int rc = SQLITE_OK;
2524
2525 /* if we already have a lock, it is exclusive.
2526 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002527 if (pFile->eFileLock > NO_LOCK) {
2528 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002529 rc = SQLITE_OK;
2530 goto sem_end_lock;
2531 }
2532
2533 /* lock semaphore now but bail out when already locked. */
2534 if( sem_trywait(pSem)==-1 ){
2535 rc = SQLITE_BUSY;
2536 goto sem_end_lock;
2537 }
2538
2539 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002540 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002541
2542 sem_end_lock:
2543 return rc;
2544}
2545
drh6b9d6dd2008-12-03 19:34:47 +00002546/*
drh308c2a52010-05-14 11:30:18 +00002547** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002548** must be either NO_LOCK or SHARED_LOCK.
2549**
2550** If the locking level of the file descriptor is already at or below
2551** the requested locking level, this routine is a no-op.
2552*/
drh8cd5b252015-03-02 22:06:43 +00002553static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002554 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002555 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002556
2557 assert( pFile );
2558 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002559 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002560 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002561 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002562
2563 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002564 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002565 return SQLITE_OK;
2566 }
2567
2568 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002569 if (eFileLock==SHARED_LOCK) {
2570 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002571 return SQLITE_OK;
2572 }
2573
2574 /* no, really unlock. */
2575 if ( sem_post(pSem)==-1 ) {
2576 int rc, tErrno = errno;
2577 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2578 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002579 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002580 }
2581 return rc;
2582 }
drh308c2a52010-05-14 11:30:18 +00002583 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002584 return SQLITE_OK;
2585}
2586
2587/*
2588 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002589 */
drh8cd5b252015-03-02 22:06:43 +00002590static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002591 if( id ){
2592 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002593 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002594 assert( pFile );
2595 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002596 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002597 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002598 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002599 }
2600 return SQLITE_OK;
2601}
2602
2603#endif /* OS_VXWORKS */
2604/*
2605** Named semaphore locking is only available on VxWorks.
2606**
2607*************** End of the named semaphore lock implementation ****************
2608******************************************************************************/
2609
2610
2611/******************************************************************************
2612*************************** Begin AFP Locking *********************************
2613**
2614** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2615** on Apple Macintosh computers - both OS9 and OSX.
2616**
2617** Third-party implementations of AFP are available. But this code here
2618** only works on OSX.
2619*/
2620
drhd2cb50b2009-01-09 21:41:17 +00002621#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002622/*
2623** The afpLockingContext structure contains all afp lock specific state
2624*/
drhbfe66312006-10-03 17:40:40 +00002625typedef struct afpLockingContext afpLockingContext;
2626struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002627 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002628 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002629};
2630
2631struct ByteRangeLockPB2
2632{
2633 unsigned long long offset; /* offset to first byte to lock */
2634 unsigned long long length; /* nbr of bytes to lock */
2635 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2636 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2637 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2638 int fd; /* file desc to assoc this lock with */
2639};
2640
drhfd131da2007-08-07 17:13:03 +00002641#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002642
drh6b9d6dd2008-12-03 19:34:47 +00002643/*
2644** This is a utility for setting or clearing a bit-range lock on an
2645** AFP filesystem.
2646**
2647** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2648*/
2649static int afpSetLock(
2650 const char *path, /* Name of the file to be locked or unlocked */
2651 unixFile *pFile, /* Open file descriptor on path */
2652 unsigned long long offset, /* First byte to be locked */
2653 unsigned long long length, /* Number of bytes to lock */
2654 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002655){
drh6b9d6dd2008-12-03 19:34:47 +00002656 struct ByteRangeLockPB2 pb;
2657 int err;
drhbfe66312006-10-03 17:40:40 +00002658
2659 pb.unLockFlag = setLockFlag ? 0 : 1;
2660 pb.startEndFlag = 0;
2661 pb.offset = offset;
2662 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002663 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002664
drh308c2a52010-05-14 11:30:18 +00002665 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002666 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002667 offset, length));
drhbfe66312006-10-03 17:40:40 +00002668 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2669 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002670 int rc;
2671 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002672 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2673 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002674#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2675 rc = SQLITE_BUSY;
2676#else
drh734c9862008-11-28 15:37:20 +00002677 rc = sqliteErrorFromPosixError(tErrno,
2678 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002679#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002680 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002681 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002682 }
2683 return rc;
drhbfe66312006-10-03 17:40:40 +00002684 } else {
aswift5b1a2562008-08-22 00:22:35 +00002685 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002686 }
2687}
2688
drh6b9d6dd2008-12-03 19:34:47 +00002689/*
2690** This routine checks if there is a RESERVED lock held on the specified
2691** file by this or any other process. If such a lock is held, set *pResOut
2692** to a non-zero value otherwise *pResOut is set to zero. The return value
2693** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2694*/
danielk1977e339d652008-06-28 11:23:00 +00002695static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002696 int rc = SQLITE_OK;
2697 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002698 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002699 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002700
aswift5b1a2562008-08-22 00:22:35 +00002701 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2702
2703 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002704 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002705 if( context->reserved ){
2706 *pResOut = 1;
2707 return SQLITE_OK;
2708 }
drh8af6c222010-05-14 12:43:01 +00002709 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002710
2711 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002712 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002713 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002714 }
2715
2716 /* Otherwise see if some other process holds it.
2717 */
aswift5b1a2562008-08-22 00:22:35 +00002718 if( !reserved ){
2719 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002720 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002721 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002722 /* if we succeeded in taking the reserved lock, unlock it to restore
2723 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002724 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002725 } else {
2726 /* if we failed to get the lock then someone else must have it */
2727 reserved = 1;
2728 }
2729 if( IS_LOCK_ERROR(lrc) ){
2730 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002731 }
2732 }
drhbfe66312006-10-03 17:40:40 +00002733
drh7ed97b92010-01-20 13:07:21 +00002734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002735 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002736
2737 *pResOut = reserved;
2738 return rc;
drhbfe66312006-10-03 17:40:40 +00002739}
2740
drh6b9d6dd2008-12-03 19:34:47 +00002741/*
drh308c2a52010-05-14 11:30:18 +00002742** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002743** of the following:
2744**
2745** (1) SHARED_LOCK
2746** (2) RESERVED_LOCK
2747** (3) PENDING_LOCK
2748** (4) EXCLUSIVE_LOCK
2749**
2750** Sometimes when requesting one lock state, additional lock states
2751** are inserted in between. The locking might fail on one of the later
2752** transitions leaving the lock state different from what it started but
2753** still short of its goal. The following chart shows the allowed
2754** transitions and the inserted intermediate states:
2755**
2756** UNLOCKED -> SHARED
2757** SHARED -> RESERVED
2758** SHARED -> (PENDING) -> EXCLUSIVE
2759** RESERVED -> (PENDING) -> EXCLUSIVE
2760** PENDING -> EXCLUSIVE
2761**
2762** This routine will only increase a lock. Use the sqlite3OsUnlock()
2763** routine to lower a locking level.
2764*/
drh308c2a52010-05-14 11:30:18 +00002765static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002766 int rc = SQLITE_OK;
2767 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002768 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002769 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002770
2771 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002772 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2773 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00002774 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid()));
drh339eb0b2008-03-07 15:34:11 +00002775
drhbfe66312006-10-03 17:40:40 +00002776 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002777 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002778 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002779 */
drh308c2a52010-05-14 11:30:18 +00002780 if( pFile->eFileLock>=eFileLock ){
2781 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2782 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002783 return SQLITE_OK;
2784 }
2785
2786 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002787 ** (1) We never move from unlocked to anything higher than shared lock.
2788 ** (2) SQLite never explicitly requests a pendig lock.
2789 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002790 */
drh308c2a52010-05-14 11:30:18 +00002791 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2792 assert( eFileLock!=PENDING_LOCK );
2793 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002794
drh8af6c222010-05-14 12:43:01 +00002795 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002796 */
drh6c7d5c52008-11-21 20:32:33 +00002797 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002798 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002799
2800 /* If some thread using this PID has a lock via a different unixFile*
2801 ** handle that precludes the requested lock, return BUSY.
2802 */
drh8af6c222010-05-14 12:43:01 +00002803 if( (pFile->eFileLock!=pInode->eFileLock &&
2804 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002805 ){
2806 rc = SQLITE_BUSY;
2807 goto afp_end_lock;
2808 }
2809
2810 /* If a SHARED lock is requested, and some thread using this PID already
2811 ** has a SHARED or RESERVED lock, then increment reference counts and
2812 ** return SQLITE_OK.
2813 */
drh308c2a52010-05-14 11:30:18 +00002814 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002815 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002816 assert( eFileLock==SHARED_LOCK );
2817 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002818 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002819 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002820 pInode->nShared++;
2821 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002822 goto afp_end_lock;
2823 }
drhbfe66312006-10-03 17:40:40 +00002824
2825 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002826 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2827 ** be released.
2828 */
drh308c2a52010-05-14 11:30:18 +00002829 if( eFileLock==SHARED_LOCK
2830 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002831 ){
2832 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002833 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002834 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002835 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002836 goto afp_end_lock;
2837 }
2838 }
2839
2840 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002841 ** operating system calls for the specified lock.
2842 */
drh308c2a52010-05-14 11:30:18 +00002843 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002844 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002845 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002846
drh8af6c222010-05-14 12:43:01 +00002847 assert( pInode->nShared==0 );
2848 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002849
2850 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002851 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002852 /* note that the quality of the randomness doesn't matter that much */
2853 lk = random();
drh8af6c222010-05-14 12:43:01 +00002854 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002855 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002856 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002857 if( IS_LOCK_ERROR(lrc1) ){
2858 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002859 }
aswift5b1a2562008-08-22 00:22:35 +00002860 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002861 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002862
aswift5b1a2562008-08-22 00:22:35 +00002863 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002864 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002865 rc = lrc1;
2866 goto afp_end_lock;
2867 } else if( IS_LOCK_ERROR(lrc2) ){
2868 rc = lrc2;
2869 goto afp_end_lock;
2870 } else if( lrc1 != SQLITE_OK ) {
2871 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002872 } else {
drh308c2a52010-05-14 11:30:18 +00002873 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002874 pInode->nLock++;
2875 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002876 }
drh8af6c222010-05-14 12:43:01 +00002877 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002878 /* We are trying for an exclusive lock but another thread in this
2879 ** same process is still holding a shared lock. */
2880 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002881 }else{
2882 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2883 ** assumed that there is a SHARED or greater lock on the file
2884 ** already.
2885 */
2886 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002887 assert( 0!=pFile->eFileLock );
2888 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002889 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002890 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002891 if( !failed ){
2892 context->reserved = 1;
2893 }
drhbfe66312006-10-03 17:40:40 +00002894 }
drh308c2a52010-05-14 11:30:18 +00002895 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002896 /* Acquire an EXCLUSIVE lock */
2897
2898 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002899 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002900 */
drh6b9d6dd2008-12-03 19:34:47 +00002901 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002902 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002903 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002904 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002905 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002906 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002907 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002908 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002909 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2910 ** a critical I/O error
2911 */
2912 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2913 SQLITE_IOERR_LOCK;
2914 goto afp_end_lock;
2915 }
2916 }else{
aswift5b1a2562008-08-22 00:22:35 +00002917 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002918 }
2919 }
aswift5b1a2562008-08-22 00:22:35 +00002920 if( failed ){
2921 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002922 }
2923 }
2924
2925 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002926 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002927 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002928 }else if( eFileLock==EXCLUSIVE_LOCK ){
2929 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002930 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002931 }
2932
2933afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002934 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002935 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2936 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002937 return rc;
2938}
2939
2940/*
drh308c2a52010-05-14 11:30:18 +00002941** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002942** must be either NO_LOCK or SHARED_LOCK.
2943**
2944** If the locking level of the file descriptor is already at or below
2945** the requested locking level, this routine is a no-op.
2946*/
drh308c2a52010-05-14 11:30:18 +00002947static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002948 int rc = SQLITE_OK;
2949 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002950 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002951 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2952 int skipShared = 0;
2953#ifdef SQLITE_TEST
2954 int h = pFile->h;
2955#endif
drhbfe66312006-10-03 17:40:40 +00002956
2957 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002958 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002959 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh91eb93c2015-03-03 19:56:20 +00002960 osGetpid()));
aswift5b1a2562008-08-22 00:22:35 +00002961
drh308c2a52010-05-14 11:30:18 +00002962 assert( eFileLock<=SHARED_LOCK );
2963 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002964 return SQLITE_OK;
2965 }
drh6c7d5c52008-11-21 20:32:33 +00002966 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002967 pInode = pFile->pInode;
2968 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002969 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002970 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002971 SimulateIOErrorBenign(1);
2972 SimulateIOError( h=(-1) )
2973 SimulateIOErrorBenign(0);
2974
drhd3d8c042012-05-29 17:02:40 +00002975#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002976 /* When reducing a lock such that other processes can start
2977 ** reading the database file again, make sure that the
2978 ** transaction counter was updated if any part of the database
2979 ** file changed. If the transaction counter is not updated,
2980 ** other connections to the same file might not realize that
2981 ** the file has changed and hence might not know to flush their
2982 ** cache. The use of a stale cache can lead to database corruption.
2983 */
2984 assert( pFile->inNormalWrite==0
2985 || pFile->dbUpdate==0
2986 || pFile->transCntrChng==1 );
2987 pFile->inNormalWrite = 0;
2988#endif
aswiftaebf4132008-11-21 00:10:35 +00002989
drh308c2a52010-05-14 11:30:18 +00002990 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002991 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002992 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002993 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002994 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002995 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2996 } else {
2997 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002998 }
2999 }
drh308c2a52010-05-14 11:30:18 +00003000 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003001 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003002 }
drh308c2a52010-05-14 11:30:18 +00003003 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003004 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3005 if( !rc ){
3006 context->reserved = 0;
3007 }
aswiftaebf4132008-11-21 00:10:35 +00003008 }
drh8af6c222010-05-14 12:43:01 +00003009 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3010 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003011 }
aswiftaebf4132008-11-21 00:10:35 +00003012 }
drh308c2a52010-05-14 11:30:18 +00003013 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003014
drh7ed97b92010-01-20 13:07:21 +00003015 /* Decrement the shared lock counter. Release the lock using an
3016 ** OS call only when all threads in this same process have released
3017 ** the lock.
3018 */
drh8af6c222010-05-14 12:43:01 +00003019 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3020 pInode->nShared--;
3021 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003022 SimulateIOErrorBenign(1);
3023 SimulateIOError( h=(-1) )
3024 SimulateIOErrorBenign(0);
3025 if( !skipShared ){
3026 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3027 }
3028 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003029 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003030 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003031 }
3032 }
3033 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003034 pInode->nLock--;
3035 assert( pInode->nLock>=0 );
3036 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003037 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003038 }
3039 }
drhbfe66312006-10-03 17:40:40 +00003040 }
drh7ed97b92010-01-20 13:07:21 +00003041
drh6c7d5c52008-11-21 20:32:33 +00003042 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003043 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003044 return rc;
3045}
3046
3047/*
drh339eb0b2008-03-07 15:34:11 +00003048** Close a file & cleanup AFP specific locking context
3049*/
danielk1977e339d652008-06-28 11:23:00 +00003050static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003051 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003052 if( id ){
3053 unixFile *pFile = (unixFile*)id;
3054 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003055 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003056 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003057 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003058 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003059 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003060 ** the last lock is cleared.
3061 */
dan08da86a2009-08-21 17:18:03 +00003062 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003063 }
danb0ac3e32010-06-16 10:55:42 +00003064 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003065 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003066 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003067 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003068 }
drh7ed97b92010-01-20 13:07:21 +00003069 return rc;
drhbfe66312006-10-03 17:40:40 +00003070}
3071
drhd2cb50b2009-01-09 21:41:17 +00003072#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003073/*
3074** The code above is the AFP lock implementation. The code is specific
3075** to MacOSX and does not work on other unix platforms. No alternative
3076** is available. If you don't compile for a mac, then the "unix-afp"
3077** VFS is not available.
3078**
3079********************* End of the AFP lock implementation **********************
3080******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003081
drh7ed97b92010-01-20 13:07:21 +00003082/******************************************************************************
3083*************************** Begin NFS Locking ********************************/
3084
3085#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3086/*
drh308c2a52010-05-14 11:30:18 +00003087 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003088 ** must be either NO_LOCK or SHARED_LOCK.
3089 **
3090 ** If the locking level of the file descriptor is already at or below
3091 ** the requested locking level, this routine is a no-op.
3092 */
drh308c2a52010-05-14 11:30:18 +00003093static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003094 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003095}
3096
3097#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3098/*
3099** The code above is the NFS lock implementation. The code is specific
3100** to MacOSX and does not work on other unix platforms. No alternative
3101** is available.
3102**
3103********************* End of the NFS lock implementation **********************
3104******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003105
3106/******************************************************************************
3107**************** Non-locking sqlite3_file methods *****************************
3108**
3109** The next division contains implementations for all methods of the
3110** sqlite3_file object other than the locking methods. The locking
3111** methods were defined in divisions above (one locking method per
3112** division). Those methods that are common to all locking modes
3113** are gather together into this division.
3114*/
drhbfe66312006-10-03 17:40:40 +00003115
3116/*
drh734c9862008-11-28 15:37:20 +00003117** Seek to the offset passed as the second argument, then read cnt
3118** bytes into pBuf. Return the number of bytes actually read.
3119**
3120** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3121** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3122** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003123** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003124** See tickets #2741 and #2681.
3125**
3126** To avoid stomping the errno value on a failed read the lastErrno value
3127** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003128*/
drh734c9862008-11-28 15:37:20 +00003129static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3130 int got;
drh58024642011-11-07 18:16:00 +00003131 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003132#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003133 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003134#endif
drh734c9862008-11-28 15:37:20 +00003135 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003136 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003137 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003138 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003139 do{
drh734c9862008-11-28 15:37:20 +00003140#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003141 got = osPread(id->h, pBuf, cnt, offset);
3142 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003143#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003144 got = osPread64(id->h, pBuf, cnt, offset);
3145 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003146#else
drh58024642011-11-07 18:16:00 +00003147 newOffset = lseek(id->h, offset, SEEK_SET);
3148 SimulateIOError( newOffset-- );
3149 if( newOffset!=offset ){
3150 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003151 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003152 }else{
drh4bf66fd2015-02-19 02:43:02 +00003153 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003154 }
3155 return -1;
drh734c9862008-11-28 15:37:20 +00003156 }
drh58024642011-11-07 18:16:00 +00003157 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003158#endif
drh58024642011-11-07 18:16:00 +00003159 if( got==cnt ) break;
3160 if( got<0 ){
3161 if( errno==EINTR ){ got = 1; continue; }
3162 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003163 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003164 break;
3165 }else if( got>0 ){
3166 cnt -= got;
3167 offset += got;
3168 prior += got;
3169 pBuf = (void*)(got + (char*)pBuf);
3170 }
3171 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003172 TIMER_END;
drh58024642011-11-07 18:16:00 +00003173 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3174 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3175 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003176}
3177
3178/*
drh734c9862008-11-28 15:37:20 +00003179** Read data from a file into a buffer. Return SQLITE_OK if all
3180** bytes were read successfully and SQLITE_IOERR if anything goes
3181** wrong.
drh339eb0b2008-03-07 15:34:11 +00003182*/
drh734c9862008-11-28 15:37:20 +00003183static int unixRead(
3184 sqlite3_file *id,
3185 void *pBuf,
3186 int amt,
3187 sqlite3_int64 offset
3188){
dan08da86a2009-08-21 17:18:03 +00003189 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003190 int got;
3191 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003192 assert( offset>=0 );
3193 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003194
dan08da86a2009-08-21 17:18:03 +00003195 /* If this is a database file (not a journal, master-journal or temp
3196 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003197#if 0
dane946c392009-08-22 11:39:46 +00003198 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003199 || offset>=PENDING_BYTE+512
3200 || offset+amt<=PENDING_BYTE
3201 );
dan7c246102010-04-12 19:00:29 +00003202#endif
drh08c6d442009-02-09 17:34:07 +00003203
drh9b4c59f2013-04-15 17:03:42 +00003204#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003205 /* Deal with as much of this read request as possible by transfering
3206 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003207 if( offset<pFile->mmapSize ){
3208 if( offset+amt <= pFile->mmapSize ){
3209 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3210 return SQLITE_OK;
3211 }else{
3212 int nCopy = pFile->mmapSize - offset;
3213 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3214 pBuf = &((u8 *)pBuf)[nCopy];
3215 amt -= nCopy;
3216 offset += nCopy;
3217 }
3218 }
drh6e0b6d52013-04-09 16:19:20 +00003219#endif
danf23da962013-03-23 21:00:41 +00003220
dan08da86a2009-08-21 17:18:03 +00003221 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003222 if( got==amt ){
3223 return SQLITE_OK;
3224 }else if( got<0 ){
3225 /* lastErrno set by seekAndRead */
3226 return SQLITE_IOERR_READ;
3227 }else{
drh4bf66fd2015-02-19 02:43:02 +00003228 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003229 /* Unread parts of the buffer must be zero-filled */
3230 memset(&((char*)pBuf)[got], 0, amt-got);
3231 return SQLITE_IOERR_SHORT_READ;
3232 }
3233}
3234
3235/*
dan47a2b4a2013-04-26 16:09:29 +00003236** Attempt to seek the file-descriptor passed as the first argument to
3237** absolute offset iOff, then attempt to write nBuf bytes of data from
3238** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3239** return the actual number of bytes written (which may be less than
3240** nBuf).
3241*/
3242static int seekAndWriteFd(
3243 int fd, /* File descriptor to write to */
3244 i64 iOff, /* File offset to begin writing at */
3245 const void *pBuf, /* Copy data from this buffer to the file */
3246 int nBuf, /* Size of buffer pBuf in bytes */
3247 int *piErrno /* OUT: Error number if error occurs */
3248){
3249 int rc = 0; /* Value returned by system call */
3250
3251 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003252 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003253 nBuf &= 0x1ffff;
3254 TIMER_START;
3255
3256#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003257 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003258#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003259 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003260#else
3261 do{
3262 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3263 SimulateIOError( iSeek-- );
3264
3265 if( iSeek!=iOff ){
3266 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3267 return -1;
3268 }
3269 rc = osWrite(fd, pBuf, nBuf);
3270 }while( rc<0 && errno==EINTR );
3271#endif
3272
3273 TIMER_END;
3274 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3275
3276 if( rc<0 && piErrno ) *piErrno = errno;
3277 return rc;
3278}
3279
3280
3281/*
drh734c9862008-11-28 15:37:20 +00003282** Seek to the offset in id->offset then read cnt bytes into pBuf.
3283** Return the number of bytes actually read. Update the offset.
3284**
3285** To avoid stomping the errno value on a failed write the lastErrno value
3286** is set before returning.
3287*/
3288static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003289 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003290}
3291
3292
3293/*
3294** Write data from a buffer into a file. Return SQLITE_OK on success
3295** or some other error code on failure.
3296*/
3297static int unixWrite(
3298 sqlite3_file *id,
3299 const void *pBuf,
3300 int amt,
3301 sqlite3_int64 offset
3302){
dan08da86a2009-08-21 17:18:03 +00003303 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003304 int wrote = 0;
3305 assert( id );
3306 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003307
dan08da86a2009-08-21 17:18:03 +00003308 /* If this is a database file (not a journal, master-journal or temp
3309 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003310#if 0
dane946c392009-08-22 11:39:46 +00003311 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003312 || offset>=PENDING_BYTE+512
3313 || offset+amt<=PENDING_BYTE
3314 );
dan7c246102010-04-12 19:00:29 +00003315#endif
drh08c6d442009-02-09 17:34:07 +00003316
drhd3d8c042012-05-29 17:02:40 +00003317#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003318 /* If we are doing a normal write to a database file (as opposed to
3319 ** doing a hot-journal rollback or a write to some file other than a
3320 ** normal database file) then record the fact that the database
3321 ** has changed. If the transaction counter is modified, record that
3322 ** fact too.
3323 */
dan08da86a2009-08-21 17:18:03 +00003324 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003325 pFile->dbUpdate = 1; /* The database has been modified */
3326 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003327 int rc;
drh8f941bc2009-01-14 23:03:40 +00003328 char oldCntr[4];
3329 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003330 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003331 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003332 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003333 pFile->transCntrChng = 1; /* The transaction counter has changed */
3334 }
3335 }
3336 }
3337#endif
3338
drh9b4c59f2013-04-15 17:03:42 +00003339#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003340 /* Deal with as much of this write request as possible by transfering
3341 ** data from the memory mapping using memcpy(). */
3342 if( offset<pFile->mmapSize ){
3343 if( offset+amt <= pFile->mmapSize ){
3344 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3345 return SQLITE_OK;
3346 }else{
3347 int nCopy = pFile->mmapSize - offset;
3348 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3349 pBuf = &((u8 *)pBuf)[nCopy];
3350 amt -= nCopy;
3351 offset += nCopy;
3352 }
3353 }
drh6e0b6d52013-04-09 16:19:20 +00003354#endif
danf23da962013-03-23 21:00:41 +00003355
dan08da86a2009-08-21 17:18:03 +00003356 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003357 amt -= wrote;
3358 offset += wrote;
3359 pBuf = &((char*)pBuf)[wrote];
3360 }
3361 SimulateIOError(( wrote=(-1), amt=1 ));
3362 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003363
drh734c9862008-11-28 15:37:20 +00003364 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003365 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003366 /* lastErrno set by seekAndWrite */
3367 return SQLITE_IOERR_WRITE;
3368 }else{
drh4bf66fd2015-02-19 02:43:02 +00003369 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003370 return SQLITE_FULL;
3371 }
3372 }
dan6e09d692010-07-27 18:34:15 +00003373
drh734c9862008-11-28 15:37:20 +00003374 return SQLITE_OK;
3375}
3376
3377#ifdef SQLITE_TEST
3378/*
3379** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003380** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003381*/
3382int sqlite3_sync_count = 0;
3383int sqlite3_fullsync_count = 0;
3384#endif
3385
3386/*
drh89240432009-03-25 01:06:01 +00003387** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003388** Others do no. To be safe, we will stick with the (slightly slower)
3389** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003390** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003391*/
drhf7a4a1b2015-01-10 18:02:45 +00003392#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003393# define fdatasync fsync
3394#endif
3395
3396/*
3397** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3398** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3399** only available on Mac OS X. But that could change.
3400*/
3401#ifdef F_FULLFSYNC
3402# define HAVE_FULLFSYNC 1
3403#else
3404# define HAVE_FULLFSYNC 0
3405#endif
3406
3407
3408/*
3409** The fsync() system call does not work as advertised on many
3410** unix systems. The following procedure is an attempt to make
3411** it work better.
3412**
3413** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3414** for testing when we want to run through the test suite quickly.
3415** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3416** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3417** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003418**
3419** SQLite sets the dataOnly flag if the size of the file is unchanged.
3420** The idea behind dataOnly is that it should only write the file content
3421** to disk, not the inode. We only set dataOnly if the file size is
3422** unchanged since the file size is part of the inode. However,
3423** Ted Ts'o tells us that fdatasync() will also write the inode if the
3424** file size has changed. The only real difference between fdatasync()
3425** and fsync(), Ted tells us, is that fdatasync() will not flush the
3426** inode if the mtime or owner or other inode attributes have changed.
3427** We only care about the file size, not the other file attributes, so
3428** as far as SQLite is concerned, an fdatasync() is always adequate.
3429** So, we always use fdatasync() if it is available, regardless of
3430** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003431*/
3432static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003433 int rc;
drh734c9862008-11-28 15:37:20 +00003434
3435 /* The following "ifdef/elif/else/" block has the same structure as
3436 ** the one below. It is replicated here solely to avoid cluttering
3437 ** up the real code with the UNUSED_PARAMETER() macros.
3438 */
3439#ifdef SQLITE_NO_SYNC
3440 UNUSED_PARAMETER(fd);
3441 UNUSED_PARAMETER(fullSync);
3442 UNUSED_PARAMETER(dataOnly);
3443#elif HAVE_FULLFSYNC
3444 UNUSED_PARAMETER(dataOnly);
3445#else
3446 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003447 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003448#endif
3449
3450 /* Record the number of times that we do a normal fsync() and
3451 ** FULLSYNC. This is used during testing to verify that this procedure
3452 ** gets called with the correct arguments.
3453 */
3454#ifdef SQLITE_TEST
3455 if( fullSync ) sqlite3_fullsync_count++;
3456 sqlite3_sync_count++;
3457#endif
3458
3459 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3460 ** no-op
3461 */
3462#ifdef SQLITE_NO_SYNC
3463 rc = SQLITE_OK;
3464#elif HAVE_FULLFSYNC
3465 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003466 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003467 }else{
3468 rc = 1;
3469 }
3470 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003471 ** It shouldn't be possible for fullfsync to fail on the local
3472 ** file system (on OSX), so failure indicates that FULLFSYNC
3473 ** isn't supported for this file system. So, attempt an fsync
3474 ** and (for now) ignore the overhead of a superfluous fcntl call.
3475 ** It'd be better to detect fullfsync support once and avoid
3476 ** the fcntl call every time sync is called.
3477 */
drh734c9862008-11-28 15:37:20 +00003478 if( rc ) rc = fsync(fd);
3479
drh7ed97b92010-01-20 13:07:21 +00003480#elif defined(__APPLE__)
3481 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3482 ** so currently we default to the macro that redefines fdatasync to fsync
3483 */
3484 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003485#else
drh0b647ff2009-03-21 14:41:04 +00003486 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003487#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003488 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003489 rc = fsync(fd);
3490 }
drh0b647ff2009-03-21 14:41:04 +00003491#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003492#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3493
3494 if( OS_VXWORKS && rc!= -1 ){
3495 rc = 0;
3496 }
chw97185482008-11-17 08:05:31 +00003497 return rc;
drhbfe66312006-10-03 17:40:40 +00003498}
3499
drh734c9862008-11-28 15:37:20 +00003500/*
drh0059eae2011-08-08 23:48:40 +00003501** Open a file descriptor to the directory containing file zFilename.
3502** If successful, *pFd is set to the opened file descriptor and
3503** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3504** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3505** value.
3506**
drh90315a22011-08-10 01:52:12 +00003507** The directory file descriptor is used for only one thing - to
3508** fsync() a directory to make sure file creation and deletion events
3509** are flushed to disk. Such fsyncs are not needed on newer
3510** journaling filesystems, but are required on older filesystems.
3511**
3512** This routine can be overridden using the xSetSysCall interface.
3513** The ability to override this routine was added in support of the
3514** chromium sandbox. Opening a directory is a security risk (we are
3515** told) so making it overrideable allows the chromium sandbox to
3516** replace this routine with a harmless no-op. To make this routine
3517** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3518** *pFd set to a negative number.
3519**
drh0059eae2011-08-08 23:48:40 +00003520** If SQLITE_OK is returned, the caller is responsible for closing
3521** the file descriptor *pFd using close().
3522*/
3523static int openDirectory(const char *zFilename, int *pFd){
3524 int ii;
3525 int fd = -1;
3526 char zDirname[MAX_PATHNAME+1];
3527
3528 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3529 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3530 if( ii>0 ){
3531 zDirname[ii] = '\0';
3532 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3533 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003534 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3535 }
3536 }
3537 *pFd = fd;
3538 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3539}
3540
3541/*
drh734c9862008-11-28 15:37:20 +00003542** Make sure all writes to a particular file are committed to disk.
3543**
3544** If dataOnly==0 then both the file itself and its metadata (file
3545** size, access time, etc) are synced. If dataOnly!=0 then only the
3546** file data is synced.
3547**
3548** Under Unix, also make sure that the directory entry for the file
3549** has been created by fsync-ing the directory that contains the file.
3550** If we do not do this and we encounter a power failure, the directory
3551** entry for the journal might not exist after we reboot. The next
3552** SQLite to access the file will not know that the journal exists (because
3553** the directory entry for the journal was never created) and the transaction
3554** will not roll back - possibly leading to database corruption.
3555*/
3556static int unixSync(sqlite3_file *id, int flags){
3557 int rc;
3558 unixFile *pFile = (unixFile*)id;
3559
3560 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3561 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3562
3563 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3564 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3565 || (flags&0x0F)==SQLITE_SYNC_FULL
3566 );
3567
3568 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3569 ** line is to test that doing so does not cause any problems.
3570 */
3571 SimulateDiskfullError( return SQLITE_FULL );
3572
3573 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003574 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003575 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3576 SimulateIOError( rc=1 );
3577 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003578 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003579 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003580 }
drh0059eae2011-08-08 23:48:40 +00003581
3582 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003583 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003584 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003585 */
3586 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3587 int dirfd;
3588 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003589 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003590 rc = osOpenDirectory(pFile->zPath, &dirfd);
3591 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003592 full_fsync(dirfd, 0, 0);
3593 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003594 }else if( rc==SQLITE_CANTOPEN ){
3595 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003596 }
drh0059eae2011-08-08 23:48:40 +00003597 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003598 }
3599 return rc;
3600}
3601
3602/*
3603** Truncate an open file to a specified size
3604*/
3605static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003606 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003607 int rc;
dan6e09d692010-07-27 18:34:15 +00003608 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003609 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003610
3611 /* If the user has configured a chunk-size for this file, truncate the
3612 ** file so that it consists of an integer number of chunks (i.e. the
3613 ** actual file size after the operation may be larger than the requested
3614 ** size).
3615 */
drhb8af4b72012-04-05 20:04:39 +00003616 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003617 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3618 }
3619
dan2ee53412014-09-06 16:49:40 +00003620 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003621 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003622 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003623 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003624 }else{
drhd3d8c042012-05-29 17:02:40 +00003625#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003626 /* If we are doing a normal write to a database file (as opposed to
3627 ** doing a hot-journal rollback or a write to some file other than a
3628 ** normal database file) and we truncate the file to zero length,
3629 ** that effectively updates the change counter. This might happen
3630 ** when restoring a database using the backup API from a zero-length
3631 ** source.
3632 */
dan6e09d692010-07-27 18:34:15 +00003633 if( pFile->inNormalWrite && nByte==0 ){
3634 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003635 }
danf23da962013-03-23 21:00:41 +00003636#endif
danc0003312013-03-22 17:46:11 +00003637
mistachkine98844f2013-08-24 00:59:24 +00003638#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003639 /* If the file was just truncated to a size smaller than the currently
3640 ** mapped region, reduce the effective mapping size as well. SQLite will
3641 ** use read() and write() to access data beyond this point from now on.
3642 */
3643 if( nByte<pFile->mmapSize ){
3644 pFile->mmapSize = nByte;
3645 }
mistachkine98844f2013-08-24 00:59:24 +00003646#endif
drh3313b142009-11-06 04:13:18 +00003647
drh734c9862008-11-28 15:37:20 +00003648 return SQLITE_OK;
3649 }
3650}
3651
3652/*
3653** Determine the current size of a file in bytes
3654*/
3655static int unixFileSize(sqlite3_file *id, i64 *pSize){
3656 int rc;
3657 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003658 assert( id );
3659 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003660 SimulateIOError( rc=1 );
3661 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003662 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003663 return SQLITE_IOERR_FSTAT;
3664 }
3665 *pSize = buf.st_size;
3666
drh8af6c222010-05-14 12:43:01 +00003667 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003668 ** writes a single byte into that file in order to work around a bug
3669 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3670 ** layers, we need to report this file size as zero even though it is
3671 ** really 1. Ticket #3260.
3672 */
3673 if( *pSize==1 ) *pSize = 0;
3674
3675
3676 return SQLITE_OK;
3677}
3678
drhd2cb50b2009-01-09 21:41:17 +00003679#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003680/*
3681** Handler for proxy-locking file-control verbs. Defined below in the
3682** proxying locking division.
3683*/
3684static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003685#endif
drh715ff302008-12-03 22:32:44 +00003686
dan502019c2010-07-28 14:26:17 +00003687/*
3688** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003689** file-control operation. Enlarge the database to nBytes in size
3690** (rounded up to the next chunk-size). If the database is already
3691** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003692*/
3693static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003694 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003695 i64 nSize; /* Required file size */
3696 struct stat buf; /* Used to hold return values of fstat() */
3697
drh4bf66fd2015-02-19 02:43:02 +00003698 if( osFstat(pFile->h, &buf) ){
3699 return SQLITE_IOERR_FSTAT;
3700 }
dan502019c2010-07-28 14:26:17 +00003701
3702 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3703 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003704
dan502019c2010-07-28 14:26:17 +00003705#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003706 /* The code below is handling the return value of osFallocate()
3707 ** correctly. posix_fallocate() is defined to "returns zero on success,
3708 ** or an error number on failure". See the manpage for details. */
3709 int err;
drhff812312011-02-23 13:33:46 +00003710 do{
dan661d71a2011-03-30 19:08:03 +00003711 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3712 }while( err==EINTR );
3713 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003714#else
dan592bf7f2014-12-30 19:58:31 +00003715 /* If the OS does not have posix_fallocate(), fake it. Write a
3716 ** single byte to the last byte in each block that falls entirely
3717 ** within the extended region. Then, if required, a single byte
3718 ** at offset (nSize-1), to set the size of the file correctly.
3719 ** This is a similar technique to that used by glibc on systems
3720 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003721 */
3722 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003723 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003724 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003725
dan502019c2010-07-28 14:26:17 +00003726 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003727 assert( iWrite>=buf.st_size );
3728 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3729 assert( ((iWrite+1)%nBlk)==0 );
3730 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003731 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003732 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003733 }
danef3d66c2015-01-06 21:31:47 +00003734 if( nWrite==0 || (nSize%nBlk) ){
3735 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003736 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003737 }
dan502019c2010-07-28 14:26:17 +00003738#endif
3739 }
3740 }
3741
mistachkine98844f2013-08-24 00:59:24 +00003742#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003743 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003744 int rc;
3745 if( pFile->szChunk<=0 ){
3746 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003747 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003748 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3749 }
3750 }
3751
3752 rc = unixMapfile(pFile, nByte);
3753 return rc;
3754 }
mistachkine98844f2013-08-24 00:59:24 +00003755#endif
danf23da962013-03-23 21:00:41 +00003756
dan502019c2010-07-28 14:26:17 +00003757 return SQLITE_OK;
3758}
danielk1977ad94b582007-08-20 06:44:22 +00003759
danielk1977e3026632004-06-22 11:29:02 +00003760/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003761** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003762** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3763**
3764** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3765*/
3766static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3767 if( *pArg<0 ){
3768 *pArg = (pFile->ctrlFlags & mask)!=0;
3769 }else if( (*pArg)==0 ){
3770 pFile->ctrlFlags &= ~mask;
3771 }else{
3772 pFile->ctrlFlags |= mask;
3773 }
3774}
3775
drh696b33e2012-12-06 19:01:42 +00003776/* Forward declaration */
3777static int unixGetTempname(int nBuf, char *zBuf);
3778
drhf12b3f62011-12-21 14:42:29 +00003779/*
drh9e33c2c2007-08-31 18:34:59 +00003780** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003781*/
drhcc6bb3e2007-08-31 16:11:35 +00003782static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003783 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003784 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003785 case SQLITE_FCNTL_WAL_BLOCK: {
3786 pFile->ctrlFlags |= UNIXFILE_BLOCK;
3787 return SQLITE_OK;
3788 }
drh9e33c2c2007-08-31 18:34:59 +00003789 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003790 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003791 return SQLITE_OK;
3792 }
drh4bf66fd2015-02-19 02:43:02 +00003793 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003794 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003795 return SQLITE_OK;
3796 }
dan6e09d692010-07-27 18:34:15 +00003797 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003798 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003799 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003800 }
drh9ff27ec2010-05-19 19:26:05 +00003801 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003802 int rc;
3803 SimulateIOErrorBenign(1);
3804 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3805 SimulateIOErrorBenign(0);
3806 return rc;
drhf0b190d2011-07-26 16:03:07 +00003807 }
3808 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003809 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3810 return SQLITE_OK;
3811 }
drhcb15f352011-12-23 01:04:17 +00003812 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3813 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003814 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003815 }
drhde60fc22011-12-14 17:53:36 +00003816 case SQLITE_FCNTL_VFSNAME: {
3817 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3818 return SQLITE_OK;
3819 }
drh696b33e2012-12-06 19:01:42 +00003820 case SQLITE_FCNTL_TEMPFILENAME: {
3821 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3822 if( zTFile ){
3823 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3824 *(char**)pArg = zTFile;
3825 }
3826 return SQLITE_OK;
3827 }
drhb959a012013-12-07 12:29:22 +00003828 case SQLITE_FCNTL_HAS_MOVED: {
3829 *(int*)pArg = fileHasMoved(pFile);
3830 return SQLITE_OK;
3831 }
mistachkine98844f2013-08-24 00:59:24 +00003832#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003833 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003834 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003835 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003836 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3837 newLimit = sqlite3GlobalConfig.mxMmap;
3838 }
3839 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003840 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003841 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003842 if( pFile->mmapSize>0 ){
3843 unixUnmapfile(pFile);
3844 rc = unixMapfile(pFile, -1);
3845 }
danbcb8a862013-04-08 15:30:41 +00003846 }
drh34e258c2013-05-23 01:40:53 +00003847 return rc;
danb2d3de32013-03-14 18:34:37 +00003848 }
mistachkine98844f2013-08-24 00:59:24 +00003849#endif
drhd3d8c042012-05-29 17:02:40 +00003850#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003851 /* The pager calls this method to signal that it has done
3852 ** a rollback and that the database is therefore unchanged and
3853 ** it hence it is OK for the transaction change counter to be
3854 ** unchanged.
3855 */
3856 case SQLITE_FCNTL_DB_UNCHANGED: {
3857 ((unixFile*)id)->dbUpdate = 0;
3858 return SQLITE_OK;
3859 }
3860#endif
drhd2cb50b2009-01-09 21:41:17 +00003861#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003862 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3863 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003864 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003865 }
drhd2cb50b2009-01-09 21:41:17 +00003866#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003867 }
drh0b52b7d2011-01-26 19:46:22 +00003868 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003869}
3870
3871/*
danielk1977a3d4c882007-03-23 10:08:38 +00003872** Return the sector size in bytes of the underlying block device for
3873** the specified file. This is almost always 512 bytes, but may be
3874** larger for some devices.
3875**
3876** SQLite code assumes this function cannot fail. It also assumes that
3877** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003878** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003879** same for both.
3880*/
drh537dddf2012-10-26 13:46:24 +00003881#ifndef __QNXNTO__
3882static int unixSectorSize(sqlite3_file *NotUsed){
3883 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003884 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003885}
drh537dddf2012-10-26 13:46:24 +00003886#endif
3887
3888/*
3889** The following version of unixSectorSize() is optimized for QNX.
3890*/
3891#ifdef __QNXNTO__
3892#include <sys/dcmd_blk.h>
3893#include <sys/statvfs.h>
3894static int unixSectorSize(sqlite3_file *id){
3895 unixFile *pFile = (unixFile*)id;
3896 if( pFile->sectorSize == 0 ){
3897 struct statvfs fsInfo;
3898
3899 /* Set defaults for non-supported filesystems */
3900 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3901 pFile->deviceCharacteristics = 0;
3902 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3903 return pFile->sectorSize;
3904 }
3905
3906 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3907 pFile->sectorSize = fsInfo.f_bsize;
3908 pFile->deviceCharacteristics =
3909 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3910 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3911 ** the write succeeds */
3912 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3913 ** so it is ordered */
3914 0;
3915 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3916 pFile->sectorSize = fsInfo.f_bsize;
3917 pFile->deviceCharacteristics =
3918 /* etfs cluster size writes are atomic */
3919 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3920 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3921 ** the write succeeds */
3922 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3923 ** so it is ordered */
3924 0;
3925 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3926 pFile->sectorSize = fsInfo.f_bsize;
3927 pFile->deviceCharacteristics =
3928 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3929 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3930 ** the write succeeds */
3931 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3932 ** so it is ordered */
3933 0;
3934 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3935 pFile->sectorSize = fsInfo.f_bsize;
3936 pFile->deviceCharacteristics =
3937 /* full bitset of atomics from max sector size and smaller */
3938 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3939 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3940 ** so it is ordered */
3941 0;
3942 }else if( strstr(fsInfo.f_basetype, "dos") ){
3943 pFile->sectorSize = fsInfo.f_bsize;
3944 pFile->deviceCharacteristics =
3945 /* full bitset of atomics from max sector size and smaller */
3946 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3947 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3948 ** so it is ordered */
3949 0;
3950 }else{
3951 pFile->deviceCharacteristics =
3952 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3953 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3954 ** the write succeeds */
3955 0;
3956 }
3957 }
3958 /* Last chance verification. If the sector size isn't a multiple of 512
3959 ** then it isn't valid.*/
3960 if( pFile->sectorSize % 512 != 0 ){
3961 pFile->deviceCharacteristics = 0;
3962 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3963 }
3964 return pFile->sectorSize;
3965}
3966#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003967
danielk197790949c22007-08-17 16:50:38 +00003968/*
drhf12b3f62011-12-21 14:42:29 +00003969** Return the device characteristics for the file.
3970**
drhcb15f352011-12-23 01:04:17 +00003971** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003972** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003973** file system does not always provide powersafe overwrites. (In other
3974** words, after a power-loss event, parts of the file that were never
3975** written might end up being altered.) However, non-PSOW behavior is very,
3976** very rare. And asserting PSOW makes a large reduction in the amount
3977** of required I/O for journaling, since a lot of padding is eliminated.
3978** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3979** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003980*/
drhf12b3f62011-12-21 14:42:29 +00003981static int unixDeviceCharacteristics(sqlite3_file *id){
3982 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003983 int rc = 0;
3984#ifdef __QNXNTO__
3985 if( p->sectorSize==0 ) unixSectorSize(id);
3986 rc = p->deviceCharacteristics;
3987#endif
drhcb15f352011-12-23 01:04:17 +00003988 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003989 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003990 }
drh537dddf2012-10-26 13:46:24 +00003991 return rc;
danielk197762079062007-08-15 17:08:46 +00003992}
3993
dan702eec12014-06-23 10:04:58 +00003994#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003995
dan702eec12014-06-23 10:04:58 +00003996/*
3997** Return the system page size.
3998**
3999** This function should not be called directly by other code in this file.
4000** Instead, it should be called via macro osGetpagesize().
4001*/
4002static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004003#if OS_VXWORKS
4004 return 1024;
4005#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004006 return getpagesize();
4007#else
4008 return (int)sysconf(_SC_PAGESIZE);
4009#endif
4010}
4011
4012#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4013
4014#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004015
4016/*
drhd91c68f2010-05-14 14:52:25 +00004017** Object used to represent an shared memory buffer.
4018**
4019** When multiple threads all reference the same wal-index, each thread
4020** has its own unixShm object, but they all point to a single instance
4021** of this unixShmNode object. In other words, each wal-index is opened
4022** only once per process.
4023**
4024** Each unixShmNode object is connected to a single unixInodeInfo object.
4025** We could coalesce this object into unixInodeInfo, but that would mean
4026** every open file that does not use shared memory (in other words, most
4027** open files) would have to carry around this extra information. So
4028** the unixInodeInfo object contains a pointer to this unixShmNode object
4029** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004030**
4031** unixMutexHeld() must be true when creating or destroying
4032** this object or while reading or writing the following fields:
4033**
4034** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004035**
4036** The following fields are read-only after the object is created:
4037**
4038** fid
4039** zFilename
4040**
drhd91c68f2010-05-14 14:52:25 +00004041** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004042** unixMutexHeld() is true when reading or writing any other field
4043** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004044*/
drhd91c68f2010-05-14 14:52:25 +00004045struct unixShmNode {
4046 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004047 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004048 char *zFilename; /* Name of the mmapped file */
4049 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004050 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004051 u16 nRegion; /* Size of array apRegion */
4052 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004053 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004054 int nRef; /* Number of unixShm objects pointing to this */
4055 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004056#ifdef SQLITE_DEBUG
4057 u8 exclMask; /* Mask of exclusive locks held */
4058 u8 sharedMask; /* Mask of shared locks held */
4059 u8 nextShmId; /* Next available unixShm.id value */
4060#endif
4061};
4062
4063/*
drhd9e5c4f2010-05-12 18:01:39 +00004064** Structure used internally by this VFS to record the state of an
4065** open shared memory connection.
4066**
drhd91c68f2010-05-14 14:52:25 +00004067** The following fields are initialized when this object is created and
4068** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004069**
drhd91c68f2010-05-14 14:52:25 +00004070** unixShm.pFile
4071** unixShm.id
4072**
4073** All other fields are read/write. The unixShm.pFile->mutex must be held
4074** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004075*/
4076struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004077 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4078 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004079 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004080 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004081 u16 sharedMask; /* Mask of shared locks held */
4082 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004083};
4084
4085/*
drhd9e5c4f2010-05-12 18:01:39 +00004086** Constants used for locking
4087*/
drhbd9676c2010-06-23 17:58:38 +00004088#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004089#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004090
drhd9e5c4f2010-05-12 18:01:39 +00004091/*
drh73b64e42010-05-30 19:55:15 +00004092** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004093**
4094** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4095** otherwise.
4096*/
4097static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004098 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004099 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004100 int ofst, /* First byte of the locking range */
4101 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004102){
drhbbf76ee2015-03-10 20:22:35 +00004103 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4104 struct flock f; /* The posix advisory locking structure */
4105 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004106
drhd91c68f2010-05-14 14:52:25 +00004107 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004108 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004109 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004110
drh73b64e42010-05-30 19:55:15 +00004111 /* Shared locks never span more than one byte */
4112 assert( n==1 || lockType!=F_RDLCK );
4113
4114 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004115 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004116
drh3cb93392011-03-12 18:10:44 +00004117 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004118 int lkType;
drh3cb93392011-03-12 18:10:44 +00004119 /* Initialize the locking parameters */
4120 memset(&f, 0, sizeof(f));
4121 f.l_type = lockType;
4122 f.l_whence = SEEK_SET;
4123 f.l_start = ofst;
4124 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004125
drhbbf76ee2015-03-10 20:22:35 +00004126 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4127 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004128 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004129 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004130 }
drhd9e5c4f2010-05-12 18:01:39 +00004131
4132 /* Update the global lock state and do debug tracing */
4133#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004134 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004135 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004136 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004137 if( rc==SQLITE_OK ){
4138 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004139 OSTRACE(("unlock %d ok", ofst));
4140 pShmNode->exclMask &= ~mask;
4141 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004142 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004143 OSTRACE(("read-lock %d ok", ofst));
4144 pShmNode->exclMask &= ~mask;
4145 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004146 }else{
4147 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004148 OSTRACE(("write-lock %d ok", ofst));
4149 pShmNode->exclMask |= mask;
4150 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004151 }
4152 }else{
4153 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004154 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004155 }else if( lockType==F_RDLCK ){
4156 OSTRACE(("read-lock failed"));
4157 }else{
4158 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004159 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004160 }
4161 }
drh20e1f082010-05-31 16:10:12 +00004162 OSTRACE((" - afterwards %03x,%03x\n",
4163 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004164 }
drhd9e5c4f2010-05-12 18:01:39 +00004165#endif
4166
4167 return rc;
4168}
4169
dan781e34c2014-03-20 08:59:47 +00004170/*
dan781e34c2014-03-20 08:59:47 +00004171** Return the minimum number of 32KB shm regions that should be mapped at
4172** a time, assuming that each mapping must be an integer multiple of the
4173** current system page-size.
4174**
4175** Usually, this is 1. The exception seems to be systems that are configured
4176** to use 64KB pages - in this case each mapping must cover at least two
4177** shm regions.
4178*/
4179static int unixShmRegionPerMap(void){
4180 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004181 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004182 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4183 if( pgsz<shmsz ) return 1;
4184 return pgsz/shmsz;
4185}
drhd9e5c4f2010-05-12 18:01:39 +00004186
4187/*
drhd91c68f2010-05-14 14:52:25 +00004188** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004189**
4190** This is not a VFS shared-memory method; it is a utility function called
4191** by VFS shared-memory methods.
4192*/
drhd91c68f2010-05-14 14:52:25 +00004193static void unixShmPurge(unixFile *pFd){
4194 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004195 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004196 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004197 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004198 int i;
drhd91c68f2010-05-14 14:52:25 +00004199 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004200 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004201 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004202 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004203 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004204 }else{
4205 sqlite3_free(p->apRegion[i]);
4206 }
dan13a3cb82010-06-11 19:04:21 +00004207 }
dan18801912010-06-14 14:07:50 +00004208 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004209 if( p->h>=0 ){
4210 robust_close(pFd, p->h, __LINE__);
4211 p->h = -1;
4212 }
drhd91c68f2010-05-14 14:52:25 +00004213 p->pInode->pShmNode = 0;
4214 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004215 }
4216}
4217
4218/*
danda9fe0c2010-07-13 18:44:03 +00004219** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004220** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004221**
drh7234c6d2010-06-19 15:10:09 +00004222** The file used to implement shared-memory is in the same directory
4223** as the open database file and has the same name as the open database
4224** file with the "-shm" suffix added. For example, if the database file
4225** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004226** for shared memory will be called "/home/user1/config.db-shm".
4227**
4228** Another approach to is to use files in /dev/shm or /dev/tmp or an
4229** some other tmpfs mount. But if a file in a different directory
4230** from the database file is used, then differing access permissions
4231** or a chroot() might cause two different processes on the same
4232** database to end up using different files for shared memory -
4233** meaning that their memory would not really be shared - resulting
4234** in database corruption. Nevertheless, this tmpfs file usage
4235** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4236** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4237** option results in an incompatible build of SQLite; builds of SQLite
4238** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4239** same database file at the same time, database corruption will likely
4240** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4241** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004242**
4243** When opening a new shared-memory file, if no other instances of that
4244** file are currently open, in this process or in other processes, then
4245** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004246**
4247** If the original database file (pDbFd) is using the "unix-excl" VFS
4248** that means that an exclusive lock is held on the database file and
4249** that no other processes are able to read or write the database. In
4250** that case, we do not really need shared memory. No shared memory
4251** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004252*/
danda9fe0c2010-07-13 18:44:03 +00004253static int unixOpenSharedMemory(unixFile *pDbFd){
4254 struct unixShm *p = 0; /* The connection to be opened */
4255 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4256 int rc; /* Result code */
4257 unixInodeInfo *pInode; /* The inode of fd */
4258 char *zShmFilename; /* Name of the file used for SHM */
4259 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004260
danda9fe0c2010-07-13 18:44:03 +00004261 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004262 p = sqlite3_malloc( sizeof(*p) );
4263 if( p==0 ) return SQLITE_NOMEM;
4264 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004265 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004266
danda9fe0c2010-07-13 18:44:03 +00004267 /* Check to see if a unixShmNode object already exists. Reuse an existing
4268 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004269 */
4270 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004271 pInode = pDbFd->pInode;
4272 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004273 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004274 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004275#ifndef SQLITE_SHM_DIRECTORY
4276 const char *zBasePath = pDbFd->zPath;
4277#endif
danddb0ac42010-07-14 14:48:58 +00004278
4279 /* Call fstat() to figure out the permissions on the database file. If
4280 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004281 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004282 */
drh3cb93392011-03-12 18:10:44 +00004283 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004284 rc = SQLITE_IOERR_FSTAT;
4285 goto shm_open_err;
4286 }
4287
drha4ced192010-07-15 18:32:40 +00004288#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004289 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004290#else
drh4bf66fd2015-02-19 02:43:02 +00004291 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004292#endif
drh7234c6d2010-06-19 15:10:09 +00004293 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004294 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004295 rc = SQLITE_NOMEM;
4296 goto shm_open_err;
4297 }
drh9cb5a0d2012-01-05 21:19:54 +00004298 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004299 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004300#ifdef SQLITE_SHM_DIRECTORY
4301 sqlite3_snprintf(nShmFilename, zShmFilename,
4302 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4303 (u32)sStat.st_ino, (u32)sStat.st_dev);
4304#else
drh4bf66fd2015-02-19 02:43:02 +00004305 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004306 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004307#endif
drhd91c68f2010-05-14 14:52:25 +00004308 pShmNode->h = -1;
4309 pDbFd->pInode->pShmNode = pShmNode;
4310 pShmNode->pInode = pDbFd->pInode;
4311 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4312 if( pShmNode->mutex==0 ){
4313 rc = SQLITE_NOMEM;
4314 goto shm_open_err;
4315 }
drhd9e5c4f2010-05-12 18:01:39 +00004316
drh3cb93392011-03-12 18:10:44 +00004317 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004318 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004319 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004320 openFlags = O_RDONLY;
4321 pShmNode->isReadonly = 1;
4322 }
4323 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004324 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004325 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4326 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004327 }
drhac7c3ac2012-02-11 19:23:48 +00004328
4329 /* If this process is running as root, make sure that the SHM file
4330 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004331 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004332 */
drhed466822012-05-31 13:10:49 +00004333 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004334
4335 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004336 ** If not, truncate the file to zero length.
4337 */
4338 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004339 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004340 if( robust_ftruncate(pShmNode->h, 0) ){
4341 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004342 }
4343 }
drh66dfec8b2011-06-01 20:01:49 +00004344 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004345 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004346 }
4347 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004348 }
drhd9e5c4f2010-05-12 18:01:39 +00004349 }
4350
drhd91c68f2010-05-14 14:52:25 +00004351 /* Make the new connection a child of the unixShmNode */
4352 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004353#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004354 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004355#endif
drhd91c68f2010-05-14 14:52:25 +00004356 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004357 pDbFd->pShm = p;
4358 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004359
4360 /* The reference count on pShmNode has already been incremented under
4361 ** the cover of the unixEnterMutex() mutex and the pointer from the
4362 ** new (struct unixShm) object to the pShmNode has been set. All that is
4363 ** left to do is to link the new object into the linked list starting
4364 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4365 ** mutex.
4366 */
4367 sqlite3_mutex_enter(pShmNode->mutex);
4368 p->pNext = pShmNode->pFirst;
4369 pShmNode->pFirst = p;
4370 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004371 return SQLITE_OK;
4372
4373 /* Jump here on any error */
4374shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004375 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004376 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004377 unixLeaveMutex();
4378 return rc;
4379}
4380
4381/*
danda9fe0c2010-07-13 18:44:03 +00004382** This function is called to obtain a pointer to region iRegion of the
4383** shared-memory associated with the database file fd. Shared-memory regions
4384** are numbered starting from zero. Each shared-memory region is szRegion
4385** bytes in size.
4386**
4387** If an error occurs, an error code is returned and *pp is set to NULL.
4388**
4389** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4390** region has not been allocated (by any client, including one running in a
4391** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4392** bExtend is non-zero and the requested shared-memory region has not yet
4393** been allocated, it is allocated by this function.
4394**
4395** If the shared-memory region has already been allocated or is allocated by
4396** this call as described above, then it is mapped into this processes
4397** address space (if it is not already), *pp is set to point to the mapped
4398** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004399*/
danda9fe0c2010-07-13 18:44:03 +00004400static int unixShmMap(
4401 sqlite3_file *fd, /* Handle open on database file */
4402 int iRegion, /* Region to retrieve */
4403 int szRegion, /* Size of regions */
4404 int bExtend, /* True to extend file if necessary */
4405 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004406){
danda9fe0c2010-07-13 18:44:03 +00004407 unixFile *pDbFd = (unixFile*)fd;
4408 unixShm *p;
4409 unixShmNode *pShmNode;
4410 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004411 int nShmPerMap = unixShmRegionPerMap();
4412 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004413
danda9fe0c2010-07-13 18:44:03 +00004414 /* If the shared-memory file has not yet been opened, open it now. */
4415 if( pDbFd->pShm==0 ){
4416 rc = unixOpenSharedMemory(pDbFd);
4417 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004418 }
drhd9e5c4f2010-05-12 18:01:39 +00004419
danda9fe0c2010-07-13 18:44:03 +00004420 p = pDbFd->pShm;
4421 pShmNode = p->pShmNode;
4422 sqlite3_mutex_enter(pShmNode->mutex);
4423 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004424 assert( pShmNode->pInode==pDbFd->pInode );
4425 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4426 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004427
dan781e34c2014-03-20 08:59:47 +00004428 /* Minimum number of regions required to be mapped. */
4429 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4430
4431 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004432 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004433 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004434 struct stat sStat; /* Used by fstat() */
4435
4436 pShmNode->szRegion = szRegion;
4437
drh3cb93392011-03-12 18:10:44 +00004438 if( pShmNode->h>=0 ){
4439 /* The requested region is not mapped into this processes address space.
4440 ** Check to see if it has been allocated (i.e. if the wal-index file is
4441 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004442 */
drh3cb93392011-03-12 18:10:44 +00004443 if( osFstat(pShmNode->h, &sStat) ){
4444 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004445 goto shmpage_out;
4446 }
drh3cb93392011-03-12 18:10:44 +00004447
4448 if( sStat.st_size<nByte ){
4449 /* The requested memory region does not exist. If bExtend is set to
4450 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004451 */
dan47a2b4a2013-04-26 16:09:29 +00004452 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004453 goto shmpage_out;
4454 }
dan47a2b4a2013-04-26 16:09:29 +00004455
4456 /* Alternatively, if bExtend is true, extend the file. Do this by
4457 ** writing a single byte to the end of each (OS) page being
4458 ** allocated or extended. Technically, we need only write to the
4459 ** last page in order to extend the file. But writing to all new
4460 ** pages forces the OS to allocate them immediately, which reduces
4461 ** the chances of SIGBUS while accessing the mapped region later on.
4462 */
4463 else{
4464 static const int pgsz = 4096;
4465 int iPg;
4466
4467 /* Write to the last byte of each newly allocated or extended page */
4468 assert( (nByte % pgsz)==0 );
4469 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4470 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4471 const char *zFile = pShmNode->zFilename;
4472 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4473 goto shmpage_out;
4474 }
4475 }
drh3cb93392011-03-12 18:10:44 +00004476 }
4477 }
danda9fe0c2010-07-13 18:44:03 +00004478 }
4479
4480 /* Map the requested memory region into this processes address space. */
4481 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004482 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004483 );
4484 if( !apNew ){
4485 rc = SQLITE_IOERR_NOMEM;
4486 goto shmpage_out;
4487 }
4488 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004489 while( pShmNode->nRegion<nReqRegion ){
4490 int nMap = szRegion*nShmPerMap;
4491 int i;
drh3cb93392011-03-12 18:10:44 +00004492 void *pMem;
4493 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004494 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004495 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004496 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004497 );
4498 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004499 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004500 goto shmpage_out;
4501 }
4502 }else{
4503 pMem = sqlite3_malloc(szRegion);
4504 if( pMem==0 ){
4505 rc = SQLITE_NOMEM;
4506 goto shmpage_out;
4507 }
4508 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004509 }
dan781e34c2014-03-20 08:59:47 +00004510
4511 for(i=0; i<nShmPerMap; i++){
4512 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4513 }
4514 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004515 }
4516 }
4517
4518shmpage_out:
4519 if( pShmNode->nRegion>iRegion ){
4520 *pp = pShmNode->apRegion[iRegion];
4521 }else{
4522 *pp = 0;
4523 }
drh66dfec8b2011-06-01 20:01:49 +00004524 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004525 sqlite3_mutex_leave(pShmNode->mutex);
4526 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004527}
4528
4529/*
drhd9e5c4f2010-05-12 18:01:39 +00004530** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004531**
4532** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4533** different here than in posix. In xShmLock(), one can go from unlocked
4534** to shared and back or from unlocked to exclusive and back. But one may
4535** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004536*/
4537static int unixShmLock(
4538 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004539 int ofst, /* First lock to acquire or release */
4540 int n, /* Number of locks to acquire or release */
4541 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004542){
drh73b64e42010-05-30 19:55:15 +00004543 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4544 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4545 unixShm *pX; /* For looping over all siblings */
4546 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4547 int rc = SQLITE_OK; /* Result code */
4548 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004549
drhd91c68f2010-05-14 14:52:25 +00004550 assert( pShmNode==pDbFd->pInode->pShmNode );
4551 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004552 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004553 assert( n>=1 );
4554 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4555 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4556 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4557 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4558 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004559 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4560 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004561
drhc99597c2010-05-31 01:41:15 +00004562 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004563 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004564 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004565 if( flags & SQLITE_SHM_UNLOCK ){
4566 u16 allMask = 0; /* Mask of locks held by siblings */
4567
4568 /* See if any siblings hold this same lock */
4569 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4570 if( pX==p ) continue;
4571 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4572 allMask |= pX->sharedMask;
4573 }
4574
4575 /* Unlock the system-level locks */
4576 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004577 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004578 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004579 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004580 }
drh73b64e42010-05-30 19:55:15 +00004581
4582 /* Undo the local locks */
4583 if( rc==SQLITE_OK ){
4584 p->exclMask &= ~mask;
4585 p->sharedMask &= ~mask;
4586 }
4587 }else if( flags & SQLITE_SHM_SHARED ){
4588 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4589
4590 /* Find out which shared locks are already held by sibling connections.
4591 ** If any sibling already holds an exclusive lock, go ahead and return
4592 ** SQLITE_BUSY.
4593 */
4594 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004595 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004596 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004597 break;
4598 }
4599 allShared |= pX->sharedMask;
4600 }
4601
4602 /* Get shared locks at the system level, if necessary */
4603 if( rc==SQLITE_OK ){
4604 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004605 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004606 }else{
drh73b64e42010-05-30 19:55:15 +00004607 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004608 }
drhd9e5c4f2010-05-12 18:01:39 +00004609 }
drh73b64e42010-05-30 19:55:15 +00004610
4611 /* Get the local shared locks */
4612 if( rc==SQLITE_OK ){
4613 p->sharedMask |= mask;
4614 }
4615 }else{
4616 /* Make sure no sibling connections hold locks that will block this
4617 ** lock. If any do, return SQLITE_BUSY right away.
4618 */
4619 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004620 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4621 rc = SQLITE_BUSY;
4622 break;
4623 }
4624 }
4625
4626 /* Get the exclusive locks at the system level. Then if successful
4627 ** also mark the local connection as being locked.
4628 */
4629 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004630 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004631 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004632 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004633 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004634 }
drhd9e5c4f2010-05-12 18:01:39 +00004635 }
4636 }
drhd91c68f2010-05-14 14:52:25 +00004637 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004638 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh91eb93c2015-03-03 19:56:20 +00004639 p->id, osGetpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004640 return rc;
4641}
4642
drh286a2882010-05-20 23:51:06 +00004643/*
4644** Implement a memory barrier or memory fence on shared memory.
4645**
4646** All loads and stores begun before the barrier must complete before
4647** any load or store begun after the barrier.
4648*/
4649static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004650 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004651){
drhff828942010-06-26 21:34:06 +00004652 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004653 unixEnterMutex();
4654 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004655}
4656
dan18801912010-06-14 14:07:50 +00004657/*
danda9fe0c2010-07-13 18:44:03 +00004658** Close a connection to shared-memory. Delete the underlying
4659** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004660**
4661** If there is no shared memory associated with the connection then this
4662** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004663*/
danda9fe0c2010-07-13 18:44:03 +00004664static int unixShmUnmap(
4665 sqlite3_file *fd, /* The underlying database file */
4666 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004667){
danda9fe0c2010-07-13 18:44:03 +00004668 unixShm *p; /* The connection to be closed */
4669 unixShmNode *pShmNode; /* The underlying shared-memory file */
4670 unixShm **pp; /* For looping over sibling connections */
4671 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004672
danda9fe0c2010-07-13 18:44:03 +00004673 pDbFd = (unixFile*)fd;
4674 p = pDbFd->pShm;
4675 if( p==0 ) return SQLITE_OK;
4676 pShmNode = p->pShmNode;
4677
4678 assert( pShmNode==pDbFd->pInode->pShmNode );
4679 assert( pShmNode->pInode==pDbFd->pInode );
4680
4681 /* Remove connection p from the set of connections associated
4682 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004683 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004684 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4685 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004686
danda9fe0c2010-07-13 18:44:03 +00004687 /* Free the connection p */
4688 sqlite3_free(p);
4689 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004690 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004691
4692 /* If pShmNode->nRef has reached 0, then close the underlying
4693 ** shared-memory file, too */
4694 unixEnterMutex();
4695 assert( pShmNode->nRef>0 );
4696 pShmNode->nRef--;
4697 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004698 if( deleteFlag && pShmNode->h>=0 ){
4699 osUnlink(pShmNode->zFilename);
4700 }
danda9fe0c2010-07-13 18:44:03 +00004701 unixShmPurge(pDbFd);
4702 }
4703 unixLeaveMutex();
4704
4705 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004706}
drh286a2882010-05-20 23:51:06 +00004707
danda9fe0c2010-07-13 18:44:03 +00004708
drhd9e5c4f2010-05-12 18:01:39 +00004709#else
drh6b017cc2010-06-14 18:01:46 +00004710# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004711# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004712# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004713# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004714#endif /* #ifndef SQLITE_OMIT_WAL */
4715
mistachkine98844f2013-08-24 00:59:24 +00004716#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004717/*
danaef49d72013-03-25 16:28:54 +00004718** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004719*/
danf23da962013-03-23 21:00:41 +00004720static void unixUnmapfile(unixFile *pFd){
4721 assert( pFd->nFetchOut==0 );
4722 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004723 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004724 pFd->pMapRegion = 0;
4725 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004726 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004727 }
4728}
dan5d8a1372013-03-19 19:28:06 +00004729
danaef49d72013-03-25 16:28:54 +00004730/*
dane6ecd662013-04-01 17:56:59 +00004731** Attempt to set the size of the memory mapping maintained by file
4732** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4733**
4734** If successful, this function sets the following variables:
4735**
4736** unixFile.pMapRegion
4737** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004738** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004739**
4740** If unsuccessful, an error message is logged via sqlite3_log() and
4741** the three variables above are zeroed. In this case SQLite should
4742** continue accessing the database using the xRead() and xWrite()
4743** methods.
4744*/
4745static void unixRemapfile(
4746 unixFile *pFd, /* File descriptor object */
4747 i64 nNew /* Required mapping size */
4748){
dan4ff7bc42013-04-02 12:04:09 +00004749 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004750 int h = pFd->h; /* File descriptor open on db file */
4751 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004752 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004753 u8 *pNew = 0; /* Location of new mapping */
4754 int flags = PROT_READ; /* Flags to pass to mmap() */
4755
4756 assert( pFd->nFetchOut==0 );
4757 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004758 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004759 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004760 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004761 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004762
4763 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4764
4765 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004766#if HAVE_MREMAP
4767 i64 nReuse = pFd->mmapSize;
4768#else
danbc760632014-03-20 09:42:09 +00004769 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004770 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004771#endif
dane6ecd662013-04-01 17:56:59 +00004772 u8 *pReq = &pOrig[nReuse];
4773
4774 /* Unmap any pages of the existing mapping that cannot be reused. */
4775 if( nReuse!=nOrig ){
4776 osMunmap(pReq, nOrig-nReuse);
4777 }
4778
4779#if HAVE_MREMAP
4780 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004781 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004782#else
4783 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4784 if( pNew!=MAP_FAILED ){
4785 if( pNew!=pReq ){
4786 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004787 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004788 }else{
4789 pNew = pOrig;
4790 }
4791 }
4792#endif
4793
dan48ccef82013-04-02 20:55:01 +00004794 /* The attempt to extend the existing mapping failed. Free it. */
4795 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004796 osMunmap(pOrig, nReuse);
4797 }
4798 }
4799
4800 /* If pNew is still NULL, try to create an entirely new mapping. */
4801 if( pNew==0 ){
4802 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004803 }
4804
dan4ff7bc42013-04-02 12:04:09 +00004805 if( pNew==MAP_FAILED ){
4806 pNew = 0;
4807 nNew = 0;
4808 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4809
4810 /* If the mmap() above failed, assume that all subsequent mmap() calls
4811 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4812 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004813 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004814 }
dane6ecd662013-04-01 17:56:59 +00004815 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004816 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004817}
4818
4819/*
danaef49d72013-03-25 16:28:54 +00004820** Memory map or remap the file opened by file-descriptor pFd (if the file
4821** is already mapped, the existing mapping is replaced by the new). Or, if
4822** there already exists a mapping for this file, and there are still
4823** outstanding xFetch() references to it, this function is a no-op.
4824**
4825** If parameter nByte is non-negative, then it is the requested size of
4826** the mapping to create. Otherwise, if nByte is less than zero, then the
4827** requested size is the size of the file on disk. The actual size of the
4828** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004829** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004830**
4831** SQLITE_OK is returned if no error occurs (even if the mapping is not
4832** recreated as a result of outstanding references) or an SQLite error
4833** code otherwise.
4834*/
danf23da962013-03-23 21:00:41 +00004835static int unixMapfile(unixFile *pFd, i64 nByte){
4836 i64 nMap = nByte;
4837 int rc;
daneb97b292013-03-20 14:26:59 +00004838
danf23da962013-03-23 21:00:41 +00004839 assert( nMap>=0 || pFd->nFetchOut==0 );
4840 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4841
4842 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004843 struct stat statbuf; /* Low-level file information */
4844 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004845 if( rc!=SQLITE_OK ){
4846 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004847 }
drh3044b512014-06-16 16:41:52 +00004848 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004849 }
drh9b4c59f2013-04-15 17:03:42 +00004850 if( nMap>pFd->mmapSizeMax ){
4851 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004852 }
4853
danf23da962013-03-23 21:00:41 +00004854 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004855 if( nMap>0 ){
4856 unixRemapfile(pFd, nMap);
4857 }else{
danb7e3a322013-03-25 20:30:13 +00004858 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004859 }
4860 }
4861
danf23da962013-03-23 21:00:41 +00004862 return SQLITE_OK;
4863}
mistachkine98844f2013-08-24 00:59:24 +00004864#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004865
danaef49d72013-03-25 16:28:54 +00004866/*
4867** If possible, return a pointer to a mapping of file fd starting at offset
4868** iOff. The mapping must be valid for at least nAmt bytes.
4869**
4870** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4871** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4872** Finally, if an error does occur, return an SQLite error code. The final
4873** value of *pp is undefined in this case.
4874**
4875** If this function does return a pointer, the caller must eventually
4876** release the reference by calling unixUnfetch().
4877*/
danf23da962013-03-23 21:00:41 +00004878static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004879#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004880 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004881#endif
danf23da962013-03-23 21:00:41 +00004882 *pp = 0;
4883
drh9b4c59f2013-04-15 17:03:42 +00004884#if SQLITE_MAX_MMAP_SIZE>0
4885 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004886 if( pFd->pMapRegion==0 ){
4887 int rc = unixMapfile(pFd, -1);
4888 if( rc!=SQLITE_OK ) return rc;
4889 }
4890 if( pFd->mmapSize >= iOff+nAmt ){
4891 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4892 pFd->nFetchOut++;
4893 }
4894 }
drh6e0b6d52013-04-09 16:19:20 +00004895#endif
danf23da962013-03-23 21:00:41 +00004896 return SQLITE_OK;
4897}
4898
danaef49d72013-03-25 16:28:54 +00004899/*
dandf737fe2013-03-25 17:00:24 +00004900** If the third argument is non-NULL, then this function releases a
4901** reference obtained by an earlier call to unixFetch(). The second
4902** argument passed to this function must be the same as the corresponding
4903** argument that was passed to the unixFetch() invocation.
4904**
4905** Or, if the third argument is NULL, then this function is being called
4906** to inform the VFS layer that, according to POSIX, any existing mapping
4907** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004908*/
dandf737fe2013-03-25 17:00:24 +00004909static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004910#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004911 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004912 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004913
danaef49d72013-03-25 16:28:54 +00004914 /* If p==0 (unmap the entire file) then there must be no outstanding
4915 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4916 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004917 assert( (p==0)==(pFd->nFetchOut==0) );
4918
dandf737fe2013-03-25 17:00:24 +00004919 /* If p!=0, it must match the iOff value. */
4920 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4921
danf23da962013-03-23 21:00:41 +00004922 if( p ){
4923 pFd->nFetchOut--;
4924 }else{
4925 unixUnmapfile(pFd);
4926 }
4927
4928 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004929#else
4930 UNUSED_PARAMETER(fd);
4931 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004932 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004933#endif
danf23da962013-03-23 21:00:41 +00004934 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004935}
4936
4937/*
drh734c9862008-11-28 15:37:20 +00004938** Here ends the implementation of all sqlite3_file methods.
4939**
4940********************** End sqlite3_file Methods *******************************
4941******************************************************************************/
4942
4943/*
drh6b9d6dd2008-12-03 19:34:47 +00004944** This division contains definitions of sqlite3_io_methods objects that
4945** implement various file locking strategies. It also contains definitions
4946** of "finder" functions. A finder-function is used to locate the appropriate
4947** sqlite3_io_methods object for a particular database file. The pAppData
4948** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4949** the correct finder-function for that VFS.
4950**
4951** Most finder functions return a pointer to a fixed sqlite3_io_methods
4952** object. The only interesting finder-function is autolockIoFinder, which
4953** looks at the filesystem type and tries to guess the best locking
4954** strategy from that.
4955**
peter.d.reid60ec9142014-09-06 16:39:46 +00004956** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004957**
4958** (1) The real finder-function named "FImpt()".
4959**
dane946c392009-08-22 11:39:46 +00004960** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004961**
4962**
4963** A pointer to the F pointer is used as the pAppData value for VFS
4964** objects. We have to do this instead of letting pAppData point
4965** directly at the finder-function since C90 rules prevent a void*
4966** from be cast into a function pointer.
4967**
drh6b9d6dd2008-12-03 19:34:47 +00004968**
drh7708e972008-11-29 00:56:52 +00004969** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004970**
drh7708e972008-11-29 00:56:52 +00004971** * A constant sqlite3_io_methods object call METHOD that has locking
4972** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4973**
4974** * An I/O method finder function called FINDER that returns a pointer
4975** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004976*/
drhe6d41732015-02-21 00:49:00 +00004977#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004978static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004979 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004980 CLOSE, /* xClose */ \
4981 unixRead, /* xRead */ \
4982 unixWrite, /* xWrite */ \
4983 unixTruncate, /* xTruncate */ \
4984 unixSync, /* xSync */ \
4985 unixFileSize, /* xFileSize */ \
4986 LOCK, /* xLock */ \
4987 UNLOCK, /* xUnlock */ \
4988 CKLOCK, /* xCheckReservedLock */ \
4989 unixFileControl, /* xFileControl */ \
4990 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004991 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004992 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004993 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004994 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004995 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004996 unixFetch, /* xFetch */ \
4997 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004998}; \
drh0c2694b2009-09-03 16:23:44 +00004999static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5000 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005001 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005002} \
drh0c2694b2009-09-03 16:23:44 +00005003static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005004 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005005
5006/*
5007** Here are all of the sqlite3_io_methods objects for each of the
5008** locking strategies. Functions that return pointers to these methods
5009** are also created.
5010*/
5011IOMETHODS(
5012 posixIoFinder, /* Finder function name */
5013 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005014 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005015 unixClose, /* xClose method */
5016 unixLock, /* xLock method */
5017 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005018 unixCheckReservedLock, /* xCheckReservedLock method */
5019 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005020)
drh7708e972008-11-29 00:56:52 +00005021IOMETHODS(
5022 nolockIoFinder, /* Finder function name */
5023 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005024 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005025 nolockClose, /* xClose method */
5026 nolockLock, /* xLock method */
5027 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005028 nolockCheckReservedLock, /* xCheckReservedLock method */
5029 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005030)
drh7708e972008-11-29 00:56:52 +00005031IOMETHODS(
5032 dotlockIoFinder, /* Finder function name */
5033 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005034 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005035 dotlockClose, /* xClose method */
5036 dotlockLock, /* xLock method */
5037 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005038 dotlockCheckReservedLock, /* xCheckReservedLock method */
5039 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005040)
drh7708e972008-11-29 00:56:52 +00005041
drhe89b2912015-03-03 20:42:01 +00005042#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005043IOMETHODS(
5044 flockIoFinder, /* Finder function name */
5045 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005046 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005047 flockClose, /* xClose method */
5048 flockLock, /* xLock method */
5049 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005050 flockCheckReservedLock, /* xCheckReservedLock method */
5051 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005052)
drh7708e972008-11-29 00:56:52 +00005053#endif
5054
drh6c7d5c52008-11-21 20:32:33 +00005055#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005056IOMETHODS(
5057 semIoFinder, /* Finder function name */
5058 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005059 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005060 semXClose, /* xClose method */
5061 semXLock, /* xLock method */
5062 semXUnlock, /* xUnlock method */
5063 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005064 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005065)
aswiftaebf4132008-11-21 00:10:35 +00005066#endif
drh7708e972008-11-29 00:56:52 +00005067
drhd2cb50b2009-01-09 21:41:17 +00005068#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005069IOMETHODS(
5070 afpIoFinder, /* Finder function name */
5071 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005072 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005073 afpClose, /* xClose method */
5074 afpLock, /* xLock method */
5075 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005076 afpCheckReservedLock, /* xCheckReservedLock method */
5077 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005078)
drh715ff302008-12-03 22:32:44 +00005079#endif
5080
5081/*
5082** The proxy locking method is a "super-method" in the sense that it
5083** opens secondary file descriptors for the conch and lock files and
5084** it uses proxy, dot-file, AFP, and flock() locking methods on those
5085** secondary files. For this reason, the division that implements
5086** proxy locking is located much further down in the file. But we need
5087** to go ahead and define the sqlite3_io_methods and finder function
5088** for proxy locking here. So we forward declare the I/O methods.
5089*/
drhd2cb50b2009-01-09 21:41:17 +00005090#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005091static int proxyClose(sqlite3_file*);
5092static int proxyLock(sqlite3_file*, int);
5093static int proxyUnlock(sqlite3_file*, int);
5094static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005095IOMETHODS(
5096 proxyIoFinder, /* Finder function name */
5097 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005098 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005099 proxyClose, /* xClose method */
5100 proxyLock, /* xLock method */
5101 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005102 proxyCheckReservedLock, /* xCheckReservedLock method */
5103 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005104)
aswiftaebf4132008-11-21 00:10:35 +00005105#endif
drh7708e972008-11-29 00:56:52 +00005106
drh7ed97b92010-01-20 13:07:21 +00005107/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5108#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5109IOMETHODS(
5110 nfsIoFinder, /* Finder function name */
5111 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005112 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005113 unixClose, /* xClose method */
5114 unixLock, /* xLock method */
5115 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005116 unixCheckReservedLock, /* xCheckReservedLock method */
5117 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005118)
5119#endif
drh7708e972008-11-29 00:56:52 +00005120
drhd2cb50b2009-01-09 21:41:17 +00005121#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005122/*
drh6b9d6dd2008-12-03 19:34:47 +00005123** This "finder" function attempts to determine the best locking strategy
5124** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005125** object that implements that strategy.
5126**
5127** This is for MacOSX only.
5128*/
drh1875f7a2008-12-08 18:19:17 +00005129static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005130 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005131 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005132){
5133 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005134 const char *zFilesystem; /* Filesystem type name */
5135 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005136 } aMap[] = {
5137 { "hfs", &posixIoMethods },
5138 { "ufs", &posixIoMethods },
5139 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005140 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005141 { "webdav", &nolockIoMethods },
5142 { 0, 0 }
5143 };
5144 int i;
5145 struct statfs fsInfo;
5146 struct flock lockInfo;
5147
5148 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005149 /* If filePath==NULL that means we are dealing with a transient file
5150 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005151 return &nolockIoMethods;
5152 }
5153 if( statfs(filePath, &fsInfo) != -1 ){
5154 if( fsInfo.f_flags & MNT_RDONLY ){
5155 return &nolockIoMethods;
5156 }
5157 for(i=0; aMap[i].zFilesystem; i++){
5158 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5159 return aMap[i].pMethods;
5160 }
5161 }
5162 }
5163
5164 /* Default case. Handles, amongst others, "nfs".
5165 ** Test byte-range lock using fcntl(). If the call succeeds,
5166 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005167 */
drh7708e972008-11-29 00:56:52 +00005168 lockInfo.l_len = 1;
5169 lockInfo.l_start = 0;
5170 lockInfo.l_whence = SEEK_SET;
5171 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005172 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005173 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5174 return &nfsIoMethods;
5175 } else {
5176 return &posixIoMethods;
5177 }
drh7708e972008-11-29 00:56:52 +00005178 }else{
5179 return &dotlockIoMethods;
5180 }
5181}
drh0c2694b2009-09-03 16:23:44 +00005182static const sqlite3_io_methods
5183 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005184
drhd2cb50b2009-01-09 21:41:17 +00005185#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005186
drhe89b2912015-03-03 20:42:01 +00005187#if OS_VXWORKS
5188/*
5189** This "finder" function for VxWorks checks to see if posix advisory
5190** locking works. If it does, then that is what is used. If it does not
5191** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005192*/
drhe89b2912015-03-03 20:42:01 +00005193static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005194 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005195 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005196){
5197 struct flock lockInfo;
5198
5199 if( !filePath ){
5200 /* If filePath==NULL that means we are dealing with a transient file
5201 ** that does not need to be locked. */
5202 return &nolockIoMethods;
5203 }
5204
5205 /* Test if fcntl() is supported and use POSIX style locks.
5206 ** Otherwise fall back to the named semaphore method.
5207 */
5208 lockInfo.l_len = 1;
5209 lockInfo.l_start = 0;
5210 lockInfo.l_whence = SEEK_SET;
5211 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005212 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005213 return &posixIoMethods;
5214 }else{
5215 return &semIoMethods;
5216 }
5217}
drh0c2694b2009-09-03 16:23:44 +00005218static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005219 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005220
drhe89b2912015-03-03 20:42:01 +00005221#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005222
drh7708e972008-11-29 00:56:52 +00005223/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005224** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005225*/
drh0c2694b2009-09-03 16:23:44 +00005226typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005227
aswiftaebf4132008-11-21 00:10:35 +00005228
drh734c9862008-11-28 15:37:20 +00005229/****************************************************************************
5230**************************** sqlite3_vfs methods ****************************
5231**
5232** This division contains the implementation of methods on the
5233** sqlite3_vfs object.
5234*/
5235
danielk1977a3d4c882007-03-23 10:08:38 +00005236/*
danielk1977e339d652008-06-28 11:23:00 +00005237** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005238*/
5239static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005240 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005241 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005242 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005243 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005244 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005245){
drh7708e972008-11-29 00:56:52 +00005246 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005247 unixFile *pNew = (unixFile *)pId;
5248 int rc = SQLITE_OK;
5249
drh8af6c222010-05-14 12:43:01 +00005250 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005251
dan00157392010-10-05 11:33:15 +00005252 /* Usually the path zFilename should not be a relative pathname. The
5253 ** exception is when opening the proxy "conch" file in builds that
5254 ** include the special Apple locking styles.
5255 */
dan00157392010-10-05 11:33:15 +00005256#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005257 assert( zFilename==0 || zFilename[0]=='/'
5258 || pVfs->pAppData==(void*)&autolockIoFinder );
5259#else
5260 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005261#endif
dan00157392010-10-05 11:33:15 +00005262
drhb07028f2011-10-14 21:49:18 +00005263 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005264 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005265
drh308c2a52010-05-14 11:30:18 +00005266 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005267 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005268 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005269 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005270 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005271#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005272 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005273#endif
drhc02a43a2012-01-10 23:18:38 +00005274 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5275 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005276 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005277 }
drh503a6862013-03-01 01:07:17 +00005278 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005279 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005280 }
drh339eb0b2008-03-07 15:34:11 +00005281
drh6c7d5c52008-11-21 20:32:33 +00005282#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005283 pNew->pId = vxworksFindFileId(zFilename);
5284 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005285 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005286 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005287 }
5288#endif
5289
drhc02a43a2012-01-10 23:18:38 +00005290 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005291 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005292 }else{
drh0c2694b2009-09-03 16:23:44 +00005293 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005294#if SQLITE_ENABLE_LOCKING_STYLE
5295 /* Cache zFilename in the locking context (AFP and dotlock override) for
5296 ** proxyLock activation is possible (remote proxy is based on db name)
5297 ** zFilename remains valid until file is closed, to support */
5298 pNew->lockingContext = (void*)zFilename;
5299#endif
drhda0e7682008-07-30 15:27:54 +00005300 }
danielk1977e339d652008-06-28 11:23:00 +00005301
drh7ed97b92010-01-20 13:07:21 +00005302 if( pLockingStyle == &posixIoMethods
5303#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5304 || pLockingStyle == &nfsIoMethods
5305#endif
5306 ){
drh7708e972008-11-29 00:56:52 +00005307 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005308 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005309 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005310 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005311 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005312 ** in two scenarios:
5313 **
5314 ** (a) A call to fstat() failed.
5315 ** (b) A malloc failed.
5316 **
5317 ** Scenario (b) may only occur if the process is holding no other
5318 ** file descriptors open on the same file. If there were other file
5319 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005320 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005321 ** handle h - as it is guaranteed that no posix locks will be released
5322 ** by doing so.
5323 **
5324 ** If scenario (a) caused the error then things are not so safe. The
5325 ** implicit assumption here is that if fstat() fails, things are in
5326 ** such bad shape that dropping a lock or two doesn't matter much.
5327 */
drh0e9365c2011-03-02 02:08:13 +00005328 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005329 h = -1;
5330 }
drh7708e972008-11-29 00:56:52 +00005331 unixLeaveMutex();
5332 }
danielk1977e339d652008-06-28 11:23:00 +00005333
drhd2cb50b2009-01-09 21:41:17 +00005334#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005335 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005336 /* AFP locking uses the file path so it needs to be included in
5337 ** the afpLockingContext.
5338 */
5339 afpLockingContext *pCtx;
5340 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5341 if( pCtx==0 ){
5342 rc = SQLITE_NOMEM;
5343 }else{
5344 /* NB: zFilename exists and remains valid until the file is closed
5345 ** according to requirement F11141. So we do not need to make a
5346 ** copy of the filename. */
5347 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005348 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005349 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005350 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005351 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005352 if( rc!=SQLITE_OK ){
5353 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005354 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005355 h = -1;
5356 }
drh7708e972008-11-29 00:56:52 +00005357 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005358 }
drh7708e972008-11-29 00:56:52 +00005359 }
5360#endif
danielk1977e339d652008-06-28 11:23:00 +00005361
drh7708e972008-11-29 00:56:52 +00005362 else if( pLockingStyle == &dotlockIoMethods ){
5363 /* Dotfile locking uses the file path so it needs to be included in
5364 ** the dotlockLockingContext
5365 */
5366 char *zLockFile;
5367 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005368 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005369 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005370 zLockFile = (char *)sqlite3_malloc(nFilename);
5371 if( zLockFile==0 ){
5372 rc = SQLITE_NOMEM;
5373 }else{
5374 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005375 }
drh7708e972008-11-29 00:56:52 +00005376 pNew->lockingContext = zLockFile;
5377 }
danielk1977e339d652008-06-28 11:23:00 +00005378
drh6c7d5c52008-11-21 20:32:33 +00005379#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005380 else if( pLockingStyle == &semIoMethods ){
5381 /* Named semaphore locking uses the file path so it needs to be
5382 ** included in the semLockingContext
5383 */
5384 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005385 rc = findInodeInfo(pNew, &pNew->pInode);
5386 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5387 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005388 int n;
drh2238dcc2009-08-27 17:56:20 +00005389 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005390 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005391 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005392 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005393 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5394 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005395 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005396 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005397 }
chw97185482008-11-17 08:05:31 +00005398 }
drh7708e972008-11-29 00:56:52 +00005399 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005400 }
drh7708e972008-11-29 00:56:52 +00005401#endif
aswift5b1a2562008-08-22 00:22:35 +00005402
drh4bf66fd2015-02-19 02:43:02 +00005403 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005404#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005405 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005406 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005407 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005408 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005409 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005410 }
chw97185482008-11-17 08:05:31 +00005411#endif
danielk1977e339d652008-06-28 11:23:00 +00005412 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005413 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005414 }else{
drh7708e972008-11-29 00:56:52 +00005415 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005416 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005417 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005418 }
danielk1977e339d652008-06-28 11:23:00 +00005419 return rc;
drh054889e2005-11-30 03:20:31 +00005420}
drh9c06c952005-11-26 00:25:00 +00005421
danielk1977ad94b582007-08-20 06:44:22 +00005422/*
drh8b3cf822010-06-01 21:02:51 +00005423** Return the name of a directory in which to put temporary files.
5424** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005425*/
drh7234c6d2010-06-19 15:10:09 +00005426static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005427 static const char *azDirs[] = {
5428 0,
aswiftaebf4132008-11-21 00:10:35 +00005429 0,
mistachkind95a3d32013-08-30 21:52:38 +00005430 0,
danielk197717b90b52008-06-06 11:11:25 +00005431 "/var/tmp",
5432 "/usr/tmp",
5433 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005434 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005435 };
drh8b3cf822010-06-01 21:02:51 +00005436 unsigned int i;
5437 struct stat buf;
5438 const char *zDir = 0;
5439
5440 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005441 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5442 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005443 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005444 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005445 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005446 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005447 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005448 break;
5449 }
5450 return zDir;
5451}
5452
5453/*
5454** Create a temporary file name in zBuf. zBuf must be allocated
5455** by the calling process and must be big enough to hold at least
5456** pVfs->mxPathname bytes.
5457*/
5458static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005459 static const unsigned char zChars[] =
5460 "abcdefghijklmnopqrstuvwxyz"
5461 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5462 "0123456789";
drh41022642008-11-21 00:24:42 +00005463 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005464 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005465
5466 /* It's odd to simulate an io-error here, but really this is just
5467 ** using the io-error infrastructure to test that SQLite handles this
5468 ** function failing.
5469 */
5470 SimulateIOError( return SQLITE_IOERR );
5471
drh7234c6d2010-06-19 15:10:09 +00005472 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005473 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005474
5475 /* Check that the output buffer is large enough for the temporary file
5476 ** name. If it is not, return SQLITE_ERROR.
5477 */
drhc02a43a2012-01-10 23:18:38 +00005478 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005479 return SQLITE_ERROR;
5480 }
5481
5482 do{
drhc02a43a2012-01-10 23:18:38 +00005483 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005484 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005485 sqlite3_randomness(15, &zBuf[j]);
5486 for(i=0; i<15; i++, j++){
5487 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5488 }
5489 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005490 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005491 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005492 return SQLITE_OK;
5493}
5494
drhd2cb50b2009-01-09 21:41:17 +00005495#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005496/*
5497** Routine to transform a unixFile into a proxy-locking unixFile.
5498** Implementation in the proxy-lock division, but used by unixOpen()
5499** if SQLITE_PREFER_PROXY_LOCKING is defined.
5500*/
5501static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005502#endif
drhc66d5b62008-12-03 22:48:32 +00005503
dan08da86a2009-08-21 17:18:03 +00005504/*
5505** Search for an unused file descriptor that was opened on the database
5506** file (not a journal or master-journal file) identified by pathname
5507** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5508** argument to this function.
5509**
5510** Such a file descriptor may exist if a database connection was closed
5511** but the associated file descriptor could not be closed because some
5512** other file descriptor open on the same file is holding a file-lock.
5513** Refer to comments in the unixClose() function and the lengthy comment
5514** describing "Posix Advisory Locking" at the start of this file for
5515** further details. Also, ticket #4018.
5516**
5517** If a suitable file descriptor is found, then it is returned. If no
5518** such file descriptor is located, -1 is returned.
5519*/
dane946c392009-08-22 11:39:46 +00005520static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5521 UnixUnusedFd *pUnused = 0;
5522
5523 /* Do not search for an unused file descriptor on vxworks. Not because
5524 ** vxworks would not benefit from the change (it might, we're not sure),
5525 ** but because no way to test it is currently available. It is better
5526 ** not to risk breaking vxworks support for the sake of such an obscure
5527 ** feature. */
5528#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005529 struct stat sStat; /* Results of stat() call */
5530
5531 /* A stat() call may fail for various reasons. If this happens, it is
5532 ** almost certain that an open() call on the same path will also fail.
5533 ** For this reason, if an error occurs in the stat() call here, it is
5534 ** ignored and -1 is returned. The caller will try to open a new file
5535 ** descriptor on the same path, fail, and return an error to SQLite.
5536 **
5537 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005538 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005539 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005540 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005541
5542 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005543 pInode = inodeList;
5544 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5545 || pInode->fileId.ino!=sStat.st_ino) ){
5546 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005547 }
drh8af6c222010-05-14 12:43:01 +00005548 if( pInode ){
dane946c392009-08-22 11:39:46 +00005549 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005550 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005551 pUnused = *pp;
5552 if( pUnused ){
5553 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005554 }
5555 }
5556 unixLeaveMutex();
5557 }
dane946c392009-08-22 11:39:46 +00005558#endif /* if !OS_VXWORKS */
5559 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005560}
danielk197717b90b52008-06-06 11:11:25 +00005561
5562/*
danddb0ac42010-07-14 14:48:58 +00005563** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005564** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005565** and a value suitable for passing as the third argument to open(2) is
5566** written to *pMode. If an IO error occurs, an SQLite error code is
5567** returned and the value of *pMode is not modified.
5568**
peter.d.reid60ec9142014-09-06 16:39:46 +00005569** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005570** an indication to robust_open() to create the file using
5571** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5572** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005573** this function queries the file-system for the permissions on the
5574** corresponding database file and sets *pMode to this value. Whenever
5575** possible, WAL and journal files are created using the same permissions
5576** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005577**
5578** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5579** original filename is unavailable. But 8_3_NAMES is only used for
5580** FAT filesystems and permissions do not matter there, so just use
5581** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005582*/
5583static int findCreateFileMode(
5584 const char *zPath, /* Path of file (possibly) being created */
5585 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005586 mode_t *pMode, /* OUT: Permissions to open file with */
5587 uid_t *pUid, /* OUT: uid to set on the file */
5588 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005589){
5590 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005591 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005592 *pUid = 0;
5593 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005594 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005595 char zDb[MAX_PATHNAME+1]; /* Database file path */
5596 int nDb; /* Number of valid bytes in zDb */
5597 struct stat sStat; /* Output of stat() on database file */
5598
dana0c989d2010-11-05 18:07:37 +00005599 /* zPath is a path to a WAL or journal file. The following block derives
5600 ** the path to the associated database file from zPath. This block handles
5601 ** the following naming conventions:
5602 **
5603 ** "<path to db>-journal"
5604 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005605 ** "<path to db>-journalNN"
5606 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005607 **
drhd337c5b2011-10-20 18:23:35 +00005608 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005609 ** used by the test_multiplex.c module.
5610 */
5611 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005612#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005613 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005614 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005615#else
5616 while( zPath[nDb]!='-' ){
5617 assert( nDb>0 );
5618 assert( zPath[nDb]!='\n' );
5619 nDb--;
5620 }
5621#endif
danddb0ac42010-07-14 14:48:58 +00005622 memcpy(zDb, zPath, nDb);
5623 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005624
drh58384f12011-07-28 00:14:45 +00005625 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005626 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005627 *pUid = sStat.st_uid;
5628 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005629 }else{
5630 rc = SQLITE_IOERR_FSTAT;
5631 }
5632 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5633 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005634 }
5635 return rc;
5636}
5637
5638/*
danielk1977ad94b582007-08-20 06:44:22 +00005639** Open the file zPath.
5640**
danielk1977b4b47412007-08-17 15:53:36 +00005641** Previously, the SQLite OS layer used three functions in place of this
5642** one:
5643**
5644** sqlite3OsOpenReadWrite();
5645** sqlite3OsOpenReadOnly();
5646** sqlite3OsOpenExclusive();
5647**
5648** These calls correspond to the following combinations of flags:
5649**
5650** ReadWrite() -> (READWRITE | CREATE)
5651** ReadOnly() -> (READONLY)
5652** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5653**
5654** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5655** true, the file was configured to be automatically deleted when the
5656** file handle closed. To achieve the same effect using this new
5657** interface, add the DELETEONCLOSE flag to those specified above for
5658** OpenExclusive().
5659*/
5660static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005661 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5662 const char *zPath, /* Pathname of file to be opened */
5663 sqlite3_file *pFile, /* The file descriptor to be filled in */
5664 int flags, /* Input flags to control the opening */
5665 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005666){
dan08da86a2009-08-21 17:18:03 +00005667 unixFile *p = (unixFile *)pFile;
5668 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005669 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005670 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005671 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005672 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005673 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005674
5675 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5676 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5677 int isCreate = (flags & SQLITE_OPEN_CREATE);
5678 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5679 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005680#if SQLITE_ENABLE_LOCKING_STYLE
5681 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5682#endif
drh3d4435b2011-08-26 20:55:50 +00005683#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5684 struct statfs fsInfo;
5685#endif
danielk1977b4b47412007-08-17 15:53:36 +00005686
danielk1977fee2d252007-08-18 10:59:19 +00005687 /* If creating a master or main-file journal, this function will open
5688 ** a file-descriptor on the directory too. The first time unixSync()
5689 ** is called the directory file descriptor will be fsync()ed and close()d.
5690 */
drh0059eae2011-08-08 23:48:40 +00005691 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005692 eType==SQLITE_OPEN_MASTER_JOURNAL
5693 || eType==SQLITE_OPEN_MAIN_JOURNAL
5694 || eType==SQLITE_OPEN_WAL
5695 ));
danielk1977fee2d252007-08-18 10:59:19 +00005696
danielk197717b90b52008-06-06 11:11:25 +00005697 /* If argument zPath is a NULL pointer, this function is required to open
5698 ** a temporary file. Use this buffer to store the file name in.
5699 */
drhc02a43a2012-01-10 23:18:38 +00005700 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005701 const char *zName = zPath;
5702
danielk1977fee2d252007-08-18 10:59:19 +00005703 /* Check the following statements are true:
5704 **
5705 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5706 ** (b) if CREATE is set, then READWRITE must also be set, and
5707 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005708 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005709 */
danielk1977b4b47412007-08-17 15:53:36 +00005710 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005711 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005712 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005713 assert(isDelete==0 || isCreate);
5714
danddb0ac42010-07-14 14:48:58 +00005715 /* The main DB, main journal, WAL file and master journal are never
5716 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005717 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5718 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5719 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005720 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005721
danielk1977fee2d252007-08-18 10:59:19 +00005722 /* Assert that the upper layer has set one of the "file-type" flags. */
5723 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5724 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5725 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005726 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005727 );
5728
drhb00d8622014-01-01 15:18:36 +00005729 /* Detect a pid change and reset the PRNG. There is a race condition
5730 ** here such that two or more threads all trying to open databases at
5731 ** the same instant might all reset the PRNG. But multiple resets
5732 ** are harmless.
5733 */
drh91eb93c2015-03-03 19:56:20 +00005734 if( randomnessPid!=osGetpid() ){
5735 randomnessPid = osGetpid();
drhb00d8622014-01-01 15:18:36 +00005736 sqlite3_randomness(0,0);
5737 }
5738
dan08da86a2009-08-21 17:18:03 +00005739 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005740
dan08da86a2009-08-21 17:18:03 +00005741 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005742 UnixUnusedFd *pUnused;
5743 pUnused = findReusableFd(zName, flags);
5744 if( pUnused ){
5745 fd = pUnused->fd;
5746 }else{
dan6aa657f2009-08-24 18:57:58 +00005747 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005748 if( !pUnused ){
5749 return SQLITE_NOMEM;
5750 }
5751 }
5752 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005753
5754 /* Database filenames are double-zero terminated if they are not
5755 ** URIs with parameters. Hence, they can always be passed into
5756 ** sqlite3_uri_parameter(). */
5757 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5758
dan08da86a2009-08-21 17:18:03 +00005759 }else if( !zName ){
5760 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005761 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005762 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005763 if( rc!=SQLITE_OK ){
5764 return rc;
5765 }
5766 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005767
5768 /* Generated temporary filenames are always double-zero terminated
5769 ** for use by sqlite3_uri_parameter(). */
5770 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005771 }
5772
dan08da86a2009-08-21 17:18:03 +00005773 /* Determine the value of the flags parameter passed to POSIX function
5774 ** open(). These must be calculated even if open() is not called, as
5775 ** they may be stored as part of the file handle and used by the
5776 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005777 if( isReadonly ) openFlags |= O_RDONLY;
5778 if( isReadWrite ) openFlags |= O_RDWR;
5779 if( isCreate ) openFlags |= O_CREAT;
5780 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5781 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005782
danielk1977b4b47412007-08-17 15:53:36 +00005783 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005784 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005785 uid_t uid; /* Userid for the file */
5786 gid_t gid; /* Groupid for the file */
5787 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005788 if( rc!=SQLITE_OK ){
5789 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005790 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005791 return rc;
5792 }
drhad4f1e52011-03-04 15:43:57 +00005793 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005794 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005795 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5796 /* Failed to open the file for read/write access. Try read-only. */
5797 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005798 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005799 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005800 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005801 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005802 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005803 }
5804 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005805 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005806 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005807 }
drhac7c3ac2012-02-11 19:23:48 +00005808
5809 /* If this process is running as root and if creating a new rollback
5810 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005811 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005812 */
5813 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005814 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005815 }
danielk1977b4b47412007-08-17 15:53:36 +00005816 }
dan08da86a2009-08-21 17:18:03 +00005817 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005818 if( pOutFlags ){
5819 *pOutFlags = flags;
5820 }
5821
dane946c392009-08-22 11:39:46 +00005822 if( p->pUnused ){
5823 p->pUnused->fd = fd;
5824 p->pUnused->flags = flags;
5825 }
5826
danielk1977b4b47412007-08-17 15:53:36 +00005827 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005828#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005829 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005830#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5831 zPath = sqlite3_mprintf("%s", zName);
5832 if( zPath==0 ){
5833 robust_close(p, fd, __LINE__);
5834 return SQLITE_NOMEM;
5835 }
chw97185482008-11-17 08:05:31 +00005836#else
drh036ac7f2011-08-08 23:18:05 +00005837 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005838#endif
danielk1977b4b47412007-08-17 15:53:36 +00005839 }
drh41022642008-11-21 00:24:42 +00005840#if SQLITE_ENABLE_LOCKING_STYLE
5841 else{
dan08da86a2009-08-21 17:18:03 +00005842 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005843 }
5844#endif
5845
drhda0e7682008-07-30 15:27:54 +00005846 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005847
drh7ed97b92010-01-20 13:07:21 +00005848
5849#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005850 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005851 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005852 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005853 return SQLITE_IOERR_ACCESS;
5854 }
5855 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5856 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5857 }
drh4bf66fd2015-02-19 02:43:02 +00005858 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5859 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5860 }
drh7ed97b92010-01-20 13:07:21 +00005861#endif
drhc02a43a2012-01-10 23:18:38 +00005862
5863 /* Set up appropriate ctrlFlags */
5864 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5865 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5866 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5867 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5868 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5869
drh7ed97b92010-01-20 13:07:21 +00005870#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005871#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005872 isAutoProxy = 1;
5873#endif
5874 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005875 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5876 int useProxy = 0;
5877
dan08da86a2009-08-21 17:18:03 +00005878 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5879 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005880 if( envforce!=NULL ){
5881 useProxy = atoi(envforce)>0;
5882 }else{
aswiftaebf4132008-11-21 00:10:35 +00005883 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5884 }
5885 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005886 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005887 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005888 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005889 if( rc!=SQLITE_OK ){
5890 /* Use unixClose to clean up the resources added in fillInUnixFile
5891 ** and clear all the structure's references. Specifically,
5892 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5893 */
5894 unixClose(pFile);
5895 return rc;
5896 }
aswiftaebf4132008-11-21 00:10:35 +00005897 }
dane946c392009-08-22 11:39:46 +00005898 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005899 }
5900 }
5901#endif
5902
drhc02a43a2012-01-10 23:18:38 +00005903 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5904
dane946c392009-08-22 11:39:46 +00005905open_finished:
5906 if( rc!=SQLITE_OK ){
5907 sqlite3_free(p->pUnused);
5908 }
5909 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005910}
5911
dane946c392009-08-22 11:39:46 +00005912
danielk1977b4b47412007-08-17 15:53:36 +00005913/*
danielk1977fee2d252007-08-18 10:59:19 +00005914** Delete the file at zPath. If the dirSync argument is true, fsync()
5915** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005916*/
drh6b9d6dd2008-12-03 19:34:47 +00005917static int unixDelete(
5918 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5919 const char *zPath, /* Name of file to be deleted */
5920 int dirSync /* If true, fsync() directory after deleting file */
5921){
danielk1977fee2d252007-08-18 10:59:19 +00005922 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005923 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005924 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005925 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005926 if( errno==ENOENT
5927#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005928 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005929#endif
5930 ){
dan9fc5b4a2012-11-09 20:17:26 +00005931 rc = SQLITE_IOERR_DELETE_NOENT;
5932 }else{
drhb4308162012-11-09 21:40:02 +00005933 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005934 }
drhb4308162012-11-09 21:40:02 +00005935 return rc;
drh5d4feff2010-07-14 01:45:22 +00005936 }
danielk1977d39fa702008-10-16 13:27:40 +00005937#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005938 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005939 int fd;
drh90315a22011-08-10 01:52:12 +00005940 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005941 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005942#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005943 if( fsync(fd)==-1 )
5944#else
5945 if( fsync(fd) )
5946#endif
5947 {
dane18d4952011-02-21 11:46:24 +00005948 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005949 }
drh0e9365c2011-03-02 02:08:13 +00005950 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005951 }else if( rc==SQLITE_CANTOPEN ){
5952 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005953 }
5954 }
danielk1977d138dd82008-10-15 16:02:48 +00005955#endif
danielk1977fee2d252007-08-18 10:59:19 +00005956 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005957}
5958
danielk197790949c22007-08-17 16:50:38 +00005959/*
mistachkin48864df2013-03-21 21:20:32 +00005960** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005961** test performed depends on the value of flags:
5962**
5963** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5964** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5965** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5966**
5967** Otherwise return 0.
5968*/
danielk1977861f7452008-06-05 11:39:11 +00005969static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005970 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5971 const char *zPath, /* Path of the file to examine */
5972 int flags, /* What do we want to learn about the zPath file? */
5973 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005974){
rse25c0d1a2007-09-20 08:38:14 +00005975 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005976 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005977 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005978 switch( flags ){
5979 case SQLITE_ACCESS_EXISTS:
5980 amode = F_OK;
5981 break;
5982 case SQLITE_ACCESS_READWRITE:
5983 amode = W_OK|R_OK;
5984 break;
drh50d3f902007-08-27 21:10:36 +00005985 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005986 amode = R_OK;
5987 break;
5988
5989 default:
5990 assert(!"Invalid flags argument");
5991 }
drh99ab3b12011-03-02 15:09:07 +00005992 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005993 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5994 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005995 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005996 *pResOut = 0;
5997 }
5998 }
danielk1977861f7452008-06-05 11:39:11 +00005999 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006000}
6001
danielk1977b4b47412007-08-17 15:53:36 +00006002
6003/*
6004** Turn a relative pathname into a full pathname. The relative path
6005** is stored as a nul-terminated string in the buffer pointed to by
6006** zPath.
6007**
6008** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6009** (in this case, MAX_PATHNAME bytes). The full-path is written to
6010** this buffer before returning.
6011*/
danielk1977adfb9b02007-09-17 07:02:56 +00006012static int unixFullPathname(
6013 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6014 const char *zPath, /* Possibly relative input path */
6015 int nOut, /* Size of output buffer in bytes */
6016 char *zOut /* Output buffer */
6017){
danielk1977843e65f2007-09-01 16:16:15 +00006018
6019 /* It's odd to simulate an io-error here, but really this is just
6020 ** using the io-error infrastructure to test that SQLite handles this
6021 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006022 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006023 */
6024 SimulateIOError( return SQLITE_ERROR );
6025
drh153c62c2007-08-24 03:51:33 +00006026 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006027 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006028
drh3c7f2dc2007-12-06 13:26:20 +00006029 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006030 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006031 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006032 }else{
6033 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006034 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006035 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006036 }
drhea678832008-12-10 19:26:22 +00006037 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006038 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006039 }
6040 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006041}
6042
drh0ccebe72005-06-07 22:22:50 +00006043
drh761df872006-12-21 01:29:22 +00006044#ifndef SQLITE_OMIT_LOAD_EXTENSION
6045/*
6046** Interfaces for opening a shared library, finding entry points
6047** within the shared library, and closing the shared library.
6048*/
6049#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006050static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6051 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006052 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6053}
danielk197795c8a542007-09-01 06:51:27 +00006054
6055/*
6056** SQLite calls this function immediately after a call to unixDlSym() or
6057** unixDlOpen() fails (returns a null pointer). If a more detailed error
6058** message is available, it is written to zBufOut. If no error message
6059** is available, zBufOut is left unmodified and SQLite uses a default
6060** error message.
6061*/
danielk1977397d65f2008-11-19 11:35:39 +00006062static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006063 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006064 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006065 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006066 zErr = dlerror();
6067 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006068 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006069 }
drh6c7d5c52008-11-21 20:32:33 +00006070 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006071}
drh1875f7a2008-12-08 18:19:17 +00006072static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6073 /*
6074 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6075 ** cast into a pointer to a function. And yet the library dlsym() routine
6076 ** returns a void* which is really a pointer to a function. So how do we
6077 ** use dlsym() with -pedantic-errors?
6078 **
6079 ** Variable x below is defined to be a pointer to a function taking
6080 ** parameters void* and const char* and returning a pointer to a function.
6081 ** We initialize x by assigning it a pointer to the dlsym() function.
6082 ** (That assignment requires a cast.) Then we call the function that
6083 ** x points to.
6084 **
6085 ** This work-around is unlikely to work correctly on any system where
6086 ** you really cannot cast a function pointer into void*. But then, on the
6087 ** other hand, dlsym() will not work on such a system either, so we have
6088 ** not really lost anything.
6089 */
6090 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006091 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006092 x = (void(*(*)(void*,const char*))(void))dlsym;
6093 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006094}
danielk1977397d65f2008-11-19 11:35:39 +00006095static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6096 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006097 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006098}
danielk1977b4b47412007-08-17 15:53:36 +00006099#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6100 #define unixDlOpen 0
6101 #define unixDlError 0
6102 #define unixDlSym 0
6103 #define unixDlClose 0
6104#endif
6105
6106/*
danielk197790949c22007-08-17 16:50:38 +00006107** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006108*/
danielk1977397d65f2008-11-19 11:35:39 +00006109static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6110 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006111 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006112
drhbbd42a62004-05-22 17:41:58 +00006113 /* We have to initialize zBuf to prevent valgrind from reporting
6114 ** errors. The reports issued by valgrind are incorrect - we would
6115 ** prefer that the randomness be increased by making use of the
6116 ** uninitialized space in zBuf - but valgrind errors tend to worry
6117 ** some users. Rather than argue, it seems easier just to initialize
6118 ** the whole array and silence valgrind, even if that means less randomness
6119 ** in the random seed.
6120 **
6121 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006122 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006123 ** tests repeatable.
6124 */
danielk1977b4b47412007-08-17 15:53:36 +00006125 memset(zBuf, 0, nBuf);
drh91eb93c2015-03-03 19:56:20 +00006126 randomnessPid = osGetpid();
drhbbd42a62004-05-22 17:41:58 +00006127#if !defined(SQLITE_TEST)
6128 {
drhb00d8622014-01-01 15:18:36 +00006129 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006130 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006131 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006132 time_t t;
6133 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006134 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006135 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6136 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6137 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006138 }else{
drhc18b4042012-02-10 03:10:27 +00006139 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006140 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006141 }
drhbbd42a62004-05-22 17:41:58 +00006142 }
6143#endif
drh72cbd072008-10-14 17:58:38 +00006144 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006145}
6146
danielk1977b4b47412007-08-17 15:53:36 +00006147
drhbbd42a62004-05-22 17:41:58 +00006148/*
6149** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006150** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006151** The return value is the number of microseconds of sleep actually
6152** requested from the underlying operating system, a number which
6153** might be greater than or equal to the argument, but not less
6154** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006155*/
danielk1977397d65f2008-11-19 11:35:39 +00006156static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006157#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006158 struct timespec sp;
6159
6160 sp.tv_sec = microseconds / 1000000;
6161 sp.tv_nsec = (microseconds % 1000000) * 1000;
6162 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006163 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006164 return microseconds;
6165#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006166 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006167 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006168 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006169#else
danielk1977b4b47412007-08-17 15:53:36 +00006170 int seconds = (microseconds+999999)/1000000;
6171 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006172 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006173 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006174#endif
drh88f474a2006-01-02 20:00:12 +00006175}
6176
6177/*
drh6b9d6dd2008-12-03 19:34:47 +00006178** The following variable, if set to a non-zero value, is interpreted as
6179** the number of seconds since 1970 and is used to set the result of
6180** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006181*/
6182#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006183int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006184#endif
6185
6186/*
drhb7e8ea22010-05-03 14:32:30 +00006187** Find the current time (in Universal Coordinated Time). Write into *piNow
6188** the current time and date as a Julian Day number times 86_400_000. In
6189** other words, write into *piNow the number of milliseconds since the Julian
6190** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6191** proleptic Gregorian calendar.
6192**
drh31702252011-10-12 23:13:43 +00006193** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6194** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006195*/
6196static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6197 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006198 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006199#if defined(NO_GETTOD)
6200 time_t t;
6201 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006202 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006203#elif OS_VXWORKS
6204 struct timespec sNow;
6205 clock_gettime(CLOCK_REALTIME, &sNow);
6206 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6207#else
6208 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006209 if( gettimeofday(&sNow, 0)==0 ){
6210 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6211 }else{
6212 rc = SQLITE_ERROR;
6213 }
drhb7e8ea22010-05-03 14:32:30 +00006214#endif
6215
6216#ifdef SQLITE_TEST
6217 if( sqlite3_current_time ){
6218 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6219 }
6220#endif
6221 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006222 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006223}
6224
6225/*
drhbbd42a62004-05-22 17:41:58 +00006226** Find the current time (in Universal Coordinated Time). Write the
6227** current time and date as a Julian Day number into *prNow and
6228** return 0. Return 1 if the time and date cannot be found.
6229*/
danielk1977397d65f2008-11-19 11:35:39 +00006230static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006231 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006232 int rc;
drhff828942010-06-26 21:34:06 +00006233 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006234 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006235 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006236 return rc;
drhbbd42a62004-05-22 17:41:58 +00006237}
danielk1977b4b47412007-08-17 15:53:36 +00006238
drh6b9d6dd2008-12-03 19:34:47 +00006239/*
6240** We added the xGetLastError() method with the intention of providing
6241** better low-level error messages when operating-system problems come up
6242** during SQLite operation. But so far, none of that has been implemented
6243** in the core. So this routine is never called. For now, it is merely
6244** a place-holder.
6245*/
danielk1977397d65f2008-11-19 11:35:39 +00006246static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6247 UNUSED_PARAMETER(NotUsed);
6248 UNUSED_PARAMETER(NotUsed2);
6249 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006250 return 0;
6251}
6252
drhf2424c52010-04-26 00:04:55 +00006253
6254/*
drh734c9862008-11-28 15:37:20 +00006255************************ End of sqlite3_vfs methods ***************************
6256******************************************************************************/
6257
drh715ff302008-12-03 22:32:44 +00006258/******************************************************************************
6259************************** Begin Proxy Locking ********************************
6260**
6261** Proxy locking is a "uber-locking-method" in this sense: It uses the
6262** other locking methods on secondary lock files. Proxy locking is a
6263** meta-layer over top of the primitive locking implemented above. For
6264** this reason, the division that implements of proxy locking is deferred
6265** until late in the file (here) after all of the other I/O methods have
6266** been defined - so that the primitive locking methods are available
6267** as services to help with the implementation of proxy locking.
6268**
6269****
6270**
6271** The default locking schemes in SQLite use byte-range locks on the
6272** database file to coordinate safe, concurrent access by multiple readers
6273** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6274** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6275** as POSIX read & write locks over fixed set of locations (via fsctl),
6276** on AFP and SMB only exclusive byte-range locks are available via fsctl
6277** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6278** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6279** address in the shared range is taken for a SHARED lock, the entire
6280** shared range is taken for an EXCLUSIVE lock):
6281**
drhf2f105d2012-08-20 15:53:54 +00006282** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006283** RESERVED_BYTE 0x40000001
6284** SHARED_RANGE 0x40000002 -> 0x40000200
6285**
6286** This works well on the local file system, but shows a nearly 100x
6287** slowdown in read performance on AFP because the AFP client disables
6288** the read cache when byte-range locks are present. Enabling the read
6289** cache exposes a cache coherency problem that is present on all OS X
6290** supported network file systems. NFS and AFP both observe the
6291** close-to-open semantics for ensuring cache coherency
6292** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6293** address the requirements for concurrent database access by multiple
6294** readers and writers
6295** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6296**
6297** To address the performance and cache coherency issues, proxy file locking
6298** changes the way database access is controlled by limiting access to a
6299** single host at a time and moving file locks off of the database file
6300** and onto a proxy file on the local file system.
6301**
6302**
6303** Using proxy locks
6304** -----------------
6305**
6306** C APIs
6307**
drh4bf66fd2015-02-19 02:43:02 +00006308** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006309** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006310** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6311** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006312**
6313**
6314** SQL pragmas
6315**
6316** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6317** PRAGMA [database.]lock_proxy_file
6318**
6319** Specifying ":auto:" means that if there is a conch file with a matching
6320** host ID in it, the proxy path in the conch file will be used, otherwise
6321** a proxy path based on the user's temp dir
6322** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6323** actual proxy file name is generated from the name and path of the
6324** database file. For example:
6325**
6326** For database path "/Users/me/foo.db"
6327** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6328**
6329** Once a lock proxy is configured for a database connection, it can not
6330** be removed, however it may be switched to a different proxy path via
6331** the above APIs (assuming the conch file is not being held by another
6332** connection or process).
6333**
6334**
6335** How proxy locking works
6336** -----------------------
6337**
6338** Proxy file locking relies primarily on two new supporting files:
6339**
6340** * conch file to limit access to the database file to a single host
6341** at a time
6342**
6343** * proxy file to act as a proxy for the advisory locks normally
6344** taken on the database
6345**
6346** The conch file - to use a proxy file, sqlite must first "hold the conch"
6347** by taking an sqlite-style shared lock on the conch file, reading the
6348** contents and comparing the host's unique host ID (see below) and lock
6349** proxy path against the values stored in the conch. The conch file is
6350** stored in the same directory as the database file and the file name
6351** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006352** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006353** host ID and/or proxy path, then the lock is escalated to an exclusive
6354** lock and the conch file contents is updated with the host ID and proxy
6355** path and the lock is downgraded to a shared lock again. If the conch
6356** is held by another process (with a shared lock), the exclusive lock
6357** will fail and SQLITE_BUSY is returned.
6358**
6359** The proxy file - a single-byte file used for all advisory file locks
6360** normally taken on the database file. This allows for safe sharing
6361** of the database file for multiple readers and writers on the same
6362** host (the conch ensures that they all use the same local lock file).
6363**
drh715ff302008-12-03 22:32:44 +00006364** Requesting the lock proxy does not immediately take the conch, it is
6365** only taken when the first request to lock database file is made.
6366** This matches the semantics of the traditional locking behavior, where
6367** opening a connection to a database file does not take a lock on it.
6368** The shared lock and an open file descriptor are maintained until
6369** the connection to the database is closed.
6370**
6371** The proxy file and the lock file are never deleted so they only need
6372** to be created the first time they are used.
6373**
6374** Configuration options
6375** ---------------------
6376**
6377** SQLITE_PREFER_PROXY_LOCKING
6378**
6379** Database files accessed on non-local file systems are
6380** automatically configured for proxy locking, lock files are
6381** named automatically using the same logic as
6382** PRAGMA lock_proxy_file=":auto:"
6383**
6384** SQLITE_PROXY_DEBUG
6385**
6386** Enables the logging of error messages during host id file
6387** retrieval and creation
6388**
drh715ff302008-12-03 22:32:44 +00006389** LOCKPROXYDIR
6390**
6391** Overrides the default directory used for lock proxy files that
6392** are named automatically via the ":auto:" setting
6393**
6394** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6395**
6396** Permissions to use when creating a directory for storing the
6397** lock proxy files, only used when LOCKPROXYDIR is not set.
6398**
6399**
6400** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6401** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6402** force proxy locking to be used for every database file opened, and 0
6403** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006404** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006405** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6406*/
6407
6408/*
6409** Proxy locking is only available on MacOSX
6410*/
drhd2cb50b2009-01-09 21:41:17 +00006411#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006412
drh715ff302008-12-03 22:32:44 +00006413/*
6414** The proxyLockingContext has the path and file structures for the remote
6415** and local proxy files in it
6416*/
6417typedef struct proxyLockingContext proxyLockingContext;
6418struct proxyLockingContext {
6419 unixFile *conchFile; /* Open conch file */
6420 char *conchFilePath; /* Name of the conch file */
6421 unixFile *lockProxy; /* Open proxy lock file */
6422 char *lockProxyPath; /* Name of the proxy lock file */
6423 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006424 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006425 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006426 void *oldLockingContext; /* Original lockingcontext to restore on close */
6427 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6428};
6429
drh7ed97b92010-01-20 13:07:21 +00006430/*
6431** The proxy lock file path for the database at dbPath is written into lPath,
6432** which must point to valid, writable memory large enough for a maxLen length
6433** file path.
drh715ff302008-12-03 22:32:44 +00006434*/
drh715ff302008-12-03 22:32:44 +00006435static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6436 int len;
6437 int dbLen;
6438 int i;
6439
6440#ifdef LOCKPROXYDIR
6441 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6442#else
6443# ifdef _CS_DARWIN_USER_TEMP_DIR
6444 {
drh7ed97b92010-01-20 13:07:21 +00006445 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006446 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh91eb93c2015-03-03 19:56:20 +00006447 lPath, errno, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006448 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006449 }
drh7ed97b92010-01-20 13:07:21 +00006450 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006451 }
6452# else
6453 len = strlcpy(lPath, "/tmp/", maxLen);
6454# endif
6455#endif
6456
6457 if( lPath[len-1]!='/' ){
6458 len = strlcat(lPath, "/", maxLen);
6459 }
6460
6461 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006462 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006463 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006464 char c = dbPath[i];
6465 lPath[i+len] = (c=='/')?'_':c;
6466 }
6467 lPath[i+len]='\0';
6468 strlcat(lPath, ":auto:", maxLen);
drh91eb93c2015-03-03 19:56:20 +00006469 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid()));
drh715ff302008-12-03 22:32:44 +00006470 return SQLITE_OK;
6471}
6472
drh7ed97b92010-01-20 13:07:21 +00006473/*
6474 ** Creates the lock file and any missing directories in lockPath
6475 */
6476static int proxyCreateLockPath(const char *lockPath){
6477 int i, len;
6478 char buf[MAXPATHLEN];
6479 int start = 0;
6480
6481 assert(lockPath!=NULL);
6482 /* try to create all the intermediate directories */
6483 len = (int)strlen(lockPath);
6484 buf[0] = lockPath[0];
6485 for( i=1; i<len; i++ ){
6486 if( lockPath[i] == '/' && (i - start > 0) ){
6487 /* only mkdir if leaf dir != "." or "/" or ".." */
6488 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6489 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6490 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006491 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006492 int err=errno;
6493 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006494 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006495 "'%s' proxy lock path=%s pid=%d\n",
drh91eb93c2015-03-03 19:56:20 +00006496 buf, strerror(err), lockPath, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006497 return err;
6498 }
6499 }
6500 }
6501 start=i+1;
6502 }
6503 buf[i] = lockPath[i];
6504 }
drh91eb93c2015-03-03 19:56:20 +00006505 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006506 return 0;
6507}
6508
drh715ff302008-12-03 22:32:44 +00006509/*
6510** Create a new VFS file descriptor (stored in memory obtained from
6511** sqlite3_malloc) and open the file named "path" in the file descriptor.
6512**
6513** The caller is responsible not only for closing the file descriptor
6514** but also for freeing the memory associated with the file descriptor.
6515*/
drh7ed97b92010-01-20 13:07:21 +00006516static int proxyCreateUnixFile(
6517 const char *path, /* path for the new unixFile */
6518 unixFile **ppFile, /* unixFile created and returned by ref */
6519 int islockfile /* if non zero missing dirs will be created */
6520) {
6521 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006522 unixFile *pNew;
6523 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006524 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006525 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006526 int terrno = 0;
6527 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006528
drh7ed97b92010-01-20 13:07:21 +00006529 /* 1. first try to open/create the file
6530 ** 2. if that fails, and this is a lock file (not-conch), try creating
6531 ** the parent directories and then try again.
6532 ** 3. if that fails, try to open the file read-only
6533 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6534 */
6535 pUnused = findReusableFd(path, openFlags);
6536 if( pUnused ){
6537 fd = pUnused->fd;
6538 }else{
6539 pUnused = sqlite3_malloc(sizeof(*pUnused));
6540 if( !pUnused ){
6541 return SQLITE_NOMEM;
6542 }
6543 }
6544 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006545 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006546 terrno = errno;
6547 if( fd<0 && errno==ENOENT && islockfile ){
6548 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006549 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006550 }
6551 }
6552 }
6553 if( fd<0 ){
6554 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006555 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006556 terrno = errno;
6557 }
6558 if( fd<0 ){
6559 if( islockfile ){
6560 return SQLITE_BUSY;
6561 }
6562 switch (terrno) {
6563 case EACCES:
6564 return SQLITE_PERM;
6565 case EIO:
6566 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6567 default:
drh9978c972010-02-23 17:36:32 +00006568 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006569 }
6570 }
6571
6572 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6573 if( pNew==NULL ){
6574 rc = SQLITE_NOMEM;
6575 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006576 }
6577 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006578 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006579 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006580 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006581 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006582 pUnused->fd = fd;
6583 pUnused->flags = openFlags;
6584 pNew->pUnused = pUnused;
6585
drhc02a43a2012-01-10 23:18:38 +00006586 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006587 if( rc==SQLITE_OK ){
6588 *ppFile = pNew;
6589 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006590 }
drh7ed97b92010-01-20 13:07:21 +00006591end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006592 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006593 sqlite3_free(pNew);
6594 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006595 return rc;
6596}
6597
drh7ed97b92010-01-20 13:07:21 +00006598#ifdef SQLITE_TEST
6599/* simulate multiple hosts by creating unique hostid file paths */
6600int sqlite3_hostid_num = 0;
6601#endif
6602
6603#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6604
drh0ab216a2010-07-02 17:10:40 +00006605/* Not always defined in the headers as it ought to be */
6606extern int gethostuuid(uuid_t id, const struct timespec *wait);
6607
drh7ed97b92010-01-20 13:07:21 +00006608/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6609** bytes of writable memory.
6610*/
6611static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006612 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6613 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh4bf66fd2015-02-19 02:43:02 +00006614# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
6615 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
drh29ecd8a2010-12-21 00:16:40 +00006616 {
drh4bf66fd2015-02-19 02:43:02 +00006617 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006618 if( gethostuuid(pHostID, &timeout) ){
6619 int err = errno;
6620 if( pError ){
6621 *pError = err;
6622 }
6623 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006624 }
drh7ed97b92010-01-20 13:07:21 +00006625 }
drh3d4435b2011-08-26 20:55:50 +00006626#else
6627 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006628#endif
drh7ed97b92010-01-20 13:07:21 +00006629#ifdef SQLITE_TEST
6630 /* simulate multiple hosts by creating unique hostid file paths */
6631 if( sqlite3_hostid_num != 0){
6632 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6633 }
6634#endif
6635
6636 return SQLITE_OK;
6637}
6638
6639/* The conch file contains the header, host id and lock file path
6640 */
6641#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6642#define PROXY_HEADERLEN 1 /* conch file header length */
6643#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6644#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6645
6646/*
6647** Takes an open conch file, copies the contents to a new path and then moves
6648** it back. The newly created file's file descriptor is assigned to the
6649** conch file structure and finally the original conch file descriptor is
6650** closed. Returns zero if successful.
6651*/
6652static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6653 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6654 unixFile *conchFile = pCtx->conchFile;
6655 char tPath[MAXPATHLEN];
6656 char buf[PROXY_MAXCONCHLEN];
6657 char *cPath = pCtx->conchFilePath;
6658 size_t readLen = 0;
6659 size_t pathLen = 0;
6660 char errmsg[64] = "";
6661 int fd = -1;
6662 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006663 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006664
6665 /* create a new path by replace the trailing '-conch' with '-break' */
6666 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6667 if( pathLen>MAXPATHLEN || pathLen<6 ||
6668 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006669 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006670 goto end_breaklock;
6671 }
6672 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006673 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006674 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006675 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006676 goto end_breaklock;
6677 }
6678 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006679 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006680 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006681 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006682 goto end_breaklock;
6683 }
drhe562be52011-03-02 18:01:10 +00006684 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006685 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006686 goto end_breaklock;
6687 }
6688 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006689 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006690 goto end_breaklock;
6691 }
6692 rc = 0;
6693 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006694 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006695 conchFile->h = fd;
6696 conchFile->openFlags = O_RDWR | O_CREAT;
6697
6698end_breaklock:
6699 if( rc ){
6700 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006701 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006702 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006703 }
6704 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6705 }
6706 return rc;
6707}
6708
6709/* Take the requested lock on the conch file and break a stale lock if the
6710** host id matches.
6711*/
6712static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6713 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6714 unixFile *conchFile = pCtx->conchFile;
6715 int rc = SQLITE_OK;
6716 int nTries = 0;
6717 struct timespec conchModTime;
6718
drh3d4435b2011-08-26 20:55:50 +00006719 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006720 do {
6721 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6722 nTries ++;
6723 if( rc==SQLITE_BUSY ){
6724 /* If the lock failed (busy):
6725 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6726 * 2nd try: fail if the mod time changed or host id is different, wait
6727 * 10 sec and try again
6728 * 3rd try: break the lock unless the mod time has changed.
6729 */
6730 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006731 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006732 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006733 return SQLITE_IOERR_LOCK;
6734 }
6735
6736 if( nTries==1 ){
6737 conchModTime = buf.st_mtimespec;
6738 usleep(500000); /* wait 0.5 sec and try the lock again*/
6739 continue;
6740 }
6741
6742 assert( nTries>1 );
6743 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6744 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6745 return SQLITE_BUSY;
6746 }
6747
6748 if( nTries==2 ){
6749 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006750 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006751 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006752 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006753 return SQLITE_IOERR_LOCK;
6754 }
6755 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6756 /* don't break the lock if the host id doesn't match */
6757 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6758 return SQLITE_BUSY;
6759 }
6760 }else{
6761 /* don't break the lock on short read or a version mismatch */
6762 return SQLITE_BUSY;
6763 }
6764 usleep(10000000); /* wait 10 sec and try the lock again */
6765 continue;
6766 }
6767
6768 assert( nTries==3 );
6769 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6770 rc = SQLITE_OK;
6771 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006772 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006773 }
6774 if( !rc ){
6775 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6776 }
6777 }
6778 }
6779 } while( rc==SQLITE_BUSY && nTries<3 );
6780
6781 return rc;
6782}
6783
6784/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006785** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6786** lockPath means that the lockPath in the conch file will be used if the
6787** host IDs match, or a new lock path will be generated automatically
6788** and written to the conch file.
6789*/
6790static int proxyTakeConch(unixFile *pFile){
6791 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6792
drh7ed97b92010-01-20 13:07:21 +00006793 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006794 return SQLITE_OK;
6795 }else{
6796 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006797 uuid_t myHostID;
6798 int pError = 0;
6799 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006800 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006801 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006802 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006803 int createConch = 0;
6804 int hostIdMatch = 0;
6805 int readLen = 0;
6806 int tryOldLockPath = 0;
6807 int forceNewLockPath = 0;
6808
drh308c2a52010-05-14 11:30:18 +00006809 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006810 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6811 osGetpid()));
drh715ff302008-12-03 22:32:44 +00006812
drh7ed97b92010-01-20 13:07:21 +00006813 rc = proxyGetHostID(myHostID, &pError);
6814 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006815 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006816 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006817 }
drh7ed97b92010-01-20 13:07:21 +00006818 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006819 if( rc!=SQLITE_OK ){
6820 goto end_takeconch;
6821 }
drh7ed97b92010-01-20 13:07:21 +00006822 /* read the existing conch file */
6823 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6824 if( readLen<0 ){
6825 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006826 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006827 rc = SQLITE_IOERR_READ;
6828 goto end_takeconch;
6829 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6830 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6831 /* a short read or version format mismatch means we need to create a new
6832 ** conch file.
6833 */
6834 createConch = 1;
6835 }
6836 /* if the host id matches and the lock path already exists in the conch
6837 ** we'll try to use the path there, if we can't open that path, we'll
6838 ** retry with a new auto-generated path
6839 */
6840 do { /* in case we need to try again for an :auto: named lock file */
6841
6842 if( !createConch && !forceNewLockPath ){
6843 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6844 PROXY_HOSTIDLEN);
6845 /* if the conch has data compare the contents */
6846 if( !pCtx->lockProxyPath ){
6847 /* for auto-named local lock file, just check the host ID and we'll
6848 ** use the local lock file path that's already in there
6849 */
6850 if( hostIdMatch ){
6851 size_t pathLen = (readLen - PROXY_PATHINDEX);
6852
6853 if( pathLen>=MAXPATHLEN ){
6854 pathLen=MAXPATHLEN-1;
6855 }
6856 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6857 lockPath[pathLen] = 0;
6858 tempLockPath = lockPath;
6859 tryOldLockPath = 1;
6860 /* create a copy of the lock path if the conch is taken */
6861 goto end_takeconch;
6862 }
6863 }else if( hostIdMatch
6864 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6865 readLen-PROXY_PATHINDEX)
6866 ){
6867 /* conch host and lock path match */
6868 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006869 }
drh7ed97b92010-01-20 13:07:21 +00006870 }
6871
6872 /* if the conch isn't writable and doesn't match, we can't take it */
6873 if( (conchFile->openFlags&O_RDWR) == 0 ){
6874 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006875 goto end_takeconch;
6876 }
drh7ed97b92010-01-20 13:07:21 +00006877
6878 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006879 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006880 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6881 tempLockPath = lockPath;
6882 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006883 }
drh7ed97b92010-01-20 13:07:21 +00006884
6885 /* update conch with host and path (this will fail if other process
6886 ** has a shared lock already), if the host id matches, use the big
6887 ** stick.
drh715ff302008-12-03 22:32:44 +00006888 */
drh7ed97b92010-01-20 13:07:21 +00006889 futimes(conchFile->h, NULL);
6890 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006891 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006892 /* We are trying for an exclusive lock but another thread in this
6893 ** same process is still holding a shared lock. */
6894 rc = SQLITE_BUSY;
6895 } else {
6896 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006897 }
drh715ff302008-12-03 22:32:44 +00006898 }else{
drh4bf66fd2015-02-19 02:43:02 +00006899 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006900 }
drh7ed97b92010-01-20 13:07:21 +00006901 if( rc==SQLITE_OK ){
6902 char writeBuffer[PROXY_MAXCONCHLEN];
6903 int writeSize = 0;
6904
6905 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6906 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6907 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006908 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6909 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006910 }else{
6911 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6912 }
6913 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006914 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006915 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6916 fsync(conchFile->h);
6917 /* If we created a new conch file (not just updated the contents of a
6918 ** valid conch file), try to match the permissions of the database
6919 */
6920 if( rc==SQLITE_OK && createConch ){
6921 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006922 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006923 if( err==0 ){
6924 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6925 S_IROTH|S_IWOTH);
6926 /* try to match the database file R/W permissions, ignore failure */
6927#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006928 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006929#else
drhff812312011-02-23 13:33:46 +00006930 do{
drhe562be52011-03-02 18:01:10 +00006931 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006932 }while( rc==(-1) && errno==EINTR );
6933 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006934 int code = errno;
6935 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6936 cmode, code, strerror(code));
6937 } else {
6938 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6939 }
6940 }else{
6941 int code = errno;
6942 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6943 err, code, strerror(code));
6944#endif
6945 }
drh715ff302008-12-03 22:32:44 +00006946 }
6947 }
drh7ed97b92010-01-20 13:07:21 +00006948 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6949
6950 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006951 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006952 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006953 int fd;
drh7ed97b92010-01-20 13:07:21 +00006954 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006955 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006956 }
6957 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006958 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006959 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006960 if( fd>=0 ){
6961 pFile->h = fd;
6962 }else{
drh9978c972010-02-23 17:36:32 +00006963 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006964 during locking */
6965 }
6966 }
6967 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6968 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6969 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6970 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6971 /* we couldn't create the proxy lock file with the old lock file path
6972 ** so try again via auto-naming
6973 */
6974 forceNewLockPath = 1;
6975 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006976 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006977 }
6978 }
6979 if( rc==SQLITE_OK ){
6980 /* Need to make a copy of path if we extracted the value
6981 ** from the conch file or the path was allocated on the stack
6982 */
6983 if( tempLockPath ){
6984 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6985 if( !pCtx->lockProxyPath ){
6986 rc = SQLITE_NOMEM;
6987 }
6988 }
6989 }
6990 if( rc==SQLITE_OK ){
6991 pCtx->conchHeld = 1;
6992
6993 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6994 afpLockingContext *afpCtx;
6995 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6996 afpCtx->dbPath = pCtx->lockProxyPath;
6997 }
6998 } else {
6999 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7000 }
drh308c2a52010-05-14 11:30:18 +00007001 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7002 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007003 return rc;
drh308c2a52010-05-14 11:30:18 +00007004 } while (1); /* in case we need to retry the :auto: lock file -
7005 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007006 }
7007}
7008
7009/*
7010** If pFile holds a lock on a conch file, then release that lock.
7011*/
7012static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007013 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007014 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7015 unixFile *conchFile; /* Name of the conch file */
7016
7017 pCtx = (proxyLockingContext *)pFile->lockingContext;
7018 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007019 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007020 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh91eb93c2015-03-03 19:56:20 +00007021 osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00007022 if( pCtx->conchHeld>0 ){
7023 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7024 }
drh715ff302008-12-03 22:32:44 +00007025 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007026 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7027 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007028 return rc;
7029}
7030
7031/*
7032** Given the name of a database file, compute the name of its conch file.
7033** Store the conch filename in memory obtained from sqlite3_malloc().
7034** Make *pConchPath point to the new name. Return SQLITE_OK on success
7035** or SQLITE_NOMEM if unable to obtain memory.
7036**
7037** The caller is responsible for ensuring that the allocated memory
7038** space is eventually freed.
7039**
7040** *pConchPath is set to NULL if a memory allocation error occurs.
7041*/
7042static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7043 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007044 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007045 char *conchPath; /* buffer in which to construct conch name */
7046
7047 /* Allocate space for the conch filename and initialize the name to
7048 ** the name of the original database file. */
7049 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7050 if( conchPath==0 ){
7051 return SQLITE_NOMEM;
7052 }
7053 memcpy(conchPath, dbPath, len+1);
7054
7055 /* now insert a "." before the last / character */
7056 for( i=(len-1); i>=0; i-- ){
7057 if( conchPath[i]=='/' ){
7058 i++;
7059 break;
7060 }
7061 }
7062 conchPath[i]='.';
7063 while ( i<len ){
7064 conchPath[i+1]=dbPath[i];
7065 i++;
7066 }
7067
7068 /* append the "-conch" suffix to the file */
7069 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007070 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007071
7072 return SQLITE_OK;
7073}
7074
7075
7076/* Takes a fully configured proxy locking-style unix file and switches
7077** the local lock file path
7078*/
7079static int switchLockProxyPath(unixFile *pFile, const char *path) {
7080 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7081 char *oldPath = pCtx->lockProxyPath;
7082 int rc = SQLITE_OK;
7083
drh308c2a52010-05-14 11:30:18 +00007084 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007085 return SQLITE_BUSY;
7086 }
7087
7088 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7089 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7090 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7091 return SQLITE_OK;
7092 }else{
7093 unixFile *lockProxy = pCtx->lockProxy;
7094 pCtx->lockProxy=NULL;
7095 pCtx->conchHeld = 0;
7096 if( lockProxy!=NULL ){
7097 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7098 if( rc ) return rc;
7099 sqlite3_free(lockProxy);
7100 }
7101 sqlite3_free(oldPath);
7102 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7103 }
7104
7105 return rc;
7106}
7107
7108/*
7109** pFile is a file that has been opened by a prior xOpen call. dbPath
7110** is a string buffer at least MAXPATHLEN+1 characters in size.
7111**
7112** This routine find the filename associated with pFile and writes it
7113** int dbPath.
7114*/
7115static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007116#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007117 if( pFile->pMethod == &afpIoMethods ){
7118 /* afp style keeps a reference to the db path in the filePath field
7119 ** of the struct */
drhea678832008-12-10 19:26:22 +00007120 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007121 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7122 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007123 } else
drh715ff302008-12-03 22:32:44 +00007124#endif
7125 if( pFile->pMethod == &dotlockIoMethods ){
7126 /* dot lock style uses the locking context to store the dot lock
7127 ** file path */
7128 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7129 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7130 }else{
7131 /* all other styles use the locking context to store the db file path */
7132 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007133 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007134 }
7135 return SQLITE_OK;
7136}
7137
7138/*
7139** Takes an already filled in unix file and alters it so all file locking
7140** will be performed on the local proxy lock file. The following fields
7141** are preserved in the locking context so that they can be restored and
7142** the unix structure properly cleaned up at close time:
7143** ->lockingContext
7144** ->pMethod
7145*/
7146static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7147 proxyLockingContext *pCtx;
7148 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7149 char *lockPath=NULL;
7150 int rc = SQLITE_OK;
7151
drh308c2a52010-05-14 11:30:18 +00007152 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007153 return SQLITE_BUSY;
7154 }
7155 proxyGetDbPathForUnixFile(pFile, dbPath);
7156 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7157 lockPath=NULL;
7158 }else{
7159 lockPath=(char *)path;
7160 }
7161
drh308c2a52010-05-14 11:30:18 +00007162 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh91eb93c2015-03-03 19:56:20 +00007163 (lockPath ? lockPath : ":auto:"), osGetpid()));
drh715ff302008-12-03 22:32:44 +00007164
7165 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7166 if( pCtx==0 ){
7167 return SQLITE_NOMEM;
7168 }
7169 memset(pCtx, 0, sizeof(*pCtx));
7170
7171 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7172 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007173 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7174 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7175 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7176 ** (c) the file system is read-only, then enable no-locking access.
7177 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7178 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7179 */
7180 struct statfs fsInfo;
7181 struct stat conchInfo;
7182 int goLockless = 0;
7183
drh99ab3b12011-03-02 15:09:07 +00007184 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007185 int err = errno;
7186 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7187 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7188 }
7189 }
7190 if( goLockless ){
7191 pCtx->conchHeld = -1; /* read only FS/ lockless */
7192 rc = SQLITE_OK;
7193 }
7194 }
drh715ff302008-12-03 22:32:44 +00007195 }
7196 if( rc==SQLITE_OK && lockPath ){
7197 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7198 }
7199
7200 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007201 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7202 if( pCtx->dbPath==NULL ){
7203 rc = SQLITE_NOMEM;
7204 }
7205 }
7206 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007207 /* all memory is allocated, proxys are created and assigned,
7208 ** switch the locking context and pMethod then return.
7209 */
drh715ff302008-12-03 22:32:44 +00007210 pCtx->oldLockingContext = pFile->lockingContext;
7211 pFile->lockingContext = pCtx;
7212 pCtx->pOldMethod = pFile->pMethod;
7213 pFile->pMethod = &proxyIoMethods;
7214 }else{
7215 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007216 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007217 sqlite3_free(pCtx->conchFile);
7218 }
drhd56b1212010-08-11 06:14:15 +00007219 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007220 sqlite3_free(pCtx->conchFilePath);
7221 sqlite3_free(pCtx);
7222 }
drh308c2a52010-05-14 11:30:18 +00007223 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7224 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007225 return rc;
7226}
7227
7228
7229/*
7230** This routine handles sqlite3_file_control() calls that are specific
7231** to proxy locking.
7232*/
7233static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7234 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007235 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007236 unixFile *pFile = (unixFile*)id;
7237 if( pFile->pMethod == &proxyIoMethods ){
7238 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7239 proxyTakeConch(pFile);
7240 if( pCtx->lockProxyPath ){
7241 *(const char **)pArg = pCtx->lockProxyPath;
7242 }else{
7243 *(const char **)pArg = ":auto: (not held)";
7244 }
7245 } else {
7246 *(const char **)pArg = NULL;
7247 }
7248 return SQLITE_OK;
7249 }
drh4bf66fd2015-02-19 02:43:02 +00007250 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007251 unixFile *pFile = (unixFile*)id;
7252 int rc = SQLITE_OK;
7253 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7254 if( pArg==NULL || (const char *)pArg==0 ){
7255 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007256 /* turn off proxy locking - not supported. If support is added for
7257 ** switching proxy locking mode off then it will need to fail if
7258 ** the journal mode is WAL mode.
7259 */
drh715ff302008-12-03 22:32:44 +00007260 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7261 }else{
7262 /* turn off proxy locking - already off - NOOP */
7263 rc = SQLITE_OK;
7264 }
7265 }else{
7266 const char *proxyPath = (const char *)pArg;
7267 if( isProxyStyle ){
7268 proxyLockingContext *pCtx =
7269 (proxyLockingContext*)pFile->lockingContext;
7270 if( !strcmp(pArg, ":auto:")
7271 || (pCtx->lockProxyPath &&
7272 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7273 ){
7274 rc = SQLITE_OK;
7275 }else{
7276 rc = switchLockProxyPath(pFile, proxyPath);
7277 }
7278 }else{
7279 /* turn on proxy file locking */
7280 rc = proxyTransformUnixFile(pFile, proxyPath);
7281 }
7282 }
7283 return rc;
7284 }
7285 default: {
7286 assert( 0 ); /* The call assures that only valid opcodes are sent */
7287 }
7288 }
7289 /*NOTREACHED*/
7290 return SQLITE_ERROR;
7291}
7292
7293/*
7294** Within this division (the proxying locking implementation) the procedures
7295** above this point are all utilities. The lock-related methods of the
7296** proxy-locking sqlite3_io_method object follow.
7297*/
7298
7299
7300/*
7301** This routine checks if there is a RESERVED lock held on the specified
7302** file by this or any other process. If such a lock is held, set *pResOut
7303** to a non-zero value otherwise *pResOut is set to zero. The return value
7304** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7305*/
7306static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7307 unixFile *pFile = (unixFile*)id;
7308 int rc = proxyTakeConch(pFile);
7309 if( rc==SQLITE_OK ){
7310 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007311 if( pCtx->conchHeld>0 ){
7312 unixFile *proxy = pCtx->lockProxy;
7313 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7314 }else{ /* conchHeld < 0 is lockless */
7315 pResOut=0;
7316 }
drh715ff302008-12-03 22:32:44 +00007317 }
7318 return rc;
7319}
7320
7321/*
drh308c2a52010-05-14 11:30:18 +00007322** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007323** of the following:
7324**
7325** (1) SHARED_LOCK
7326** (2) RESERVED_LOCK
7327** (3) PENDING_LOCK
7328** (4) EXCLUSIVE_LOCK
7329**
7330** Sometimes when requesting one lock state, additional lock states
7331** are inserted in between. The locking might fail on one of the later
7332** transitions leaving the lock state different from what it started but
7333** still short of its goal. The following chart shows the allowed
7334** transitions and the inserted intermediate states:
7335**
7336** UNLOCKED -> SHARED
7337** SHARED -> RESERVED
7338** SHARED -> (PENDING) -> EXCLUSIVE
7339** RESERVED -> (PENDING) -> EXCLUSIVE
7340** PENDING -> EXCLUSIVE
7341**
7342** This routine will only increase a lock. Use the sqlite3OsUnlock()
7343** routine to lower a locking level.
7344*/
drh308c2a52010-05-14 11:30:18 +00007345static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007346 unixFile *pFile = (unixFile*)id;
7347 int rc = proxyTakeConch(pFile);
7348 if( rc==SQLITE_OK ){
7349 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007350 if( pCtx->conchHeld>0 ){
7351 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007352 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7353 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007354 }else{
7355 /* conchHeld < 0 is lockless */
7356 }
drh715ff302008-12-03 22:32:44 +00007357 }
7358 return rc;
7359}
7360
7361
7362/*
drh308c2a52010-05-14 11:30:18 +00007363** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007364** must be either NO_LOCK or SHARED_LOCK.
7365**
7366** If the locking level of the file descriptor is already at or below
7367** the requested locking level, this routine is a no-op.
7368*/
drh308c2a52010-05-14 11:30:18 +00007369static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007370 unixFile *pFile = (unixFile*)id;
7371 int rc = proxyTakeConch(pFile);
7372 if( rc==SQLITE_OK ){
7373 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007374 if( pCtx->conchHeld>0 ){
7375 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007376 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7377 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007378 }else{
7379 /* conchHeld < 0 is lockless */
7380 }
drh715ff302008-12-03 22:32:44 +00007381 }
7382 return rc;
7383}
7384
7385/*
7386** Close a file that uses proxy locks.
7387*/
7388static int proxyClose(sqlite3_file *id) {
7389 if( id ){
7390 unixFile *pFile = (unixFile*)id;
7391 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7392 unixFile *lockProxy = pCtx->lockProxy;
7393 unixFile *conchFile = pCtx->conchFile;
7394 int rc = SQLITE_OK;
7395
7396 if( lockProxy ){
7397 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7398 if( rc ) return rc;
7399 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7400 if( rc ) return rc;
7401 sqlite3_free(lockProxy);
7402 pCtx->lockProxy = 0;
7403 }
7404 if( conchFile ){
7405 if( pCtx->conchHeld ){
7406 rc = proxyReleaseConch(pFile);
7407 if( rc ) return rc;
7408 }
7409 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7410 if( rc ) return rc;
7411 sqlite3_free(conchFile);
7412 }
drhd56b1212010-08-11 06:14:15 +00007413 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007414 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007415 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007416 /* restore the original locking context and pMethod then close it */
7417 pFile->lockingContext = pCtx->oldLockingContext;
7418 pFile->pMethod = pCtx->pOldMethod;
7419 sqlite3_free(pCtx);
7420 return pFile->pMethod->xClose(id);
7421 }
7422 return SQLITE_OK;
7423}
7424
7425
7426
drhd2cb50b2009-01-09 21:41:17 +00007427#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007428/*
7429** The proxy locking style is intended for use with AFP filesystems.
7430** And since AFP is only supported on MacOSX, the proxy locking is also
7431** restricted to MacOSX.
7432**
7433**
7434******************* End of the proxy lock implementation **********************
7435******************************************************************************/
7436
drh734c9862008-11-28 15:37:20 +00007437/*
danielk1977e339d652008-06-28 11:23:00 +00007438** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007439**
7440** This routine registers all VFS implementations for unix-like operating
7441** systems. This routine, and the sqlite3_os_end() routine that follows,
7442** should be the only routines in this file that are visible from other
7443** files.
drh6b9d6dd2008-12-03 19:34:47 +00007444**
7445** This routine is called once during SQLite initialization and by a
7446** single thread. The memory allocation and mutex subsystems have not
7447** necessarily been initialized when this routine is called, and so they
7448** should not be used.
drh153c62c2007-08-24 03:51:33 +00007449*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007450int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007451 /*
7452 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007453 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7454 ** to the "finder" function. (pAppData is a pointer to a pointer because
7455 ** silly C90 rules prohibit a void* from being cast to a function pointer
7456 ** and so we have to go through the intermediate pointer to avoid problems
7457 ** when compiling with -pedantic-errors on GCC.)
7458 **
7459 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007460 ** finder-function. The finder-function returns a pointer to the
7461 ** sqlite_io_methods object that implements the desired locking
7462 ** behaviors. See the division above that contains the IOMETHODS
7463 ** macro for addition information on finder-functions.
7464 **
7465 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7466 ** object. But the "autolockIoFinder" available on MacOSX does a little
7467 ** more than that; it looks at the filesystem type that hosts the
7468 ** database file and tries to choose an locking method appropriate for
7469 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007470 */
drh7708e972008-11-29 00:56:52 +00007471 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007472 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007473 sizeof(unixFile), /* szOsFile */ \
7474 MAX_PATHNAME, /* mxPathname */ \
7475 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007476 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007477 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007478 unixOpen, /* xOpen */ \
7479 unixDelete, /* xDelete */ \
7480 unixAccess, /* xAccess */ \
7481 unixFullPathname, /* xFullPathname */ \
7482 unixDlOpen, /* xDlOpen */ \
7483 unixDlError, /* xDlError */ \
7484 unixDlSym, /* xDlSym */ \
7485 unixDlClose, /* xDlClose */ \
7486 unixRandomness, /* xRandomness */ \
7487 unixSleep, /* xSleep */ \
7488 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007489 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007490 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007491 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007492 unixGetSystemCall, /* xGetSystemCall */ \
7493 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007494 }
7495
drh6b9d6dd2008-12-03 19:34:47 +00007496 /*
7497 ** All default VFSes for unix are contained in the following array.
7498 **
7499 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7500 ** by the SQLite core when the VFS is registered. So the following
7501 ** array cannot be const.
7502 */
danielk1977e339d652008-06-28 11:23:00 +00007503 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007504#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007505 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007506#elif OS_VXWORKS
7507 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007508#else
7509 UNIXVFS("unix", posixIoFinder ),
7510#endif
7511 UNIXVFS("unix-none", nolockIoFinder ),
7512 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007513 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007514#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007515 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007516#endif
drhe89b2912015-03-03 20:42:01 +00007517#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007518 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007519#endif
drhe89b2912015-03-03 20:42:01 +00007520#if SQLITE_ENABLE_LOCKING_STYLE
7521 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007522#endif
drhd2cb50b2009-01-09 21:41:17 +00007523#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007524 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007525 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007526 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007527#endif
drh153c62c2007-08-24 03:51:33 +00007528 };
drh6b9d6dd2008-12-03 19:34:47 +00007529 unsigned int i; /* Loop counter */
7530
drh2aa5a002011-04-13 13:42:25 +00007531 /* Double-check that the aSyscall[] array has been constructed
7532 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007533 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007534
drh6b9d6dd2008-12-03 19:34:47 +00007535 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007536 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007537 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007538 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007539 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007540}
danielk1977e339d652008-06-28 11:23:00 +00007541
7542/*
drh6b9d6dd2008-12-03 19:34:47 +00007543** Shutdown the operating system interface.
7544**
7545** Some operating systems might need to do some cleanup in this routine,
7546** to release dynamically allocated objects. But not on unix.
7547** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007548*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007549int sqlite3_os_end(void){
7550 return SQLITE_OK;
7551}
drhdce8bdb2007-08-16 13:01:44 +00007552
danielk197729bafea2008-06-26 10:41:19 +00007553#endif /* SQLITE_OS_UNIX */