blob: a91ab00c673bdabd599acf342e2624836556bd88 [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
drh91be7dc2014-08-11 13:53:30 +000088#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drh6c7d5c52008-11-21 20:32:33 +000090# if OS_VXWORKS
danielk1977c70dfc42008-11-19 13:52:30 +000091# include <semaphore.h>
92# include <limits.h>
93# else
drh9b35ea62008-11-29 02:20:26 +000094# include <sys/file.h>
danielk1977c70dfc42008-11-19 13:52:30 +000095# include <sys/param.h>
danielk1977c70dfc42008-11-19 13:52:30 +000096# endif
drhbfe66312006-10-03 17:40:40 +000097#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000098
drhf8b4d8c2010-03-05 13:53:22 +000099#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh84a2bf62010-03-05 13:41:06 +0000100# include <sys/mount.h>
101#endif
102
drhdbe4b882011-06-20 18:00:17 +0000103#ifdef HAVE_UTIME
104# include <utime.h>
105#endif
106
drh9cbe6352005-11-29 03:13:21 +0000107/*
drh7ed97b92010-01-20 13:07:21 +0000108** Allowed values of unixFile.fsFlags
109*/
110#define SQLITE_FSFLAGS_IS_MSDOS 0x1
111
112/*
drhf1a221e2006-01-15 17:27:17 +0000113** If we are to be thread-safe, include the pthreads header and define
114** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000115*/
drhd677b3d2007-08-20 22:48:41 +0000116#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000117# include <pthread.h>
118# define SQLITE_UNIX_THREADS 1
119#endif
120
121/*
122** Default permissions when creating a new file
123*/
124#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
125# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
126#endif
127
danielk1977b4b47412007-08-17 15:53:36 +0000128/*
drh5adc60b2012-04-14 13:25:11 +0000129** Default permissions when creating auto proxy dir
130*/
aswiftaebf4132008-11-21 00:10:35 +0000131#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
132# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
133#endif
134
135/*
danielk1977b4b47412007-08-17 15:53:36 +0000136** Maximum supported path-length.
137*/
138#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000139
drh91eb93c2015-03-03 19:56:20 +0000140/* Always cast the getpid() return type for compatibility with
141** kernel modules in VxWorks. */
142#define osGetpid(X) (pid_t)getpid()
143
drh734c9862008-11-28 15:37:20 +0000144/*
drh734c9862008-11-28 15:37:20 +0000145** Only set the lastErrno if the error code is a real error and not
146** a normal expected return code of SQLITE_BUSY or SQLITE_OK
147*/
148#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
149
drhd91c68f2010-05-14 14:52:25 +0000150/* Forward references */
151typedef struct unixShm unixShm; /* Connection shared memory */
152typedef struct unixShmNode unixShmNode; /* Shared memory instance */
153typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
154typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000155
156/*
dane946c392009-08-22 11:39:46 +0000157** Sometimes, after a file handle is closed by SQLite, the file descriptor
158** cannot be closed immediately. In these cases, instances of the following
159** structure are used to store the file descriptor while waiting for an
160** opportunity to either close or reuse it.
161*/
dane946c392009-08-22 11:39:46 +0000162struct UnixUnusedFd {
163 int fd; /* File descriptor to close */
164 int flags; /* Flags this file descriptor was opened with */
165 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
166};
167
168/*
drh9b35ea62008-11-29 02:20:26 +0000169** The unixFile structure is subclass of sqlite3_file specific to the unix
170** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000171*/
drh054889e2005-11-30 03:20:31 +0000172typedef struct unixFile unixFile;
173struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000174 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000175 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000176 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000177 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000178 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000179 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000180 int lastErrno; /* The unix errno from last I/O error */
181 void *lockingContext; /* Locking style specific state */
182 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000183 const char *zPath; /* Name of the file */
184 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000185 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000186#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000187 int nFetchOut; /* Number of outstanding xFetch refs */
188 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000189 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
190 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000191 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000192#endif
drh537dddf2012-10-26 13:46:24 +0000193#ifdef __QNXNTO__
194 int sectorSize; /* Device sector size */
195 int deviceCharacteristics; /* Precomputed device characteristics */
196#endif
drh08c6d442009-02-09 17:34:07 +0000197#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000198 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000199#endif
drh7ed97b92010-01-20 13:07:21 +0000200#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000201 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000202#endif
203#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000204 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000205#endif
drhd3d8c042012-05-29 17:02:40 +0000206#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000207 /* The next group of variables are used to track whether or not the
208 ** transaction counter in bytes 24-27 of database files are updated
209 ** whenever any part of the database changes. An assertion fault will
210 ** occur if a file is updated without also updating the transaction
211 ** counter. This test is made to avoid new problems similar to the
212 ** one described by ticket #3584.
213 */
214 unsigned char transCntrChng; /* True if the transaction counter changed */
215 unsigned char dbUpdate; /* True if any part of database file changed */
216 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000217
drh8f941bc2009-01-14 23:03:40 +0000218#endif
danf23da962013-03-23 21:00:41 +0000219
danielk1977967a4a12007-08-20 14:23:44 +0000220#ifdef SQLITE_TEST
221 /* In test mode, increase the size of this structure a bit so that
222 ** it is larger than the struct CrashFile defined in test6.c.
223 */
224 char aPadding[32];
225#endif
drh9cbe6352005-11-29 03:13:21 +0000226};
227
drhb00d8622014-01-01 15:18:36 +0000228/* This variable holds the process id (pid) from when the xRandomness()
229** method was called. If xOpen() is called from a different process id,
230** indicating that a fork() has occurred, the PRNG will be reset.
231*/
drh8cd5b252015-03-02 22:06:43 +0000232static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000233
drh0ccebe72005-06-07 22:22:50 +0000234/*
drha7e61d82011-03-12 17:02:57 +0000235** Allowed values for the unixFile.ctrlFlags bitmask:
236*/
drhf0b190d2011-07-26 16:03:07 +0000237#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
238#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
239#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000240#ifndef SQLITE_DISABLE_DIRSYNC
241# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
242#else
243# define UNIXFILE_DIRSYNC 0x00
244#endif
drhcb15f352011-12-23 01:04:17 +0000245#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000246#define UNIXFILE_DELETE 0x20 /* Delete on close */
247#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
248#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000249#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drha7e61d82011-03-12 17:02:57 +0000250
251/*
drh198bf392006-01-06 21:52:49 +0000252** Include code that is common to all os_*.c files
253*/
254#include "os_common.h"
255
256/*
drh0ccebe72005-06-07 22:22:50 +0000257** Define various macros that are missing from some systems.
258*/
drhbbd42a62004-05-22 17:41:58 +0000259#ifndef O_LARGEFILE
260# define O_LARGEFILE 0
261#endif
262#ifdef SQLITE_DISABLE_LFS
263# undef O_LARGEFILE
264# define O_LARGEFILE 0
265#endif
266#ifndef O_NOFOLLOW
267# define O_NOFOLLOW 0
268#endif
269#ifndef O_BINARY
270# define O_BINARY 0
271#endif
272
273/*
drh2b4b5962005-06-15 17:47:55 +0000274** The threadid macro resolves to the thread-id or to 0. Used for
275** testing and debugging only.
276*/
drhd677b3d2007-08-20 22:48:41 +0000277#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000278#define threadid pthread_self()
279#else
280#define threadid 0
281#endif
282
drh99ab3b12011-03-02 15:09:07 +0000283/*
dane6ecd662013-04-01 17:56:59 +0000284** HAVE_MREMAP defaults to true on Linux and false everywhere else.
285*/
286#if !defined(HAVE_MREMAP)
287# if defined(__linux__) && defined(_GNU_SOURCE)
288# define HAVE_MREMAP 1
289# else
290# define HAVE_MREMAP 0
291# endif
292#endif
293
294/*
dan2ee53412014-09-06 16:49:40 +0000295** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
296** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
297*/
298#ifdef __ANDROID__
299# define lseek lseek64
300#endif
301
302/*
drh9a3baf12011-04-25 18:01:27 +0000303** Different Unix systems declare open() in different ways. Same use
304** open(const char*,int,mode_t). Others use open(const char*,int,...).
305** The difference is important when using a pointer to the function.
306**
307** The safest way to deal with the problem is to always use this wrapper
308** which always has the same well-defined interface.
309*/
310static int posixOpen(const char *zFile, int flags, int mode){
311 return open(zFile, flags, mode);
312}
313
drhed466822012-05-31 13:10:49 +0000314/*
315** On some systems, calls to fchown() will trigger a message in a security
316** log if they come from non-root processes. So avoid calling fchown() if
317** we are not running as root.
318*/
319static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000320#if OS_VXWORKS
321 return 0;
322#else
drhed466822012-05-31 13:10:49 +0000323 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000324#endif
drhed466822012-05-31 13:10:49 +0000325}
326
drh90315a22011-08-10 01:52:12 +0000327/* Forward reference */
328static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000329static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000330
drh9a3baf12011-04-25 18:01:27 +0000331/*
drh99ab3b12011-03-02 15:09:07 +0000332** Many system calls are accessed through pointer-to-functions so that
333** they may be overridden at runtime to facilitate fault injection during
334** testing and sandboxing. The following array holds the names and pointers
335** to all overrideable system calls.
336*/
337static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000338 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000339 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
340 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000341} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000342 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
343#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000344
drh58ad5802011-03-23 22:02:23 +0000345 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000346#define osClose ((int(*)(int))aSyscall[1].pCurrent)
347
drh58ad5802011-03-23 22:02:23 +0000348 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000349#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
350
drh58ad5802011-03-23 22:02:23 +0000351 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000352#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
353
drh58ad5802011-03-23 22:02:23 +0000354 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000355#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
356
357/*
358** The DJGPP compiler environment looks mostly like Unix, but it
359** lacks the fcntl() system call. So redefine fcntl() to be something
360** that always succeeds. This means that locking does not occur under
361** DJGPP. But it is DOS - what did you expect?
362*/
363#ifdef __DJGPP__
364 { "fstat", 0, 0 },
365#define osFstat(a,b,c) 0
366#else
drh58ad5802011-03-23 22:02:23 +0000367 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
369#endif
370
drh58ad5802011-03-23 22:02:23 +0000371 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000372#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
373
drh58ad5802011-03-23 22:02:23 +0000374 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000375#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000376
drh58ad5802011-03-23 22:02:23 +0000377 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000378#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
379
drh91be7dc2014-08-11 13:53:30 +0000380#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000381 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000384#endif
385#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
386
387#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000388 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000389#else
drh58ad5802011-03-23 22:02:23 +0000390 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000391#endif
392#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
393
drh58ad5802011-03-23 22:02:23 +0000394 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000395#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
396
drh91be7dc2014-08-11 13:53:30 +0000397#if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
drh58ad5802011-03-23 22:02:23 +0000398 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000399#else
drh58ad5802011-03-23 22:02:23 +0000400 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000401#endif
402#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
403 aSyscall[12].pCurrent)
404
405#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000406 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000407#else
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000409#endif
410#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
411 aSyscall[13].pCurrent)
412
drh58ad5802011-03-23 22:02:23 +0000413 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000414#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000415
416#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000417 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000418#else
drh58ad5802011-03-23 22:02:23 +0000419 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000420#endif
dan0fd7d862011-03-29 10:04:23 +0000421#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000422
drh036ac7f2011-08-08 23:18:05 +0000423 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
424#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
425
drh90315a22011-08-10 01:52:12 +0000426 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
427#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
428
drh9ef6bc42011-11-04 02:24:02 +0000429 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
430#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
431
432 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
433#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
434
drhed466822012-05-31 13:10:49 +0000435 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000436#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000437
dan4dd51442013-08-26 14:30:25 +0000438#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000439 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
440#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
441
drhd1ab8062013-03-25 20:50:25 +0000442 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
443#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
444
dane6ecd662013-04-01 17:56:59 +0000445#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000446 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
447#else
448 { "mremap", (sqlite3_syscall_ptr)0, 0 },
449#endif
450#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000451 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
452#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
453
dan702eec12014-06-23 10:04:58 +0000454#endif
455
drhe562be52011-03-02 18:01:10 +0000456}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000457
458/*
459** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000460** "unix" VFSes. Return SQLITE_OK opon successfully updating the
461** system call pointer, or SQLITE_NOTFOUND if there is no configurable
462** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000463*/
464static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000465 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
466 const char *zName, /* Name of system call to override */
467 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000468){
drh58ad5802011-03-23 22:02:23 +0000469 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000470 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000471
472 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000473 if( zName==0 ){
474 /* If no zName is given, restore all system calls to their default
475 ** settings and return NULL
476 */
dan51438a72011-04-02 17:00:47 +0000477 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000478 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
479 if( aSyscall[i].pDefault ){
480 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000481 }
482 }
483 }else{
484 /* If zName is specified, operate on only the one system call
485 ** specified.
486 */
487 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
488 if( strcmp(zName, aSyscall[i].zName)==0 ){
489 if( aSyscall[i].pDefault==0 ){
490 aSyscall[i].pDefault = aSyscall[i].pCurrent;
491 }
drh1df30962011-03-02 19:06:42 +0000492 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000493 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
494 aSyscall[i].pCurrent = pNewFunc;
495 break;
496 }
497 }
498 }
499 return rc;
500}
501
drh1df30962011-03-02 19:06:42 +0000502/*
503** Return the value of a system call. Return NULL if zName is not a
504** recognized system call name. NULL is also returned if the system call
505** is currently undefined.
506*/
drh58ad5802011-03-23 22:02:23 +0000507static sqlite3_syscall_ptr unixGetSystemCall(
508 sqlite3_vfs *pNotUsed,
509 const char *zName
510){
511 unsigned int i;
512
513 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000514 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
515 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
516 }
517 return 0;
518}
519
520/*
521** Return the name of the first system call after zName. If zName==NULL
522** then return the name of the first system call. Return NULL if zName
523** is the last system call or if zName is not the name of a valid
524** system call.
525*/
526static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000527 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000528
529 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000530 if( zName ){
531 for(i=0; i<ArraySize(aSyscall)-1; i++){
532 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000533 }
534 }
dan0fd7d862011-03-29 10:04:23 +0000535 for(i++; i<ArraySize(aSyscall); i++){
536 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000537 }
538 return 0;
539}
540
drhad4f1e52011-03-04 15:43:57 +0000541/*
drh77a3fdc2013-08-30 14:24:12 +0000542** Do not accept any file descriptor less than this value, in order to avoid
543** opening database file using file descriptors that are commonly used for
544** standard input, output, and error.
545*/
546#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
547# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
548#endif
549
550/*
drh8c815d12012-02-13 20:16:37 +0000551** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000552** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000553**
554** If the file creation mode "m" is 0 then set it to the default for
555** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
556** 0644) as modified by the system umask. If m is not 0, then
557** make the file creation mode be exactly m ignoring the umask.
558**
559** The m parameter will be non-zero only when creating -wal, -journal,
560** and -shm files. We want those files to have *exactly* the same
561** permissions as their original database, unadulterated by the umask.
562** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
563** transaction crashes and leaves behind hot journals, then any
564** process that is able to write to the database will also be able to
565** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000566*/
drh8c815d12012-02-13 20:16:37 +0000567static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000568 int fd;
drhe1186ab2013-01-04 20:45:13 +0000569 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000570 while(1){
drh5adc60b2012-04-14 13:25:11 +0000571#if defined(O_CLOEXEC)
572 fd = osOpen(z,f|O_CLOEXEC,m2);
573#else
574 fd = osOpen(z,f,m2);
575#endif
drh5128d002013-08-30 06:20:23 +0000576 if( fd<0 ){
577 if( errno==EINTR ) continue;
578 break;
579 }
drh77a3fdc2013-08-30 14:24:12 +0000580 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000581 osClose(fd);
582 sqlite3_log(SQLITE_WARNING,
583 "attempt to open \"%s\" as file descriptor %d", z, fd);
584 fd = -1;
585 if( osOpen("/dev/null", f, m)<0 ) break;
586 }
drhe1186ab2013-01-04 20:45:13 +0000587 if( fd>=0 ){
588 if( m!=0 ){
589 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000590 if( osFstat(fd, &statbuf)==0
591 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000592 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000593 ){
drhe1186ab2013-01-04 20:45:13 +0000594 osFchmod(fd, m);
595 }
596 }
drh5adc60b2012-04-14 13:25:11 +0000597#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000598 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000599#endif
drhe1186ab2013-01-04 20:45:13 +0000600 }
drh5adc60b2012-04-14 13:25:11 +0000601 return fd;
drhad4f1e52011-03-04 15:43:57 +0000602}
danielk197713adf8a2004-06-03 16:08:41 +0000603
drh107886a2008-11-21 22:21:50 +0000604/*
dan9359c7b2009-08-21 08:29:10 +0000605** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000606** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000607** vxworksFileId objects used by this file, all of which may be
608** shared by multiple threads.
609**
610** Function unixMutexHeld() is used to assert() that the global mutex
611** is held when required. This function is only used as part of assert()
612** statements. e.g.
613**
614** unixEnterMutex()
615** assert( unixMutexHeld() );
616** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000617*/
618static void unixEnterMutex(void){
619 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
620}
621static void unixLeaveMutex(void){
622 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
623}
dan9359c7b2009-08-21 08:29:10 +0000624#ifdef SQLITE_DEBUG
625static int unixMutexHeld(void) {
626 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
627}
628#endif
drh107886a2008-11-21 22:21:50 +0000629
drh734c9862008-11-28 15:37:20 +0000630
drh30ddce62011-10-15 00:16:30 +0000631#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000632/*
633** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000634** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000635** integer lock-type.
636*/
drh308c2a52010-05-14 11:30:18 +0000637static const char *azFileLock(int eFileLock){
638 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000639 case NO_LOCK: return "NONE";
640 case SHARED_LOCK: return "SHARED";
641 case RESERVED_LOCK: return "RESERVED";
642 case PENDING_LOCK: return "PENDING";
643 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000644 }
645 return "ERROR";
646}
647#endif
648
649#ifdef SQLITE_LOCK_TRACE
650/*
651** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000652**
drh734c9862008-11-28 15:37:20 +0000653** This routine is used for troubleshooting locks on multithreaded
654** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
655** command-line option on the compiler. This code is normally
656** turned off.
657*/
658static int lockTrace(int fd, int op, struct flock *p){
659 char *zOpName, *zType;
660 int s;
661 int savedErrno;
662 if( op==F_GETLK ){
663 zOpName = "GETLK";
664 }else if( op==F_SETLK ){
665 zOpName = "SETLK";
666 }else{
drh99ab3b12011-03-02 15:09:07 +0000667 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000668 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
669 return s;
670 }
671 if( p->l_type==F_RDLCK ){
672 zType = "RDLCK";
673 }else if( p->l_type==F_WRLCK ){
674 zType = "WRLCK";
675 }else if( p->l_type==F_UNLCK ){
676 zType = "UNLCK";
677 }else{
678 assert( 0 );
679 }
680 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000681 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000682 savedErrno = errno;
683 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
684 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
685 (int)p->l_pid, s);
686 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
687 struct flock l2;
688 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000689 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000690 if( l2.l_type==F_RDLCK ){
691 zType = "RDLCK";
692 }else if( l2.l_type==F_WRLCK ){
693 zType = "WRLCK";
694 }else if( l2.l_type==F_UNLCK ){
695 zType = "UNLCK";
696 }else{
697 assert( 0 );
698 }
699 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
700 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
701 }
702 errno = savedErrno;
703 return s;
704}
drh99ab3b12011-03-02 15:09:07 +0000705#undef osFcntl
706#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000707#endif /* SQLITE_LOCK_TRACE */
708
drhff812312011-02-23 13:33:46 +0000709/*
710** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000711**
drhe6d41732015-02-21 00:49:00 +0000712** All calls to ftruncate() within this file should be made through
713** this wrapper. On the Android platform, bypassing the logic below
714** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000715*/
drhff812312011-02-23 13:33:46 +0000716static int robust_ftruncate(int h, sqlite3_int64 sz){
717 int rc;
dan2ee53412014-09-06 16:49:40 +0000718#ifdef __ANDROID__
719 /* On Android, ftruncate() always uses 32-bit offsets, even if
720 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000721 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000722 ** such attempts. */
723 if( sz>(sqlite3_int64)0x7FFFFFFF ){
724 rc = SQLITE_OK;
725 }else
726#endif
drh99ab3b12011-03-02 15:09:07 +0000727 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000728 return rc;
729}
drh734c9862008-11-28 15:37:20 +0000730
731/*
732** This routine translates a standard POSIX errno code into something
733** useful to the clients of the sqlite3 functions. Specifically, it is
734** intended to translate a variety of "try again" errors into SQLITE_BUSY
735** and a variety of "please close the file descriptor NOW" errors into
736** SQLITE_IOERR
737**
738** Errors during initialization of locks, or file system support for locks,
739** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
740*/
741static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
742 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000743#if 0
744 /* At one point this code was not commented out. In theory, this branch
745 ** should never be hit, as this function should only be called after
746 ** a locking-related function (i.e. fcntl()) has returned non-zero with
747 ** the value of errno as the first argument. Since a system call has failed,
748 ** errno should be non-zero.
749 **
750 ** Despite this, if errno really is zero, we still don't want to return
751 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
752 ** propagated back to the caller. Commenting this branch out means errno==0
753 ** will be handled by the "default:" case below.
754 */
drh734c9862008-11-28 15:37:20 +0000755 case 0:
756 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000757#endif
758
drh734c9862008-11-28 15:37:20 +0000759 case EAGAIN:
760 case ETIMEDOUT:
761 case EBUSY:
762 case EINTR:
763 case ENOLCK:
764 /* random NFS retry error, unless during file system support
765 * introspection, in which it actually means what it says */
766 return SQLITE_BUSY;
767
768 case EACCES:
769 /* EACCES is like EAGAIN during locking operations, but not any other time*/
770 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000771 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
772 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
773 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000774 return SQLITE_BUSY;
775 }
776 /* else fall through */
777 case EPERM:
778 return SQLITE_PERM;
779
drh734c9862008-11-28 15:37:20 +0000780#if EOPNOTSUPP!=ENOTSUP
781 case EOPNOTSUPP:
782 /* something went terribly awry, unless during file system support
783 * introspection, in which it actually means what it says */
784#endif
785#ifdef ENOTSUP
786 case ENOTSUP:
787 /* invalid fd, unless during file system support introspection, in which
788 * it actually means what it says */
789#endif
790 case EIO:
791 case EBADF:
792 case EINVAL:
793 case ENOTCONN:
794 case ENODEV:
795 case ENXIO:
796 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000797#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000798 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000799#endif
drh734c9862008-11-28 15:37:20 +0000800 case ENOSYS:
801 /* these should force the client to close the file and reconnect */
802
803 default:
804 return sqliteIOErr;
805 }
806}
807
808
drh734c9862008-11-28 15:37:20 +0000809/******************************************************************************
810****************** Begin Unique File ID Utility Used By VxWorks ***************
811**
812** On most versions of unix, we can get a unique ID for a file by concatenating
813** the device number and the inode number. But this does not work on VxWorks.
814** On VxWorks, a unique file id must be based on the canonical filename.
815**
816** A pointer to an instance of the following structure can be used as a
817** unique file ID in VxWorks. Each instance of this structure contains
818** a copy of the canonical filename. There is also a reference count.
819** The structure is reclaimed when the number of pointers to it drops to
820** zero.
821**
822** There are never very many files open at one time and lookups are not
823** a performance-critical path, so it is sufficient to put these
824** structures on a linked list.
825*/
826struct vxworksFileId {
827 struct vxworksFileId *pNext; /* Next in a list of them all */
828 int nRef; /* Number of references to this one */
829 int nName; /* Length of the zCanonicalName[] string */
830 char *zCanonicalName; /* Canonical filename */
831};
832
833#if OS_VXWORKS
834/*
drh9b35ea62008-11-29 02:20:26 +0000835** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000836** variable:
837*/
838static struct vxworksFileId *vxworksFileList = 0;
839
840/*
841** Simplify a filename into its canonical form
842** by making the following changes:
843**
844** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000845** * convert /./ into just /
846** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000847**
848** Changes are made in-place. Return the new name length.
849**
850** The original filename is in z[0..n-1]. Return the number of
851** characters in the simplified name.
852*/
853static int vxworksSimplifyName(char *z, int n){
854 int i, j;
855 while( n>1 && z[n-1]=='/' ){ n--; }
856 for(i=j=0; i<n; i++){
857 if( z[i]=='/' ){
858 if( z[i+1]=='/' ) continue;
859 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
860 i += 1;
861 continue;
862 }
863 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
864 while( j>0 && z[j-1]!='/' ){ j--; }
865 if( j>0 ){ j--; }
866 i += 2;
867 continue;
868 }
869 }
870 z[j++] = z[i];
871 }
872 z[j] = 0;
873 return j;
874}
875
876/*
877** Find a unique file ID for the given absolute pathname. Return
878** a pointer to the vxworksFileId object. This pointer is the unique
879** file ID.
880**
881** The nRef field of the vxworksFileId object is incremented before
882** the object is returned. A new vxworksFileId object is created
883** and added to the global list if necessary.
884**
885** If a memory allocation error occurs, return NULL.
886*/
887static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
888 struct vxworksFileId *pNew; /* search key and new file ID */
889 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
890 int n; /* Length of zAbsoluteName string */
891
892 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000893 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000894 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
895 if( pNew==0 ) return 0;
896 pNew->zCanonicalName = (char*)&pNew[1];
897 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
898 n = vxworksSimplifyName(pNew->zCanonicalName, n);
899
900 /* Search for an existing entry that matching the canonical name.
901 ** If found, increment the reference count and return a pointer to
902 ** the existing file ID.
903 */
904 unixEnterMutex();
905 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
906 if( pCandidate->nName==n
907 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
908 ){
909 sqlite3_free(pNew);
910 pCandidate->nRef++;
911 unixLeaveMutex();
912 return pCandidate;
913 }
914 }
915
916 /* No match was found. We will make a new file ID */
917 pNew->nRef = 1;
918 pNew->nName = n;
919 pNew->pNext = vxworksFileList;
920 vxworksFileList = pNew;
921 unixLeaveMutex();
922 return pNew;
923}
924
925/*
926** Decrement the reference count on a vxworksFileId object. Free
927** the object when the reference count reaches zero.
928*/
929static void vxworksReleaseFileId(struct vxworksFileId *pId){
930 unixEnterMutex();
931 assert( pId->nRef>0 );
932 pId->nRef--;
933 if( pId->nRef==0 ){
934 struct vxworksFileId **pp;
935 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
936 assert( *pp==pId );
937 *pp = pId->pNext;
938 sqlite3_free(pId);
939 }
940 unixLeaveMutex();
941}
942#endif /* OS_VXWORKS */
943/*************** End of Unique File ID Utility Used By VxWorks ****************
944******************************************************************************/
945
946
947/******************************************************************************
948*************************** Posix Advisory Locking ****************************
949**
drh9b35ea62008-11-29 02:20:26 +0000950** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000951** section 6.5.2.2 lines 483 through 490 specify that when a process
952** sets or clears a lock, that operation overrides any prior locks set
953** by the same process. It does not explicitly say so, but this implies
954** that it overrides locks set by the same process using a different
955** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000956**
957** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000958** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
959**
960** Suppose ./file1 and ./file2 are really the same file (because
961** one is a hard or symbolic link to the other) then if you set
962** an exclusive lock on fd1, then try to get an exclusive lock
963** on fd2, it works. I would have expected the second lock to
964** fail since there was already a lock on the file due to fd1.
965** But not so. Since both locks came from the same process, the
966** second overrides the first, even though they were on different
967** file descriptors opened on different file names.
968**
drh734c9862008-11-28 15:37:20 +0000969** This means that we cannot use POSIX locks to synchronize file access
970** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000971** to synchronize access for threads in separate processes, but not
972** threads within the same process.
973**
974** To work around the problem, SQLite has to manage file locks internally
975** on its own. Whenever a new database is opened, we have to find the
976** specific inode of the database file (the inode is determined by the
977** st_dev and st_ino fields of the stat structure that fstat() fills in)
978** and check for locks already existing on that inode. When locks are
979** created or removed, we have to look at our own internal record of the
980** locks to see if another thread has previously set a lock on that same
981** inode.
982**
drh9b35ea62008-11-29 02:20:26 +0000983** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
984** For VxWorks, we have to use the alternative unique ID system based on
985** canonical filename and implemented in the previous division.)
986**
danielk1977ad94b582007-08-20 06:44:22 +0000987** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000988** descriptor. It is now a structure that holds the integer file
989** descriptor and a pointer to a structure that describes the internal
990** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000991** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000992** point to the same locking structure. The locking structure keeps
993** a reference count (so we will know when to delete it) and a "cnt"
994** field that tells us its internal lock status. cnt==0 means the
995** file is unlocked. cnt==-1 means the file has an exclusive lock.
996** cnt>0 means there are cnt shared locks on the file.
997**
998** Any attempt to lock or unlock a file first checks the locking
999** structure. The fcntl() system call is only invoked to set a
1000** POSIX lock if the internal lock structure transitions between
1001** a locked and an unlocked state.
1002**
drh734c9862008-11-28 15:37:20 +00001003** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001004**
1005** If you close a file descriptor that points to a file that has locks,
1006** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001007** released. To work around this problem, each unixInodeInfo object
1008** maintains a count of the number of pending locks on tha inode.
1009** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001010** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001011** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001012** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001013** be closed and that list is walked (and cleared) when the last lock
1014** clears.
1015**
drh9b35ea62008-11-29 02:20:26 +00001016** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001017**
drh9b35ea62008-11-29 02:20:26 +00001018** Many older versions of linux use the LinuxThreads library which is
1019** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001020** A cannot be modified or overridden by a different thread B.
1021** Only thread A can modify the lock. Locking behavior is correct
1022** if the appliation uses the newer Native Posix Thread Library (NPTL)
1023** on linux - with NPTL a lock created by thread A can override locks
1024** in thread B. But there is no way to know at compile-time which
1025** threading library is being used. So there is no way to know at
1026** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001027** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001028** current process.
drh5fdae772004-06-29 03:29:00 +00001029**
drh8af6c222010-05-14 12:43:01 +00001030** SQLite used to support LinuxThreads. But support for LinuxThreads
1031** was dropped beginning with version 3.7.0. SQLite will still work with
1032** LinuxThreads provided that (1) there is no more than one connection
1033** per database file in the same process and (2) database connections
1034** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001035*/
1036
1037/*
1038** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001039** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001040*/
1041struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001042 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001043#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001044 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001045#else
drh107886a2008-11-21 22:21:50 +00001046 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001047#endif
1048};
1049
1050/*
drhbbd42a62004-05-22 17:41:58 +00001051** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001052** inode. Or, on LinuxThreads, there is one of these structures for
1053** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001054**
danielk1977ad94b582007-08-20 06:44:22 +00001055** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001056** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001057** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001058*/
drh8af6c222010-05-14 12:43:01 +00001059struct unixInodeInfo {
1060 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001061 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001062 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1063 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001064 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001065 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1066 int nLock; /* Number of outstanding file locks */
1067 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1068 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1069 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001070#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001071 unsigned long long sharedByte; /* for AFP simulated shared lock */
1072#endif
drh6c7d5c52008-11-21 20:32:33 +00001073#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001074 sem_t *pSem; /* Named POSIX semaphore */
1075 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001076#endif
drhbbd42a62004-05-22 17:41:58 +00001077};
1078
drhda0e7682008-07-30 15:27:54 +00001079/*
drh8af6c222010-05-14 12:43:01 +00001080** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001081*/
drhd91c68f2010-05-14 14:52:25 +00001082static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001083
drh5fdae772004-06-29 03:29:00 +00001084/*
dane18d4952011-02-21 11:46:24 +00001085**
1086** This function - unixLogError_x(), is only ever called via the macro
1087** unixLogError().
1088**
1089** It is invoked after an error occurs in an OS function and errno has been
1090** set. It logs a message using sqlite3_log() containing the current value of
1091** errno and, if possible, the human-readable equivalent from strerror() or
1092** strerror_r().
1093**
1094** The first argument passed to the macro should be the error code that
1095** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1096** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001097** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001098** if any.
1099*/
drh0e9365c2011-03-02 02:08:13 +00001100#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1101static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001102 int errcode, /* SQLite error code */
1103 const char *zFunc, /* Name of OS function that failed */
1104 const char *zPath, /* File path associated with error */
1105 int iLine /* Source line number where error occurred */
1106){
1107 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001108 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001109
1110 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1111 ** the strerror() function to obtain the human-readable error message
1112 ** equivalent to errno. Otherwise, use strerror_r().
1113 */
1114#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1115 char aErr[80];
1116 memset(aErr, 0, sizeof(aErr));
1117 zErr = aErr;
1118
1119 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001120 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001121 ** returns a pointer to a buffer containing the error message. That pointer
1122 ** may point to aErr[], or it may point to some static storage somewhere.
1123 ** Otherwise, assume that the system provides the POSIX version of
1124 ** strerror_r(), which always writes an error message into aErr[].
1125 **
1126 ** If the code incorrectly assumes that it is the POSIX version that is
1127 ** available, the error message will often be an empty string. Not a
1128 ** huge problem. Incorrectly concluding that the GNU version is available
1129 ** could lead to a segfault though.
1130 */
1131#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1132 zErr =
1133# endif
drh0e9365c2011-03-02 02:08:13 +00001134 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001135
1136#elif SQLITE_THREADSAFE
1137 /* This is a threadsafe build, but strerror_r() is not available. */
1138 zErr = "";
1139#else
1140 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001141 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001142#endif
1143
drh0e9365c2011-03-02 02:08:13 +00001144 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001145 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001146 "os_unix.c:%d: (%d) %s(%s) - %s",
1147 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001148 );
1149
1150 return errcode;
1151}
1152
drh0e9365c2011-03-02 02:08:13 +00001153/*
1154** Close a file descriptor.
1155**
1156** We assume that close() almost always works, since it is only in a
1157** very sick application or on a very sick platform that it might fail.
1158** If it does fail, simply leak the file descriptor, but do log the
1159** error.
1160**
1161** Note that it is not safe to retry close() after EINTR since the
1162** file descriptor might have already been reused by another thread.
1163** So we don't even try to recover from an EINTR. Just log the error
1164** and move on.
1165*/
1166static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001167 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001168 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1169 pFile ? pFile->zPath : 0, lineno);
1170 }
1171}
dane18d4952011-02-21 11:46:24 +00001172
1173/*
drhe6d41732015-02-21 00:49:00 +00001174** Set the pFile->lastErrno. Do this in a subroutine as that provides
1175** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001176*/
1177static void storeLastErrno(unixFile *pFile, int error){
1178 pFile->lastErrno = error;
1179}
1180
1181/*
danb0ac3e32010-06-16 10:55:42 +00001182** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001183*/
drh0e9365c2011-03-02 02:08:13 +00001184static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001185 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001186 UnixUnusedFd *p;
1187 UnixUnusedFd *pNext;
1188 for(p=pInode->pUnused; p; p=pNext){
1189 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001190 robust_close(pFile, p->fd, __LINE__);
1191 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001192 }
drh0e9365c2011-03-02 02:08:13 +00001193 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001194}
1195
1196/*
drh8af6c222010-05-14 12:43:01 +00001197** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001198**
1199** The mutex entered using the unixEnterMutex() function must be held
1200** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001201*/
danb0ac3e32010-06-16 10:55:42 +00001202static void releaseInodeInfo(unixFile *pFile){
1203 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001204 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001205 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001206 pInode->nRef--;
1207 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001208 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001209 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001210 if( pInode->pPrev ){
1211 assert( pInode->pPrev->pNext==pInode );
1212 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001213 }else{
drh8af6c222010-05-14 12:43:01 +00001214 assert( inodeList==pInode );
1215 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001216 }
drh8af6c222010-05-14 12:43:01 +00001217 if( pInode->pNext ){
1218 assert( pInode->pNext->pPrev==pInode );
1219 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001220 }
drh8af6c222010-05-14 12:43:01 +00001221 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001222 }
drhbbd42a62004-05-22 17:41:58 +00001223 }
1224}
1225
1226/*
drh8af6c222010-05-14 12:43:01 +00001227** Given a file descriptor, locate the unixInodeInfo object that
1228** describes that file descriptor. Create a new one if necessary. The
1229** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001230**
dan9359c7b2009-08-21 08:29:10 +00001231** The mutex entered using the unixEnterMutex() function must be held
1232** when this function is called.
1233**
drh6c7d5c52008-11-21 20:32:33 +00001234** Return an appropriate error code.
1235*/
drh8af6c222010-05-14 12:43:01 +00001236static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001237 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001238 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001239){
1240 int rc; /* System call return code */
1241 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001242 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1243 struct stat statbuf; /* Low-level file information */
1244 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001245
dan9359c7b2009-08-21 08:29:10 +00001246 assert( unixMutexHeld() );
1247
drh6c7d5c52008-11-21 20:32:33 +00001248 /* Get low-level information about the file that we can used to
1249 ** create a unique name for the file.
1250 */
1251 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001252 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001253 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001254 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001255#ifdef EOVERFLOW
1256 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1257#endif
1258 return SQLITE_IOERR;
1259 }
1260
drheb0d74f2009-02-03 15:27:02 +00001261#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001262 /* On OS X on an msdos filesystem, the inode number is reported
1263 ** incorrectly for zero-size files. See ticket #3260. To work
1264 ** around this problem (we consider it a bug in OS X, not SQLite)
1265 ** we always increase the file size to 1 by writing a single byte
1266 ** prior to accessing the inode number. The one byte written is
1267 ** an ASCII 'S' character which also happens to be the first byte
1268 ** in the header of every SQLite database. In this way, if there
1269 ** is a race condition such that another thread has already populated
1270 ** the first page of the database, no damage is done.
1271 */
drh7ed97b92010-01-20 13:07:21 +00001272 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001273 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001274 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001275 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001276 return SQLITE_IOERR;
1277 }
drh99ab3b12011-03-02 15:09:07 +00001278 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001279 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001280 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001281 return SQLITE_IOERR;
1282 }
1283 }
drheb0d74f2009-02-03 15:27:02 +00001284#endif
drh6c7d5c52008-11-21 20:32:33 +00001285
drh8af6c222010-05-14 12:43:01 +00001286 memset(&fileId, 0, sizeof(fileId));
1287 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001288#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001289 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001290#else
drh8af6c222010-05-14 12:43:01 +00001291 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001292#endif
drh8af6c222010-05-14 12:43:01 +00001293 pInode = inodeList;
1294 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1295 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001296 }
drh8af6c222010-05-14 12:43:01 +00001297 if( pInode==0 ){
1298 pInode = sqlite3_malloc( sizeof(*pInode) );
1299 if( pInode==0 ){
1300 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001301 }
drh8af6c222010-05-14 12:43:01 +00001302 memset(pInode, 0, sizeof(*pInode));
1303 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1304 pInode->nRef = 1;
1305 pInode->pNext = inodeList;
1306 pInode->pPrev = 0;
1307 if( inodeList ) inodeList->pPrev = pInode;
1308 inodeList = pInode;
1309 }else{
1310 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001311 }
drh8af6c222010-05-14 12:43:01 +00001312 *ppInode = pInode;
1313 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001314}
drh6c7d5c52008-11-21 20:32:33 +00001315
drhb959a012013-12-07 12:29:22 +00001316/*
1317** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1318*/
1319static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001320#if OS_VXWORKS
1321 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1322#else
drhb959a012013-12-07 12:29:22 +00001323 struct stat buf;
1324 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001325 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001326#endif
drhb959a012013-12-07 12:29:22 +00001327}
1328
aswift5b1a2562008-08-22 00:22:35 +00001329
1330/*
drhfbc7e882013-04-11 01:16:15 +00001331** Check a unixFile that is a database. Verify the following:
1332**
1333** (1) There is exactly one hard link on the file
1334** (2) The file is not a symbolic link
1335** (3) The file has not been renamed or unlinked
1336**
1337** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1338*/
1339static void verifyDbFile(unixFile *pFile){
1340 struct stat buf;
1341 int rc;
drh3044b512014-06-16 16:41:52 +00001342 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1343 /* One or more of the following warnings have already been issued. Do not
1344 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001345 return;
1346 }
1347 rc = osFstat(pFile->h, &buf);
1348 if( rc!=0 ){
1349 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1350 pFile->ctrlFlags |= UNIXFILE_WARNED;
1351 return;
1352 }
drh3044b512014-06-16 16:41:52 +00001353 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001354 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1355 pFile->ctrlFlags |= UNIXFILE_WARNED;
1356 return;
1357 }
1358 if( buf.st_nlink>1 ){
1359 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1360 pFile->ctrlFlags |= UNIXFILE_WARNED;
1361 return;
1362 }
drhb959a012013-12-07 12:29:22 +00001363 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001364 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1365 pFile->ctrlFlags |= UNIXFILE_WARNED;
1366 return;
1367 }
1368}
1369
1370
1371/*
danielk197713adf8a2004-06-03 16:08:41 +00001372** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001373** file by this or any other process. If such a lock is held, set *pResOut
1374** to a non-zero value otherwise *pResOut is set to zero. The return value
1375** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001376*/
danielk1977861f7452008-06-05 11:39:11 +00001377static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001378 int rc = SQLITE_OK;
1379 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001380 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001381
danielk1977861f7452008-06-05 11:39:11 +00001382 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1383
drh054889e2005-11-30 03:20:31 +00001384 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001385 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001386
1387 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001388 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001389 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001390 }
1391
drh2ac3ee92004-06-07 16:27:46 +00001392 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001393 */
danielk197709480a92009-02-09 05:32:32 +00001394#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001395 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001396 struct flock lock;
1397 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001398 lock.l_start = RESERVED_BYTE;
1399 lock.l_len = 1;
1400 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001401 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1402 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001403 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001404 } else if( lock.l_type!=F_UNLCK ){
1405 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001406 }
1407 }
danielk197709480a92009-02-09 05:32:32 +00001408#endif
danielk197713adf8a2004-06-03 16:08:41 +00001409
drh6c7d5c52008-11-21 20:32:33 +00001410 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001411 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001412
aswift5b1a2562008-08-22 00:22:35 +00001413 *pResOut = reserved;
1414 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001415}
1416
1417/*
drha7e61d82011-03-12 17:02:57 +00001418** Attempt to set a system-lock on the file pFile. The lock is
1419** described by pLock.
1420**
drh77197112011-03-15 19:08:48 +00001421** If the pFile was opened read/write from unix-excl, then the only lock
1422** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001423** the first time any lock is attempted. All subsequent system locking
1424** operations become no-ops. Locking operations still happen internally,
1425** in order to coordinate access between separate database connections
1426** within this process, but all of that is handled in memory and the
1427** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001428**
1429** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1430** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1431** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001432**
1433** Zero is returned if the call completes successfully, or -1 if a call
1434** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001435*/
1436static int unixFileLock(unixFile *pFile, struct flock *pLock){
1437 int rc;
drh3cb93392011-03-12 18:10:44 +00001438 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001439 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001440 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001441 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1442 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1443 ){
drh3cb93392011-03-12 18:10:44 +00001444 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001445 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001446 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001447 lock.l_whence = SEEK_SET;
1448 lock.l_start = SHARED_FIRST;
1449 lock.l_len = SHARED_SIZE;
1450 lock.l_type = F_WRLCK;
1451 rc = osFcntl(pFile->h, F_SETLK, &lock);
1452 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001453 pInode->bProcessLock = 1;
1454 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001455 }else{
1456 rc = 0;
1457 }
1458 }else{
1459 rc = osFcntl(pFile->h, F_SETLK, pLock);
1460 }
1461 return rc;
1462}
1463
1464/*
drh308c2a52010-05-14 11:30:18 +00001465** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001466** of the following:
1467**
drh2ac3ee92004-06-07 16:27:46 +00001468** (1) SHARED_LOCK
1469** (2) RESERVED_LOCK
1470** (3) PENDING_LOCK
1471** (4) EXCLUSIVE_LOCK
1472**
drhb3e04342004-06-08 00:47:47 +00001473** Sometimes when requesting one lock state, additional lock states
1474** are inserted in between. The locking might fail on one of the later
1475** transitions leaving the lock state different from what it started but
1476** still short of its goal. The following chart shows the allowed
1477** transitions and the inserted intermediate states:
1478**
1479** UNLOCKED -> SHARED
1480** SHARED -> RESERVED
1481** SHARED -> (PENDING) -> EXCLUSIVE
1482** RESERVED -> (PENDING) -> EXCLUSIVE
1483** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001484**
drha6abd042004-06-09 17:37:22 +00001485** This routine will only increase a lock. Use the sqlite3OsUnlock()
1486** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001487*/
drh308c2a52010-05-14 11:30:18 +00001488static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001489 /* The following describes the implementation of the various locks and
1490 ** lock transitions in terms of the POSIX advisory shared and exclusive
1491 ** lock primitives (called read-locks and write-locks below, to avoid
1492 ** confusion with SQLite lock names). The algorithms are complicated
1493 ** slightly in order to be compatible with windows systems simultaneously
1494 ** accessing the same database file, in case that is ever required.
1495 **
1496 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1497 ** byte', each single bytes at well known offsets, and the 'shared byte
1498 ** range', a range of 510 bytes at a well known offset.
1499 **
1500 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1501 ** byte'. If this is successful, a random byte from the 'shared byte
1502 ** range' is read-locked and the lock on the 'pending byte' released.
1503 **
danielk197790ba3bd2004-06-25 08:32:25 +00001504 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1505 ** A RESERVED lock is implemented by grabbing a write-lock on the
1506 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001507 **
1508 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001509 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1510 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1511 ** obtained, but existing SHARED locks are allowed to persist. A process
1512 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1513 ** This property is used by the algorithm for rolling back a journal file
1514 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001515 **
danielk197790ba3bd2004-06-25 08:32:25 +00001516 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1517 ** implemented by obtaining a write-lock on the entire 'shared byte
1518 ** range'. Since all other locks require a read-lock on one of the bytes
1519 ** within this range, this ensures that no other locks are held on the
1520 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001521 **
1522 ** The reason a single byte cannot be used instead of the 'shared byte
1523 ** range' is that some versions of windows do not support read-locks. By
1524 ** locking a random byte from a range, concurrent SHARED locks may exist
1525 ** even if the locking primitive used is always a write-lock.
1526 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001527 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001528 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001529 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001530 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001531 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001532
drh054889e2005-11-30 03:20:31 +00001533 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001534 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1535 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001536 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1537 osGetpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001538
1539 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001540 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001541 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001542 */
drh308c2a52010-05-14 11:30:18 +00001543 if( pFile->eFileLock>=eFileLock ){
1544 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1545 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001546 return SQLITE_OK;
1547 }
1548
drh0c2694b2009-09-03 16:23:44 +00001549 /* Make sure the locking sequence is correct.
1550 ** (1) We never move from unlocked to anything higher than shared lock.
1551 ** (2) SQLite never explicitly requests a pendig lock.
1552 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001553 */
drh308c2a52010-05-14 11:30:18 +00001554 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1555 assert( eFileLock!=PENDING_LOCK );
1556 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001557
drh8af6c222010-05-14 12:43:01 +00001558 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001559 */
drh6c7d5c52008-11-21 20:32:33 +00001560 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001561 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001562
danielk1977ad94b582007-08-20 06:44:22 +00001563 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001564 ** handle that precludes the requested lock, return BUSY.
1565 */
drh8af6c222010-05-14 12:43:01 +00001566 if( (pFile->eFileLock!=pInode->eFileLock &&
1567 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001568 ){
1569 rc = SQLITE_BUSY;
1570 goto end_lock;
1571 }
1572
1573 /* If a SHARED lock is requested, and some thread using this PID already
1574 ** has a SHARED or RESERVED lock, then increment reference counts and
1575 ** return SQLITE_OK.
1576 */
drh308c2a52010-05-14 11:30:18 +00001577 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001578 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001579 assert( eFileLock==SHARED_LOCK );
1580 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001581 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001582 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001583 pInode->nShared++;
1584 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001585 goto end_lock;
1586 }
1587
danielk19779a1d0ab2004-06-01 14:09:28 +00001588
drh3cde3bb2004-06-12 02:17:14 +00001589 /* A PENDING lock is needed before acquiring a SHARED lock and before
1590 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1591 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001592 */
drh0c2694b2009-09-03 16:23:44 +00001593 lock.l_len = 1L;
1594 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001595 if( eFileLock==SHARED_LOCK
1596 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001597 ){
drh308c2a52010-05-14 11:30:18 +00001598 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001599 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001600 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001601 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001602 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001603 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001604 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001605 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001606 goto end_lock;
1607 }
drh3cde3bb2004-06-12 02:17:14 +00001608 }
1609
1610
1611 /* If control gets to this point, then actually go ahead and make
1612 ** operating system calls for the specified lock.
1613 */
drh308c2a52010-05-14 11:30:18 +00001614 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001615 assert( pInode->nShared==0 );
1616 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001617 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001618
drh2ac3ee92004-06-07 16:27:46 +00001619 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001620 lock.l_start = SHARED_FIRST;
1621 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001622 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001623 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001624 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001625 }
dan661d71a2011-03-30 19:08:03 +00001626
drh2ac3ee92004-06-07 16:27:46 +00001627 /* Drop the temporary PENDING lock */
1628 lock.l_start = PENDING_BYTE;
1629 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001630 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001631 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1632 /* This could happen with a network mount */
1633 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001634 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001635 }
dan661d71a2011-03-30 19:08:03 +00001636
1637 if( rc ){
1638 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001639 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001640 }
dan661d71a2011-03-30 19:08:03 +00001641 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001642 }else{
drh308c2a52010-05-14 11:30:18 +00001643 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001644 pInode->nLock++;
1645 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001646 }
drh8af6c222010-05-14 12:43:01 +00001647 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001648 /* We are trying for an exclusive lock but another thread in this
1649 ** same process is still holding a shared lock. */
1650 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001651 }else{
drh3cde3bb2004-06-12 02:17:14 +00001652 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001653 ** assumed that there is a SHARED or greater lock on the file
1654 ** already.
1655 */
drh308c2a52010-05-14 11:30:18 +00001656 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001657 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001658
1659 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1660 if( eFileLock==RESERVED_LOCK ){
1661 lock.l_start = RESERVED_BYTE;
1662 lock.l_len = 1L;
1663 }else{
1664 lock.l_start = SHARED_FIRST;
1665 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001666 }
dan661d71a2011-03-30 19:08:03 +00001667
1668 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001669 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001670 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001671 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001672 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001673 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001674 }
drhbbd42a62004-05-22 17:41:58 +00001675 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001676
drh8f941bc2009-01-14 23:03:40 +00001677
drhd3d8c042012-05-29 17:02:40 +00001678#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001679 /* Set up the transaction-counter change checking flags when
1680 ** transitioning from a SHARED to a RESERVED lock. The change
1681 ** from SHARED to RESERVED marks the beginning of a normal
1682 ** write operation (not a hot journal rollback).
1683 */
1684 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001685 && pFile->eFileLock<=SHARED_LOCK
1686 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001687 ){
1688 pFile->transCntrChng = 0;
1689 pFile->dbUpdate = 0;
1690 pFile->inNormalWrite = 1;
1691 }
1692#endif
1693
1694
danielk1977ecb2a962004-06-02 06:30:16 +00001695 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001696 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001697 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001698 }else if( eFileLock==EXCLUSIVE_LOCK ){
1699 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001700 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001701 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001702
1703end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001704 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001705 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1706 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001707 return rc;
1708}
1709
1710/*
dan08da86a2009-08-21 17:18:03 +00001711** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001712** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001713*/
1714static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001715 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001716 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001717 p->pNext = pInode->pUnused;
1718 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001719 pFile->h = -1;
1720 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001721}
1722
1723/*
drh308c2a52010-05-14 11:30:18 +00001724** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001725** must be either NO_LOCK or SHARED_LOCK.
1726**
1727** If the locking level of the file descriptor is already at or below
1728** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001729**
1730** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1731** the byte range is divided into 2 parts and the first part is unlocked then
1732** set to a read lock, then the other part is simply unlocked. This works
1733** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1734** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001735*/
drha7e61d82011-03-12 17:02:57 +00001736static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001737 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001738 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001739 struct flock lock;
1740 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001741
drh054889e2005-11-30 03:20:31 +00001742 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001743 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001744 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh91eb93c2015-03-03 19:56:20 +00001745 osGetpid()));
drha6abd042004-06-09 17:37:22 +00001746
drh308c2a52010-05-14 11:30:18 +00001747 assert( eFileLock<=SHARED_LOCK );
1748 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001749 return SQLITE_OK;
1750 }
drh6c7d5c52008-11-21 20:32:33 +00001751 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001752 pInode = pFile->pInode;
1753 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001754 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001755 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001756
drhd3d8c042012-05-29 17:02:40 +00001757#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001758 /* When reducing a lock such that other processes can start
1759 ** reading the database file again, make sure that the
1760 ** transaction counter was updated if any part of the database
1761 ** file changed. If the transaction counter is not updated,
1762 ** other connections to the same file might not realize that
1763 ** the file has changed and hence might not know to flush their
1764 ** cache. The use of a stale cache can lead to database corruption.
1765 */
drh8f941bc2009-01-14 23:03:40 +00001766 pFile->inNormalWrite = 0;
1767#endif
1768
drh7ed97b92010-01-20 13:07:21 +00001769 /* downgrading to a shared lock on NFS involves clearing the write lock
1770 ** before establishing the readlock - to avoid a race condition we downgrade
1771 ** the lock in 2 blocks, so that part of the range will be covered by a
1772 ** write lock until the rest is covered by a read lock:
1773 ** 1: [WWWWW]
1774 ** 2: [....W]
1775 ** 3: [RRRRW]
1776 ** 4: [RRRR.]
1777 */
drh308c2a52010-05-14 11:30:18 +00001778 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001779#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001780 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001781 assert( handleNFSUnlock==0 );
1782#endif
1783#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001784 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001785 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001786 off_t divSize = SHARED_SIZE - 1;
1787
1788 lock.l_type = F_UNLCK;
1789 lock.l_whence = SEEK_SET;
1790 lock.l_start = SHARED_FIRST;
1791 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001792 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001793 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001794 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001795 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001796 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001797 }
1798 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001799 }
drh7ed97b92010-01-20 13:07:21 +00001800 lock.l_type = F_RDLCK;
1801 lock.l_whence = SEEK_SET;
1802 lock.l_start = SHARED_FIRST;
1803 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001804 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001805 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001806 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1807 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001808 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001809 }
1810 goto end_unlock;
1811 }
1812 lock.l_type = F_UNLCK;
1813 lock.l_whence = SEEK_SET;
1814 lock.l_start = SHARED_FIRST+divSize;
1815 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001816 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001817 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001818 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001819 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001820 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001821 }
1822 goto end_unlock;
1823 }
drh30f776f2011-02-25 03:25:07 +00001824 }else
1825#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1826 {
drh7ed97b92010-01-20 13:07:21 +00001827 lock.l_type = F_RDLCK;
1828 lock.l_whence = SEEK_SET;
1829 lock.l_start = SHARED_FIRST;
1830 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001831 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001832 /* In theory, the call to unixFileLock() cannot fail because another
1833 ** process is holding an incompatible lock. If it does, this
1834 ** indicates that the other process is not following the locking
1835 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1836 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1837 ** an assert to fail). */
1838 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001839 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001840 goto end_unlock;
1841 }
drh9c105bb2004-10-02 20:38:28 +00001842 }
1843 }
drhbbd42a62004-05-22 17:41:58 +00001844 lock.l_type = F_UNLCK;
1845 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001846 lock.l_start = PENDING_BYTE;
1847 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001848 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001849 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001850 }else{
danea83bc62011-04-01 11:56:32 +00001851 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001852 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001853 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001854 }
drhbbd42a62004-05-22 17:41:58 +00001855 }
drh308c2a52010-05-14 11:30:18 +00001856 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001857 /* Decrement the shared lock counter. Release the lock using an
1858 ** OS call only when all threads in this same process have released
1859 ** the lock.
1860 */
drh8af6c222010-05-14 12:43:01 +00001861 pInode->nShared--;
1862 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001863 lock.l_type = F_UNLCK;
1864 lock.l_whence = SEEK_SET;
1865 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001866 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001867 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001868 }else{
danea83bc62011-04-01 11:56:32 +00001869 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001870 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001871 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001872 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001873 }
drha6abd042004-06-09 17:37:22 +00001874 }
1875
drhbbd42a62004-05-22 17:41:58 +00001876 /* Decrement the count of locks against this same file. When the
1877 ** count reaches zero, close any other file descriptors whose close
1878 ** was deferred because of outstanding locks.
1879 */
drh8af6c222010-05-14 12:43:01 +00001880 pInode->nLock--;
1881 assert( pInode->nLock>=0 );
1882 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001883 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001884 }
1885 }
drhf2f105d2012-08-20 15:53:54 +00001886
aswift5b1a2562008-08-22 00:22:35 +00001887end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001888 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001889 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001890 return rc;
drhbbd42a62004-05-22 17:41:58 +00001891}
1892
1893/*
drh308c2a52010-05-14 11:30:18 +00001894** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001895** must be either NO_LOCK or SHARED_LOCK.
1896**
1897** If the locking level of the file descriptor is already at or below
1898** the requested locking level, this routine is a no-op.
1899*/
drh308c2a52010-05-14 11:30:18 +00001900static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001901#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001902 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001903#endif
drha7e61d82011-03-12 17:02:57 +00001904 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001905}
1906
mistachkine98844f2013-08-24 00:59:24 +00001907#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001908static int unixMapfile(unixFile *pFd, i64 nByte);
1909static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001910#endif
danf23da962013-03-23 21:00:41 +00001911
drh7ed97b92010-01-20 13:07:21 +00001912/*
danielk1977e339d652008-06-28 11:23:00 +00001913** This function performs the parts of the "close file" operation
1914** common to all locking schemes. It closes the directory and file
1915** handles, if they are valid, and sets all fields of the unixFile
1916** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001917**
1918** It is *not* necessary to hold the mutex when this routine is called,
1919** even on VxWorks. A mutex will be acquired on VxWorks by the
1920** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001921*/
1922static int closeUnixFile(sqlite3_file *id){
1923 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001924#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001925 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001926#endif
dan661d71a2011-03-30 19:08:03 +00001927 if( pFile->h>=0 ){
1928 robust_close(pFile, pFile->h, __LINE__);
1929 pFile->h = -1;
1930 }
1931#if OS_VXWORKS
1932 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001933 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001934 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001935 }
1936 vxworksReleaseFileId(pFile->pId);
1937 pFile->pId = 0;
1938 }
1939#endif
drh0bdbc902014-06-16 18:35:06 +00001940#ifdef SQLITE_UNLINK_AFTER_CLOSE
1941 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1942 osUnlink(pFile->zPath);
1943 sqlite3_free(*(char**)&pFile->zPath);
1944 pFile->zPath = 0;
1945 }
1946#endif
dan661d71a2011-03-30 19:08:03 +00001947 OSTRACE(("CLOSE %-3d\n", pFile->h));
1948 OpenCounter(-1);
1949 sqlite3_free(pFile->pUnused);
1950 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001951 return SQLITE_OK;
1952}
1953
1954/*
danielk1977e3026632004-06-22 11:29:02 +00001955** Close a file.
1956*/
danielk197762079062007-08-15 17:08:46 +00001957static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001958 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001959 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001960 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001961 unixUnlock(id, NO_LOCK);
1962 unixEnterMutex();
1963
1964 /* unixFile.pInode is always valid here. Otherwise, a different close
1965 ** routine (e.g. nolockClose()) would be called instead.
1966 */
1967 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1968 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1969 /* If there are outstanding locks, do not actually close the file just
1970 ** yet because that would clear those locks. Instead, add the file
1971 ** descriptor to pInode->pUnused list. It will be automatically closed
1972 ** when the last lock is cleared.
1973 */
1974 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001975 }
dan661d71a2011-03-30 19:08:03 +00001976 releaseInodeInfo(pFile);
1977 rc = closeUnixFile(id);
1978 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001979 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001980}
1981
drh734c9862008-11-28 15:37:20 +00001982/************** End of the posix advisory lock implementation *****************
1983******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001984
drh734c9862008-11-28 15:37:20 +00001985/******************************************************************************
1986****************************** No-op Locking **********************************
1987**
1988** Of the various locking implementations available, this is by far the
1989** simplest: locking is ignored. No attempt is made to lock the database
1990** file for reading or writing.
1991**
1992** This locking mode is appropriate for use on read-only databases
1993** (ex: databases that are burned into CD-ROM, for example.) It can
1994** also be used if the application employs some external mechanism to
1995** prevent simultaneous access of the same database by two or more
1996** database connections. But there is a serious risk of database
1997** corruption if this locking mode is used in situations where multiple
1998** database connections are accessing the same database file at the same
1999** time and one or more of those connections are writing.
2000*/
drhbfe66312006-10-03 17:40:40 +00002001
drh734c9862008-11-28 15:37:20 +00002002static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2003 UNUSED_PARAMETER(NotUsed);
2004 *pResOut = 0;
2005 return SQLITE_OK;
2006}
drh734c9862008-11-28 15:37:20 +00002007static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2008 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2009 return SQLITE_OK;
2010}
drh734c9862008-11-28 15:37:20 +00002011static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2012 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2013 return SQLITE_OK;
2014}
2015
2016/*
drh9b35ea62008-11-29 02:20:26 +00002017** Close the file.
drh734c9862008-11-28 15:37:20 +00002018*/
2019static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002020 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002021}
2022
2023/******************* End of the no-op lock implementation *********************
2024******************************************************************************/
2025
2026/******************************************************************************
2027************************* Begin dot-file Locking ******************************
2028**
mistachkin48864df2013-03-21 21:20:32 +00002029** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002030** files (really a directory) to control access to the database. This works
2031** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002032**
2033** (1) There is zero concurrency. A single reader blocks all other
2034** connections from reading or writing the database.
2035**
2036** (2) An application crash or power loss can leave stale lock files
2037** sitting around that need to be cleared manually.
2038**
2039** Nevertheless, a dotlock is an appropriate locking mode for use if no
2040** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002041**
drh9ef6bc42011-11-04 02:24:02 +00002042** Dotfile locking works by creating a subdirectory in the same directory as
2043** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002044** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002045** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002046*/
2047
2048/*
2049** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002050** lock directory.
drh734c9862008-11-28 15:37:20 +00002051*/
2052#define DOTLOCK_SUFFIX ".lock"
2053
drh7708e972008-11-29 00:56:52 +00002054/*
2055** This routine checks if there is a RESERVED lock held on the specified
2056** file by this or any other process. If such a lock is held, set *pResOut
2057** to a non-zero value otherwise *pResOut is set to zero. The return value
2058** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2059**
2060** In dotfile locking, either a lock exists or it does not. So in this
2061** variation of CheckReservedLock(), *pResOut is set to true if any lock
2062** is held on the file and false if the file is unlocked.
2063*/
drh734c9862008-11-28 15:37:20 +00002064static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2065 int rc = SQLITE_OK;
2066 int reserved = 0;
2067 unixFile *pFile = (unixFile*)id;
2068
2069 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2070
2071 assert( pFile );
2072
2073 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002074 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002075 /* Either this connection or some other connection in the same process
2076 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002077 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002078 }else{
2079 /* The lock is held if and only if the lockfile exists */
2080 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002081 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002082 }
drh308c2a52010-05-14 11:30:18 +00002083 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002084 *pResOut = reserved;
2085 return rc;
2086}
2087
drh7708e972008-11-29 00:56:52 +00002088/*
drh308c2a52010-05-14 11:30:18 +00002089** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002090** of the following:
2091**
2092** (1) SHARED_LOCK
2093** (2) RESERVED_LOCK
2094** (3) PENDING_LOCK
2095** (4) EXCLUSIVE_LOCK
2096**
2097** Sometimes when requesting one lock state, additional lock states
2098** are inserted in between. The locking might fail on one of the later
2099** transitions leaving the lock state different from what it started but
2100** still short of its goal. The following chart shows the allowed
2101** transitions and the inserted intermediate states:
2102**
2103** UNLOCKED -> SHARED
2104** SHARED -> RESERVED
2105** SHARED -> (PENDING) -> EXCLUSIVE
2106** RESERVED -> (PENDING) -> EXCLUSIVE
2107** PENDING -> EXCLUSIVE
2108**
2109** This routine will only increase a lock. Use the sqlite3OsUnlock()
2110** routine to lower a locking level.
2111**
2112** With dotfile locking, we really only support state (4): EXCLUSIVE.
2113** But we track the other locking levels internally.
2114*/
drh308c2a52010-05-14 11:30:18 +00002115static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002116 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002117 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002118 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002119
drh7708e972008-11-29 00:56:52 +00002120
2121 /* If we have any lock, then the lock file already exists. All we have
2122 ** to do is adjust our internal record of the lock level.
2123 */
drh308c2a52010-05-14 11:30:18 +00002124 if( pFile->eFileLock > NO_LOCK ){
2125 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002126 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002127#ifdef HAVE_UTIME
2128 utime(zLockFile, NULL);
2129#else
drh734c9862008-11-28 15:37:20 +00002130 utimes(zLockFile, NULL);
2131#endif
drh7708e972008-11-29 00:56:52 +00002132 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002133 }
2134
2135 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002136 rc = osMkdir(zLockFile, 0777);
2137 if( rc<0 ){
2138 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002139 int tErrno = errno;
2140 if( EEXIST == tErrno ){
2141 rc = SQLITE_BUSY;
2142 } else {
2143 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2144 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002145 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002146 }
2147 }
drh7708e972008-11-29 00:56:52 +00002148 return rc;
drh734c9862008-11-28 15:37:20 +00002149 }
drh734c9862008-11-28 15:37:20 +00002150
2151 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002152 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002153 return rc;
2154}
2155
drh7708e972008-11-29 00:56:52 +00002156/*
drh308c2a52010-05-14 11:30:18 +00002157** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002158** must be either NO_LOCK or SHARED_LOCK.
2159**
2160** If the locking level of the file descriptor is already at or below
2161** the requested locking level, this routine is a no-op.
2162**
2163** When the locking level reaches NO_LOCK, delete the lock file.
2164*/
drh308c2a52010-05-14 11:30:18 +00002165static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002166 unixFile *pFile = (unixFile*)id;
2167 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002168 int rc;
drh734c9862008-11-28 15:37:20 +00002169
2170 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002171 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002172 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002173 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002174
2175 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002176 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002177 return SQLITE_OK;
2178 }
drh7708e972008-11-29 00:56:52 +00002179
2180 /* To downgrade to shared, simply update our internal notion of the
2181 ** lock state. No need to mess with the file on disk.
2182 */
drh308c2a52010-05-14 11:30:18 +00002183 if( eFileLock==SHARED_LOCK ){
2184 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002185 return SQLITE_OK;
2186 }
2187
drh7708e972008-11-29 00:56:52 +00002188 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002189 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002190 rc = osRmdir(zLockFile);
2191 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2192 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002193 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002194 rc = 0;
drh734c9862008-11-28 15:37:20 +00002195 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002196 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002197 }
2198 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002199 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002200 }
2201 return rc;
2202 }
drh308c2a52010-05-14 11:30:18 +00002203 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002204 return SQLITE_OK;
2205}
2206
2207/*
drh9b35ea62008-11-29 02:20:26 +00002208** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002209*/
2210static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002211 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002212 if( id ){
2213 unixFile *pFile = (unixFile*)id;
2214 dotlockUnlock(id, NO_LOCK);
2215 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002216 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002217 }
drh734c9862008-11-28 15:37:20 +00002218 return rc;
2219}
2220/****************** End of the dot-file lock implementation *******************
2221******************************************************************************/
2222
2223/******************************************************************************
2224************************** Begin flock Locking ********************************
2225**
2226** Use the flock() system call to do file locking.
2227**
drh6b9d6dd2008-12-03 19:34:47 +00002228** flock() locking is like dot-file locking in that the various
2229** fine-grain locking levels supported by SQLite are collapsed into
2230** a single exclusive lock. In other words, SHARED, RESERVED, and
2231** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2232** still works when you do this, but concurrency is reduced since
2233** only a single process can be reading the database at a time.
2234**
drh734c9862008-11-28 15:37:20 +00002235** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
2236** compiling for VXWORKS.
2237*/
2238#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh734c9862008-11-28 15:37:20 +00002239
drh6b9d6dd2008-12-03 19:34:47 +00002240/*
drhff812312011-02-23 13:33:46 +00002241** Retry flock() calls that fail with EINTR
2242*/
2243#ifdef EINTR
2244static int robust_flock(int fd, int op){
2245 int rc;
2246 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2247 return rc;
2248}
2249#else
drh5c819272011-02-23 14:00:12 +00002250# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002251#endif
2252
2253
2254/*
drh6b9d6dd2008-12-03 19:34:47 +00002255** This routine checks if there is a RESERVED lock held on the specified
2256** file by this or any other process. If such a lock is held, set *pResOut
2257** to a non-zero value otherwise *pResOut is set to zero. The return value
2258** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2259*/
drh734c9862008-11-28 15:37:20 +00002260static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2261 int rc = SQLITE_OK;
2262 int reserved = 0;
2263 unixFile *pFile = (unixFile*)id;
2264
2265 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2266
2267 assert( pFile );
2268
2269 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002270 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002271 reserved = 1;
2272 }
2273
2274 /* Otherwise see if some other process holds it. */
2275 if( !reserved ){
2276 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002277 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002278 if( !lrc ){
2279 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002280 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002281 if ( lrc ) {
2282 int tErrno = errno;
2283 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002284 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002285 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002286 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002287 rc = lrc;
2288 }
2289 }
2290 } else {
2291 int tErrno = errno;
2292 reserved = 1;
2293 /* someone else might have it reserved */
2294 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2295 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002296 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002297 rc = lrc;
2298 }
2299 }
2300 }
drh308c2a52010-05-14 11:30:18 +00002301 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002302
2303#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2304 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2305 rc = SQLITE_OK;
2306 reserved=1;
2307 }
2308#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2309 *pResOut = reserved;
2310 return rc;
2311}
2312
drh6b9d6dd2008-12-03 19:34:47 +00002313/*
drh308c2a52010-05-14 11:30:18 +00002314** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002315** of the following:
2316**
2317** (1) SHARED_LOCK
2318** (2) RESERVED_LOCK
2319** (3) PENDING_LOCK
2320** (4) EXCLUSIVE_LOCK
2321**
2322** Sometimes when requesting one lock state, additional lock states
2323** are inserted in between. The locking might fail on one of the later
2324** transitions leaving the lock state different from what it started but
2325** still short of its goal. The following chart shows the allowed
2326** transitions and the inserted intermediate states:
2327**
2328** UNLOCKED -> SHARED
2329** SHARED -> RESERVED
2330** SHARED -> (PENDING) -> EXCLUSIVE
2331** RESERVED -> (PENDING) -> EXCLUSIVE
2332** PENDING -> EXCLUSIVE
2333**
2334** flock() only really support EXCLUSIVE locks. We track intermediate
2335** lock states in the sqlite3_file structure, but all locks SHARED or
2336** above are really EXCLUSIVE locks and exclude all other processes from
2337** access the file.
2338**
2339** This routine will only increase a lock. Use the sqlite3OsUnlock()
2340** routine to lower a locking level.
2341*/
drh308c2a52010-05-14 11:30:18 +00002342static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002343 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002344 unixFile *pFile = (unixFile*)id;
2345
2346 assert( pFile );
2347
2348 /* if we already have a lock, it is exclusive.
2349 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002350 if (pFile->eFileLock > NO_LOCK) {
2351 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002352 return SQLITE_OK;
2353 }
2354
2355 /* grab an exclusive lock */
2356
drhff812312011-02-23 13:33:46 +00002357 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002358 int tErrno = errno;
2359 /* didn't get, must be busy */
2360 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2361 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002362 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002363 }
2364 } else {
2365 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002366 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002367 }
drh308c2a52010-05-14 11:30:18 +00002368 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2369 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002370#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2371 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2372 rc = SQLITE_BUSY;
2373 }
2374#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2375 return rc;
2376}
2377
drh6b9d6dd2008-12-03 19:34:47 +00002378
2379/*
drh308c2a52010-05-14 11:30:18 +00002380** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002381** must be either NO_LOCK or SHARED_LOCK.
2382**
2383** If the locking level of the file descriptor is already at or below
2384** the requested locking level, this routine is a no-op.
2385*/
drh308c2a52010-05-14 11:30:18 +00002386static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002387 unixFile *pFile = (unixFile*)id;
2388
2389 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002390 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002391 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002392 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002393
2394 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002395 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002396 return SQLITE_OK;
2397 }
2398
2399 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002400 if (eFileLock==SHARED_LOCK) {
2401 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002402 return SQLITE_OK;
2403 }
2404
2405 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002406 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002407#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002408 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002409#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002410 return SQLITE_IOERR_UNLOCK;
2411 }else{
drh308c2a52010-05-14 11:30:18 +00002412 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002413 return SQLITE_OK;
2414 }
2415}
2416
2417/*
2418** Close a file.
2419*/
2420static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002421 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002422 if( id ){
2423 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002424 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002425 }
drh5a05be12012-10-09 18:51:44 +00002426 return rc;
drh734c9862008-11-28 15:37:20 +00002427}
2428
2429#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2430
2431/******************* End of the flock lock implementation *********************
2432******************************************************************************/
2433
2434/******************************************************************************
2435************************ Begin Named Semaphore Locking ************************
2436**
2437** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002438**
2439** Semaphore locking is like dot-lock and flock in that it really only
2440** supports EXCLUSIVE locking. Only a single process can read or write
2441** the database file at a time. This reduces potential concurrency, but
2442** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002443*/
2444#if OS_VXWORKS
2445
drh6b9d6dd2008-12-03 19:34:47 +00002446/*
2447** This routine checks if there is a RESERVED lock held on the specified
2448** file by this or any other process. If such a lock is held, set *pResOut
2449** to a non-zero value otherwise *pResOut is set to zero. The return value
2450** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2451*/
drh8cd5b252015-03-02 22:06:43 +00002452static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002453 int rc = SQLITE_OK;
2454 int reserved = 0;
2455 unixFile *pFile = (unixFile*)id;
2456
2457 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2458
2459 assert( pFile );
2460
2461 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002462 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002463 reserved = 1;
2464 }
2465
2466 /* Otherwise see if some other process holds it. */
2467 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002468 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002469
2470 if( sem_trywait(pSem)==-1 ){
2471 int tErrno = errno;
2472 if( EAGAIN != tErrno ){
2473 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002474 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002475 } else {
2476 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002477 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002478 }
2479 }else{
2480 /* we could have it if we want it */
2481 sem_post(pSem);
2482 }
2483 }
drh308c2a52010-05-14 11:30:18 +00002484 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002485
2486 *pResOut = reserved;
2487 return rc;
2488}
2489
drh6b9d6dd2008-12-03 19:34:47 +00002490/*
drh308c2a52010-05-14 11:30:18 +00002491** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002492** of the following:
2493**
2494** (1) SHARED_LOCK
2495** (2) RESERVED_LOCK
2496** (3) PENDING_LOCK
2497** (4) EXCLUSIVE_LOCK
2498**
2499** Sometimes when requesting one lock state, additional lock states
2500** are inserted in between. The locking might fail on one of the later
2501** transitions leaving the lock state different from what it started but
2502** still short of its goal. The following chart shows the allowed
2503** transitions and the inserted intermediate states:
2504**
2505** UNLOCKED -> SHARED
2506** SHARED -> RESERVED
2507** SHARED -> (PENDING) -> EXCLUSIVE
2508** RESERVED -> (PENDING) -> EXCLUSIVE
2509** PENDING -> EXCLUSIVE
2510**
2511** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2512** lock states in the sqlite3_file structure, but all locks SHARED or
2513** above are really EXCLUSIVE locks and exclude all other processes from
2514** access the file.
2515**
2516** This routine will only increase a lock. Use the sqlite3OsUnlock()
2517** routine to lower a locking level.
2518*/
drh8cd5b252015-03-02 22:06:43 +00002519static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002520 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002521 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002522 int rc = SQLITE_OK;
2523
2524 /* if we already have a lock, it is exclusive.
2525 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002526 if (pFile->eFileLock > NO_LOCK) {
2527 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002528 rc = SQLITE_OK;
2529 goto sem_end_lock;
2530 }
2531
2532 /* lock semaphore now but bail out when already locked. */
2533 if( sem_trywait(pSem)==-1 ){
2534 rc = SQLITE_BUSY;
2535 goto sem_end_lock;
2536 }
2537
2538 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002539 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002540
2541 sem_end_lock:
2542 return rc;
2543}
2544
drh6b9d6dd2008-12-03 19:34:47 +00002545/*
drh308c2a52010-05-14 11:30:18 +00002546** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002547** must be either NO_LOCK or SHARED_LOCK.
2548**
2549** If the locking level of the file descriptor is already at or below
2550** the requested locking level, this routine is a no-op.
2551*/
drh8cd5b252015-03-02 22:06:43 +00002552static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002553 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002554 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002555
2556 assert( pFile );
2557 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002558 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002559 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002560 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002561
2562 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002563 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002564 return SQLITE_OK;
2565 }
2566
2567 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002568 if (eFileLock==SHARED_LOCK) {
2569 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002570 return SQLITE_OK;
2571 }
2572
2573 /* no, really unlock. */
2574 if ( sem_post(pSem)==-1 ) {
2575 int rc, tErrno = errno;
2576 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2577 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002578 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002579 }
2580 return rc;
2581 }
drh308c2a52010-05-14 11:30:18 +00002582 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002583 return SQLITE_OK;
2584}
2585
2586/*
2587 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002588 */
drh8cd5b252015-03-02 22:06:43 +00002589static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002590 if( id ){
2591 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002592 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002593 assert( pFile );
2594 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002595 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002596 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002597 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002598 }
2599 return SQLITE_OK;
2600}
2601
2602#endif /* OS_VXWORKS */
2603/*
2604** Named semaphore locking is only available on VxWorks.
2605**
2606*************** End of the named semaphore lock implementation ****************
2607******************************************************************************/
2608
2609
2610/******************************************************************************
2611*************************** Begin AFP Locking *********************************
2612**
2613** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2614** on Apple Macintosh computers - both OS9 and OSX.
2615**
2616** Third-party implementations of AFP are available. But this code here
2617** only works on OSX.
2618*/
2619
drhd2cb50b2009-01-09 21:41:17 +00002620#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002621/*
2622** The afpLockingContext structure contains all afp lock specific state
2623*/
drhbfe66312006-10-03 17:40:40 +00002624typedef struct afpLockingContext afpLockingContext;
2625struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002626 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002627 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002628};
2629
2630struct ByteRangeLockPB2
2631{
2632 unsigned long long offset; /* offset to first byte to lock */
2633 unsigned long long length; /* nbr of bytes to lock */
2634 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2635 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2636 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2637 int fd; /* file desc to assoc this lock with */
2638};
2639
drhfd131da2007-08-07 17:13:03 +00002640#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002641
drh6b9d6dd2008-12-03 19:34:47 +00002642/*
2643** This is a utility for setting or clearing a bit-range lock on an
2644** AFP filesystem.
2645**
2646** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2647*/
2648static int afpSetLock(
2649 const char *path, /* Name of the file to be locked or unlocked */
2650 unixFile *pFile, /* Open file descriptor on path */
2651 unsigned long long offset, /* First byte to be locked */
2652 unsigned long long length, /* Number of bytes to lock */
2653 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002654){
drh6b9d6dd2008-12-03 19:34:47 +00002655 struct ByteRangeLockPB2 pb;
2656 int err;
drhbfe66312006-10-03 17:40:40 +00002657
2658 pb.unLockFlag = setLockFlag ? 0 : 1;
2659 pb.startEndFlag = 0;
2660 pb.offset = offset;
2661 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002662 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002663
drh308c2a52010-05-14 11:30:18 +00002664 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002665 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002666 offset, length));
drhbfe66312006-10-03 17:40:40 +00002667 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2668 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002669 int rc;
2670 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002671 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2672 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002673#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2674 rc = SQLITE_BUSY;
2675#else
drh734c9862008-11-28 15:37:20 +00002676 rc = sqliteErrorFromPosixError(tErrno,
2677 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002678#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002679 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002680 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002681 }
2682 return rc;
drhbfe66312006-10-03 17:40:40 +00002683 } else {
aswift5b1a2562008-08-22 00:22:35 +00002684 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002685 }
2686}
2687
drh6b9d6dd2008-12-03 19:34:47 +00002688/*
2689** This routine checks if there is a RESERVED lock held on the specified
2690** file by this or any other process. If such a lock is held, set *pResOut
2691** to a non-zero value otherwise *pResOut is set to zero. The return value
2692** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2693*/
danielk1977e339d652008-06-28 11:23:00 +00002694static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002695 int rc = SQLITE_OK;
2696 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002697 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002698 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002699
aswift5b1a2562008-08-22 00:22:35 +00002700 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2701
2702 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002703 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002704 if( context->reserved ){
2705 *pResOut = 1;
2706 return SQLITE_OK;
2707 }
drh8af6c222010-05-14 12:43:01 +00002708 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002709
2710 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002711 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002712 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002713 }
2714
2715 /* Otherwise see if some other process holds it.
2716 */
aswift5b1a2562008-08-22 00:22:35 +00002717 if( !reserved ){
2718 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002719 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002720 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002721 /* if we succeeded in taking the reserved lock, unlock it to restore
2722 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002723 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002724 } else {
2725 /* if we failed to get the lock then someone else must have it */
2726 reserved = 1;
2727 }
2728 if( IS_LOCK_ERROR(lrc) ){
2729 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002730 }
2731 }
drhbfe66312006-10-03 17:40:40 +00002732
drh7ed97b92010-01-20 13:07:21 +00002733 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002734 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002735
2736 *pResOut = reserved;
2737 return rc;
drhbfe66312006-10-03 17:40:40 +00002738}
2739
drh6b9d6dd2008-12-03 19:34:47 +00002740/*
drh308c2a52010-05-14 11:30:18 +00002741** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002742** of the following:
2743**
2744** (1) SHARED_LOCK
2745** (2) RESERVED_LOCK
2746** (3) PENDING_LOCK
2747** (4) EXCLUSIVE_LOCK
2748**
2749** Sometimes when requesting one lock state, additional lock states
2750** are inserted in between. The locking might fail on one of the later
2751** transitions leaving the lock state different from what it started but
2752** still short of its goal. The following chart shows the allowed
2753** transitions and the inserted intermediate states:
2754**
2755** UNLOCKED -> SHARED
2756** SHARED -> RESERVED
2757** SHARED -> (PENDING) -> EXCLUSIVE
2758** RESERVED -> (PENDING) -> EXCLUSIVE
2759** PENDING -> EXCLUSIVE
2760**
2761** This routine will only increase a lock. Use the sqlite3OsUnlock()
2762** routine to lower a locking level.
2763*/
drh308c2a52010-05-14 11:30:18 +00002764static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002765 int rc = SQLITE_OK;
2766 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002767 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002768 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002769
2770 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002771 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2772 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00002773 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid()));
drh339eb0b2008-03-07 15:34:11 +00002774
drhbfe66312006-10-03 17:40:40 +00002775 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002776 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002777 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002778 */
drh308c2a52010-05-14 11:30:18 +00002779 if( pFile->eFileLock>=eFileLock ){
2780 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2781 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002782 return SQLITE_OK;
2783 }
2784
2785 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002786 ** (1) We never move from unlocked to anything higher than shared lock.
2787 ** (2) SQLite never explicitly requests a pendig lock.
2788 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002789 */
drh308c2a52010-05-14 11:30:18 +00002790 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2791 assert( eFileLock!=PENDING_LOCK );
2792 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002793
drh8af6c222010-05-14 12:43:01 +00002794 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002795 */
drh6c7d5c52008-11-21 20:32:33 +00002796 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002797 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002798
2799 /* If some thread using this PID has a lock via a different unixFile*
2800 ** handle that precludes the requested lock, return BUSY.
2801 */
drh8af6c222010-05-14 12:43:01 +00002802 if( (pFile->eFileLock!=pInode->eFileLock &&
2803 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002804 ){
2805 rc = SQLITE_BUSY;
2806 goto afp_end_lock;
2807 }
2808
2809 /* If a SHARED lock is requested, and some thread using this PID already
2810 ** has a SHARED or RESERVED lock, then increment reference counts and
2811 ** return SQLITE_OK.
2812 */
drh308c2a52010-05-14 11:30:18 +00002813 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002814 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002815 assert( eFileLock==SHARED_LOCK );
2816 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002817 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002818 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002819 pInode->nShared++;
2820 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002821 goto afp_end_lock;
2822 }
drhbfe66312006-10-03 17:40:40 +00002823
2824 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002825 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2826 ** be released.
2827 */
drh308c2a52010-05-14 11:30:18 +00002828 if( eFileLock==SHARED_LOCK
2829 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002830 ){
2831 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002832 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002833 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002834 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002835 goto afp_end_lock;
2836 }
2837 }
2838
2839 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002840 ** operating system calls for the specified lock.
2841 */
drh308c2a52010-05-14 11:30:18 +00002842 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002843 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002844 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002845
drh8af6c222010-05-14 12:43:01 +00002846 assert( pInode->nShared==0 );
2847 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002848
2849 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002850 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002851 /* note that the quality of the randomness doesn't matter that much */
2852 lk = random();
drh8af6c222010-05-14 12:43:01 +00002853 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002854 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002855 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002856 if( IS_LOCK_ERROR(lrc1) ){
2857 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002858 }
aswift5b1a2562008-08-22 00:22:35 +00002859 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002860 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002861
aswift5b1a2562008-08-22 00:22:35 +00002862 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002863 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002864 rc = lrc1;
2865 goto afp_end_lock;
2866 } else if( IS_LOCK_ERROR(lrc2) ){
2867 rc = lrc2;
2868 goto afp_end_lock;
2869 } else if( lrc1 != SQLITE_OK ) {
2870 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002871 } else {
drh308c2a52010-05-14 11:30:18 +00002872 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002873 pInode->nLock++;
2874 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002875 }
drh8af6c222010-05-14 12:43:01 +00002876 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002877 /* We are trying for an exclusive lock but another thread in this
2878 ** same process is still holding a shared lock. */
2879 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002880 }else{
2881 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2882 ** assumed that there is a SHARED or greater lock on the file
2883 ** already.
2884 */
2885 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002886 assert( 0!=pFile->eFileLock );
2887 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002888 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002889 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002890 if( !failed ){
2891 context->reserved = 1;
2892 }
drhbfe66312006-10-03 17:40:40 +00002893 }
drh308c2a52010-05-14 11:30:18 +00002894 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002895 /* Acquire an EXCLUSIVE lock */
2896
2897 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002898 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002899 */
drh6b9d6dd2008-12-03 19:34:47 +00002900 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002901 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002902 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002903 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002904 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002905 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002906 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002907 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002908 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2909 ** a critical I/O error
2910 */
2911 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2912 SQLITE_IOERR_LOCK;
2913 goto afp_end_lock;
2914 }
2915 }else{
aswift5b1a2562008-08-22 00:22:35 +00002916 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002917 }
2918 }
aswift5b1a2562008-08-22 00:22:35 +00002919 if( failed ){
2920 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002921 }
2922 }
2923
2924 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002925 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002926 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002927 }else if( eFileLock==EXCLUSIVE_LOCK ){
2928 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002929 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002930 }
2931
2932afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002933 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002934 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2935 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002936 return rc;
2937}
2938
2939/*
drh308c2a52010-05-14 11:30:18 +00002940** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002941** must be either NO_LOCK or SHARED_LOCK.
2942**
2943** If the locking level of the file descriptor is already at or below
2944** the requested locking level, this routine is a no-op.
2945*/
drh308c2a52010-05-14 11:30:18 +00002946static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002947 int rc = SQLITE_OK;
2948 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002949 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002950 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2951 int skipShared = 0;
2952#ifdef SQLITE_TEST
2953 int h = pFile->h;
2954#endif
drhbfe66312006-10-03 17:40:40 +00002955
2956 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002957 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002958 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh91eb93c2015-03-03 19:56:20 +00002959 osGetpid()));
aswift5b1a2562008-08-22 00:22:35 +00002960
drh308c2a52010-05-14 11:30:18 +00002961 assert( eFileLock<=SHARED_LOCK );
2962 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002963 return SQLITE_OK;
2964 }
drh6c7d5c52008-11-21 20:32:33 +00002965 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002966 pInode = pFile->pInode;
2967 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002968 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002969 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002970 SimulateIOErrorBenign(1);
2971 SimulateIOError( h=(-1) )
2972 SimulateIOErrorBenign(0);
2973
drhd3d8c042012-05-29 17:02:40 +00002974#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002975 /* When reducing a lock such that other processes can start
2976 ** reading the database file again, make sure that the
2977 ** transaction counter was updated if any part of the database
2978 ** file changed. If the transaction counter is not updated,
2979 ** other connections to the same file might not realize that
2980 ** the file has changed and hence might not know to flush their
2981 ** cache. The use of a stale cache can lead to database corruption.
2982 */
2983 assert( pFile->inNormalWrite==0
2984 || pFile->dbUpdate==0
2985 || pFile->transCntrChng==1 );
2986 pFile->inNormalWrite = 0;
2987#endif
aswiftaebf4132008-11-21 00:10:35 +00002988
drh308c2a52010-05-14 11:30:18 +00002989 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002990 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002991 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002992 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002993 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002994 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2995 } else {
2996 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002997 }
2998 }
drh308c2a52010-05-14 11:30:18 +00002999 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003000 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003001 }
drh308c2a52010-05-14 11:30:18 +00003002 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003003 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3004 if( !rc ){
3005 context->reserved = 0;
3006 }
aswiftaebf4132008-11-21 00:10:35 +00003007 }
drh8af6c222010-05-14 12:43:01 +00003008 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3009 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003010 }
aswiftaebf4132008-11-21 00:10:35 +00003011 }
drh308c2a52010-05-14 11:30:18 +00003012 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003013
drh7ed97b92010-01-20 13:07:21 +00003014 /* Decrement the shared lock counter. Release the lock using an
3015 ** OS call only when all threads in this same process have released
3016 ** the lock.
3017 */
drh8af6c222010-05-14 12:43:01 +00003018 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3019 pInode->nShared--;
3020 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003021 SimulateIOErrorBenign(1);
3022 SimulateIOError( h=(-1) )
3023 SimulateIOErrorBenign(0);
3024 if( !skipShared ){
3025 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3026 }
3027 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003028 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003029 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003030 }
3031 }
3032 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003033 pInode->nLock--;
3034 assert( pInode->nLock>=0 );
3035 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003036 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003037 }
3038 }
drhbfe66312006-10-03 17:40:40 +00003039 }
drh7ed97b92010-01-20 13:07:21 +00003040
drh6c7d5c52008-11-21 20:32:33 +00003041 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003042 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003043 return rc;
3044}
3045
3046/*
drh339eb0b2008-03-07 15:34:11 +00003047** Close a file & cleanup AFP specific locking context
3048*/
danielk1977e339d652008-06-28 11:23:00 +00003049static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003050 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003051 if( id ){
3052 unixFile *pFile = (unixFile*)id;
3053 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003054 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003055 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003056 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003057 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003058 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003059 ** the last lock is cleared.
3060 */
dan08da86a2009-08-21 17:18:03 +00003061 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003062 }
danb0ac3e32010-06-16 10:55:42 +00003063 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003064 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003065 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003066 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003067 }
drh7ed97b92010-01-20 13:07:21 +00003068 return rc;
drhbfe66312006-10-03 17:40:40 +00003069}
3070
drhd2cb50b2009-01-09 21:41:17 +00003071#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003072/*
3073** The code above is the AFP lock implementation. The code is specific
3074** to MacOSX and does not work on other unix platforms. No alternative
3075** is available. If you don't compile for a mac, then the "unix-afp"
3076** VFS is not available.
3077**
3078********************* End of the AFP lock implementation **********************
3079******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003080
drh7ed97b92010-01-20 13:07:21 +00003081/******************************************************************************
3082*************************** Begin NFS Locking ********************************/
3083
3084#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3085/*
drh308c2a52010-05-14 11:30:18 +00003086 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003087 ** must be either NO_LOCK or SHARED_LOCK.
3088 **
3089 ** If the locking level of the file descriptor is already at or below
3090 ** the requested locking level, this routine is a no-op.
3091 */
drh308c2a52010-05-14 11:30:18 +00003092static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003093 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003094}
3095
3096#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3097/*
3098** The code above is the NFS lock implementation. The code is specific
3099** to MacOSX and does not work on other unix platforms. No alternative
3100** is available.
3101**
3102********************* End of the NFS lock implementation **********************
3103******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003104
3105/******************************************************************************
3106**************** Non-locking sqlite3_file methods *****************************
3107**
3108** The next division contains implementations for all methods of the
3109** sqlite3_file object other than the locking methods. The locking
3110** methods were defined in divisions above (one locking method per
3111** division). Those methods that are common to all locking modes
3112** are gather together into this division.
3113*/
drhbfe66312006-10-03 17:40:40 +00003114
3115/*
drh734c9862008-11-28 15:37:20 +00003116** Seek to the offset passed as the second argument, then read cnt
3117** bytes into pBuf. Return the number of bytes actually read.
3118**
3119** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3120** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3121** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003122** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003123** See tickets #2741 and #2681.
3124**
3125** To avoid stomping the errno value on a failed read the lastErrno value
3126** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003127*/
drh734c9862008-11-28 15:37:20 +00003128static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3129 int got;
drh58024642011-11-07 18:16:00 +00003130 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003131#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003132 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003133#endif
drh734c9862008-11-28 15:37:20 +00003134 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003135 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003136 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003137 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003138 do{
drh734c9862008-11-28 15:37:20 +00003139#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003140 got = osPread(id->h, pBuf, cnt, offset);
3141 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003142#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003143 got = osPread64(id->h, pBuf, cnt, offset);
3144 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003145#else
drh58024642011-11-07 18:16:00 +00003146 newOffset = lseek(id->h, offset, SEEK_SET);
3147 SimulateIOError( newOffset-- );
3148 if( newOffset!=offset ){
3149 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003150 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003151 }else{
drh4bf66fd2015-02-19 02:43:02 +00003152 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003153 }
3154 return -1;
drh734c9862008-11-28 15:37:20 +00003155 }
drh58024642011-11-07 18:16:00 +00003156 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003157#endif
drh58024642011-11-07 18:16:00 +00003158 if( got==cnt ) break;
3159 if( got<0 ){
3160 if( errno==EINTR ){ got = 1; continue; }
3161 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003162 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003163 break;
3164 }else if( got>0 ){
3165 cnt -= got;
3166 offset += got;
3167 prior += got;
3168 pBuf = (void*)(got + (char*)pBuf);
3169 }
3170 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003171 TIMER_END;
drh58024642011-11-07 18:16:00 +00003172 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3173 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3174 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003175}
3176
3177/*
drh734c9862008-11-28 15:37:20 +00003178** Read data from a file into a buffer. Return SQLITE_OK if all
3179** bytes were read successfully and SQLITE_IOERR if anything goes
3180** wrong.
drh339eb0b2008-03-07 15:34:11 +00003181*/
drh734c9862008-11-28 15:37:20 +00003182static int unixRead(
3183 sqlite3_file *id,
3184 void *pBuf,
3185 int amt,
3186 sqlite3_int64 offset
3187){
dan08da86a2009-08-21 17:18:03 +00003188 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003189 int got;
3190 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003191 assert( offset>=0 );
3192 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003193
dan08da86a2009-08-21 17:18:03 +00003194 /* If this is a database file (not a journal, master-journal or temp
3195 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003196#if 0
dane946c392009-08-22 11:39:46 +00003197 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003198 || offset>=PENDING_BYTE+512
3199 || offset+amt<=PENDING_BYTE
3200 );
dan7c246102010-04-12 19:00:29 +00003201#endif
drh08c6d442009-02-09 17:34:07 +00003202
drh9b4c59f2013-04-15 17:03:42 +00003203#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003204 /* Deal with as much of this read request as possible by transfering
3205 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003206 if( offset<pFile->mmapSize ){
3207 if( offset+amt <= pFile->mmapSize ){
3208 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3209 return SQLITE_OK;
3210 }else{
3211 int nCopy = pFile->mmapSize - offset;
3212 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3213 pBuf = &((u8 *)pBuf)[nCopy];
3214 amt -= nCopy;
3215 offset += nCopy;
3216 }
3217 }
drh6e0b6d52013-04-09 16:19:20 +00003218#endif
danf23da962013-03-23 21:00:41 +00003219
dan08da86a2009-08-21 17:18:03 +00003220 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003221 if( got==amt ){
3222 return SQLITE_OK;
3223 }else if( got<0 ){
3224 /* lastErrno set by seekAndRead */
3225 return SQLITE_IOERR_READ;
3226 }else{
drh4bf66fd2015-02-19 02:43:02 +00003227 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003228 /* Unread parts of the buffer must be zero-filled */
3229 memset(&((char*)pBuf)[got], 0, amt-got);
3230 return SQLITE_IOERR_SHORT_READ;
3231 }
3232}
3233
3234/*
dan47a2b4a2013-04-26 16:09:29 +00003235** Attempt to seek the file-descriptor passed as the first argument to
3236** absolute offset iOff, then attempt to write nBuf bytes of data from
3237** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3238** return the actual number of bytes written (which may be less than
3239** nBuf).
3240*/
3241static int seekAndWriteFd(
3242 int fd, /* File descriptor to write to */
3243 i64 iOff, /* File offset to begin writing at */
3244 const void *pBuf, /* Copy data from this buffer to the file */
3245 int nBuf, /* Size of buffer pBuf in bytes */
3246 int *piErrno /* OUT: Error number if error occurs */
3247){
3248 int rc = 0; /* Value returned by system call */
3249
3250 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003251 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003252 nBuf &= 0x1ffff;
3253 TIMER_START;
3254
3255#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003256 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003257#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003258 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003259#else
3260 do{
3261 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3262 SimulateIOError( iSeek-- );
3263
3264 if( iSeek!=iOff ){
3265 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3266 return -1;
3267 }
3268 rc = osWrite(fd, pBuf, nBuf);
3269 }while( rc<0 && errno==EINTR );
3270#endif
3271
3272 TIMER_END;
3273 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3274
3275 if( rc<0 && piErrno ) *piErrno = errno;
3276 return rc;
3277}
3278
3279
3280/*
drh734c9862008-11-28 15:37:20 +00003281** Seek to the offset in id->offset then read cnt bytes into pBuf.
3282** Return the number of bytes actually read. Update the offset.
3283**
3284** To avoid stomping the errno value on a failed write the lastErrno value
3285** is set before returning.
3286*/
3287static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003288 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003289}
3290
3291
3292/*
3293** Write data from a buffer into a file. Return SQLITE_OK on success
3294** or some other error code on failure.
3295*/
3296static int unixWrite(
3297 sqlite3_file *id,
3298 const void *pBuf,
3299 int amt,
3300 sqlite3_int64 offset
3301){
dan08da86a2009-08-21 17:18:03 +00003302 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003303 int wrote = 0;
3304 assert( id );
3305 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003306
dan08da86a2009-08-21 17:18:03 +00003307 /* If this is a database file (not a journal, master-journal or temp
3308 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003309#if 0
dane946c392009-08-22 11:39:46 +00003310 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003311 || offset>=PENDING_BYTE+512
3312 || offset+amt<=PENDING_BYTE
3313 );
dan7c246102010-04-12 19:00:29 +00003314#endif
drh08c6d442009-02-09 17:34:07 +00003315
drhd3d8c042012-05-29 17:02:40 +00003316#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003317 /* If we are doing a normal write to a database file (as opposed to
3318 ** doing a hot-journal rollback or a write to some file other than a
3319 ** normal database file) then record the fact that the database
3320 ** has changed. If the transaction counter is modified, record that
3321 ** fact too.
3322 */
dan08da86a2009-08-21 17:18:03 +00003323 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003324 pFile->dbUpdate = 1; /* The database has been modified */
3325 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003326 int rc;
drh8f941bc2009-01-14 23:03:40 +00003327 char oldCntr[4];
3328 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003329 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003330 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003331 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003332 pFile->transCntrChng = 1; /* The transaction counter has changed */
3333 }
3334 }
3335 }
3336#endif
3337
drh9b4c59f2013-04-15 17:03:42 +00003338#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003339 /* Deal with as much of this write request as possible by transfering
3340 ** data from the memory mapping using memcpy(). */
3341 if( offset<pFile->mmapSize ){
3342 if( offset+amt <= pFile->mmapSize ){
3343 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3344 return SQLITE_OK;
3345 }else{
3346 int nCopy = pFile->mmapSize - offset;
3347 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3348 pBuf = &((u8 *)pBuf)[nCopy];
3349 amt -= nCopy;
3350 offset += nCopy;
3351 }
3352 }
drh6e0b6d52013-04-09 16:19:20 +00003353#endif
danf23da962013-03-23 21:00:41 +00003354
dan08da86a2009-08-21 17:18:03 +00003355 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003356 amt -= wrote;
3357 offset += wrote;
3358 pBuf = &((char*)pBuf)[wrote];
3359 }
3360 SimulateIOError(( wrote=(-1), amt=1 ));
3361 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003362
drh734c9862008-11-28 15:37:20 +00003363 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003364 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003365 /* lastErrno set by seekAndWrite */
3366 return SQLITE_IOERR_WRITE;
3367 }else{
drh4bf66fd2015-02-19 02:43:02 +00003368 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003369 return SQLITE_FULL;
3370 }
3371 }
dan6e09d692010-07-27 18:34:15 +00003372
drh734c9862008-11-28 15:37:20 +00003373 return SQLITE_OK;
3374}
3375
3376#ifdef SQLITE_TEST
3377/*
3378** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003379** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003380*/
3381int sqlite3_sync_count = 0;
3382int sqlite3_fullsync_count = 0;
3383#endif
3384
3385/*
drh89240432009-03-25 01:06:01 +00003386** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003387** Others do no. To be safe, we will stick with the (slightly slower)
3388** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003389** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003390*/
drhf7a4a1b2015-01-10 18:02:45 +00003391#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003392# define fdatasync fsync
3393#endif
3394
3395/*
3396** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3397** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3398** only available on Mac OS X. But that could change.
3399*/
3400#ifdef F_FULLFSYNC
3401# define HAVE_FULLFSYNC 1
3402#else
3403# define HAVE_FULLFSYNC 0
3404#endif
3405
3406
3407/*
3408** The fsync() system call does not work as advertised on many
3409** unix systems. The following procedure is an attempt to make
3410** it work better.
3411**
3412** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3413** for testing when we want to run through the test suite quickly.
3414** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3415** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3416** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003417**
3418** SQLite sets the dataOnly flag if the size of the file is unchanged.
3419** The idea behind dataOnly is that it should only write the file content
3420** to disk, not the inode. We only set dataOnly if the file size is
3421** unchanged since the file size is part of the inode. However,
3422** Ted Ts'o tells us that fdatasync() will also write the inode if the
3423** file size has changed. The only real difference between fdatasync()
3424** and fsync(), Ted tells us, is that fdatasync() will not flush the
3425** inode if the mtime or owner or other inode attributes have changed.
3426** We only care about the file size, not the other file attributes, so
3427** as far as SQLite is concerned, an fdatasync() is always adequate.
3428** So, we always use fdatasync() if it is available, regardless of
3429** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003430*/
3431static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003432 int rc;
drh734c9862008-11-28 15:37:20 +00003433
3434 /* The following "ifdef/elif/else/" block has the same structure as
3435 ** the one below. It is replicated here solely to avoid cluttering
3436 ** up the real code with the UNUSED_PARAMETER() macros.
3437 */
3438#ifdef SQLITE_NO_SYNC
3439 UNUSED_PARAMETER(fd);
3440 UNUSED_PARAMETER(fullSync);
3441 UNUSED_PARAMETER(dataOnly);
3442#elif HAVE_FULLFSYNC
3443 UNUSED_PARAMETER(dataOnly);
3444#else
3445 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003446 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003447#endif
3448
3449 /* Record the number of times that we do a normal fsync() and
3450 ** FULLSYNC. This is used during testing to verify that this procedure
3451 ** gets called with the correct arguments.
3452 */
3453#ifdef SQLITE_TEST
3454 if( fullSync ) sqlite3_fullsync_count++;
3455 sqlite3_sync_count++;
3456#endif
3457
3458 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3459 ** no-op
3460 */
3461#ifdef SQLITE_NO_SYNC
3462 rc = SQLITE_OK;
3463#elif HAVE_FULLFSYNC
3464 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003465 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003466 }else{
3467 rc = 1;
3468 }
3469 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003470 ** It shouldn't be possible for fullfsync to fail on the local
3471 ** file system (on OSX), so failure indicates that FULLFSYNC
3472 ** isn't supported for this file system. So, attempt an fsync
3473 ** and (for now) ignore the overhead of a superfluous fcntl call.
3474 ** It'd be better to detect fullfsync support once and avoid
3475 ** the fcntl call every time sync is called.
3476 */
drh734c9862008-11-28 15:37:20 +00003477 if( rc ) rc = fsync(fd);
3478
drh7ed97b92010-01-20 13:07:21 +00003479#elif defined(__APPLE__)
3480 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3481 ** so currently we default to the macro that redefines fdatasync to fsync
3482 */
3483 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003484#else
drh0b647ff2009-03-21 14:41:04 +00003485 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003486#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003487 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003488 rc = fsync(fd);
3489 }
drh0b647ff2009-03-21 14:41:04 +00003490#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003491#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3492
3493 if( OS_VXWORKS && rc!= -1 ){
3494 rc = 0;
3495 }
chw97185482008-11-17 08:05:31 +00003496 return rc;
drhbfe66312006-10-03 17:40:40 +00003497}
3498
drh734c9862008-11-28 15:37:20 +00003499/*
drh0059eae2011-08-08 23:48:40 +00003500** Open a file descriptor to the directory containing file zFilename.
3501** If successful, *pFd is set to the opened file descriptor and
3502** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3503** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3504** value.
3505**
drh90315a22011-08-10 01:52:12 +00003506** The directory file descriptor is used for only one thing - to
3507** fsync() a directory to make sure file creation and deletion events
3508** are flushed to disk. Such fsyncs are not needed on newer
3509** journaling filesystems, but are required on older filesystems.
3510**
3511** This routine can be overridden using the xSetSysCall interface.
3512** The ability to override this routine was added in support of the
3513** chromium sandbox. Opening a directory is a security risk (we are
3514** told) so making it overrideable allows the chromium sandbox to
3515** replace this routine with a harmless no-op. To make this routine
3516** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3517** *pFd set to a negative number.
3518**
drh0059eae2011-08-08 23:48:40 +00003519** If SQLITE_OK is returned, the caller is responsible for closing
3520** the file descriptor *pFd using close().
3521*/
3522static int openDirectory(const char *zFilename, int *pFd){
3523 int ii;
3524 int fd = -1;
3525 char zDirname[MAX_PATHNAME+1];
3526
3527 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3528 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3529 if( ii>0 ){
3530 zDirname[ii] = '\0';
3531 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3532 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003533 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3534 }
3535 }
3536 *pFd = fd;
3537 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3538}
3539
3540/*
drh734c9862008-11-28 15:37:20 +00003541** Make sure all writes to a particular file are committed to disk.
3542**
3543** If dataOnly==0 then both the file itself and its metadata (file
3544** size, access time, etc) are synced. If dataOnly!=0 then only the
3545** file data is synced.
3546**
3547** Under Unix, also make sure that the directory entry for the file
3548** has been created by fsync-ing the directory that contains the file.
3549** If we do not do this and we encounter a power failure, the directory
3550** entry for the journal might not exist after we reboot. The next
3551** SQLite to access the file will not know that the journal exists (because
3552** the directory entry for the journal was never created) and the transaction
3553** will not roll back - possibly leading to database corruption.
3554*/
3555static int unixSync(sqlite3_file *id, int flags){
3556 int rc;
3557 unixFile *pFile = (unixFile*)id;
3558
3559 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3560 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3561
3562 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3563 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3564 || (flags&0x0F)==SQLITE_SYNC_FULL
3565 );
3566
3567 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3568 ** line is to test that doing so does not cause any problems.
3569 */
3570 SimulateDiskfullError( return SQLITE_FULL );
3571
3572 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003573 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003574 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3575 SimulateIOError( rc=1 );
3576 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003577 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003578 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003579 }
drh0059eae2011-08-08 23:48:40 +00003580
3581 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003582 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003583 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003584 */
3585 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3586 int dirfd;
3587 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003588 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003589 rc = osOpenDirectory(pFile->zPath, &dirfd);
3590 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003591 full_fsync(dirfd, 0, 0);
3592 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003593 }else if( rc==SQLITE_CANTOPEN ){
3594 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003595 }
drh0059eae2011-08-08 23:48:40 +00003596 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003597 }
3598 return rc;
3599}
3600
3601/*
3602** Truncate an open file to a specified size
3603*/
3604static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003605 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003606 int rc;
dan6e09d692010-07-27 18:34:15 +00003607 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003608 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003609
3610 /* If the user has configured a chunk-size for this file, truncate the
3611 ** file so that it consists of an integer number of chunks (i.e. the
3612 ** actual file size after the operation may be larger than the requested
3613 ** size).
3614 */
drhb8af4b72012-04-05 20:04:39 +00003615 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003616 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3617 }
3618
dan2ee53412014-09-06 16:49:40 +00003619 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003620 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003621 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003622 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003623 }else{
drhd3d8c042012-05-29 17:02:40 +00003624#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003625 /* If we are doing a normal write to a database file (as opposed to
3626 ** doing a hot-journal rollback or a write to some file other than a
3627 ** normal database file) and we truncate the file to zero length,
3628 ** that effectively updates the change counter. This might happen
3629 ** when restoring a database using the backup API from a zero-length
3630 ** source.
3631 */
dan6e09d692010-07-27 18:34:15 +00003632 if( pFile->inNormalWrite && nByte==0 ){
3633 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003634 }
danf23da962013-03-23 21:00:41 +00003635#endif
danc0003312013-03-22 17:46:11 +00003636
mistachkine98844f2013-08-24 00:59:24 +00003637#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003638 /* If the file was just truncated to a size smaller than the currently
3639 ** mapped region, reduce the effective mapping size as well. SQLite will
3640 ** use read() and write() to access data beyond this point from now on.
3641 */
3642 if( nByte<pFile->mmapSize ){
3643 pFile->mmapSize = nByte;
3644 }
mistachkine98844f2013-08-24 00:59:24 +00003645#endif
drh3313b142009-11-06 04:13:18 +00003646
drh734c9862008-11-28 15:37:20 +00003647 return SQLITE_OK;
3648 }
3649}
3650
3651/*
3652** Determine the current size of a file in bytes
3653*/
3654static int unixFileSize(sqlite3_file *id, i64 *pSize){
3655 int rc;
3656 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003657 assert( id );
3658 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003659 SimulateIOError( rc=1 );
3660 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003661 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003662 return SQLITE_IOERR_FSTAT;
3663 }
3664 *pSize = buf.st_size;
3665
drh8af6c222010-05-14 12:43:01 +00003666 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003667 ** writes a single byte into that file in order to work around a bug
3668 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3669 ** layers, we need to report this file size as zero even though it is
3670 ** really 1. Ticket #3260.
3671 */
3672 if( *pSize==1 ) *pSize = 0;
3673
3674
3675 return SQLITE_OK;
3676}
3677
drhd2cb50b2009-01-09 21:41:17 +00003678#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003679/*
3680** Handler for proxy-locking file-control verbs. Defined below in the
3681** proxying locking division.
3682*/
3683static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003684#endif
drh715ff302008-12-03 22:32:44 +00003685
dan502019c2010-07-28 14:26:17 +00003686/*
3687** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003688** file-control operation. Enlarge the database to nBytes in size
3689** (rounded up to the next chunk-size). If the database is already
3690** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003691*/
3692static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003693 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003694 i64 nSize; /* Required file size */
3695 struct stat buf; /* Used to hold return values of fstat() */
3696
drh4bf66fd2015-02-19 02:43:02 +00003697 if( osFstat(pFile->h, &buf) ){
3698 return SQLITE_IOERR_FSTAT;
3699 }
dan502019c2010-07-28 14:26:17 +00003700
3701 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3702 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003703
dan502019c2010-07-28 14:26:17 +00003704#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003705 /* The code below is handling the return value of osFallocate()
3706 ** correctly. posix_fallocate() is defined to "returns zero on success,
3707 ** or an error number on failure". See the manpage for details. */
3708 int err;
drhff812312011-02-23 13:33:46 +00003709 do{
dan661d71a2011-03-30 19:08:03 +00003710 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3711 }while( err==EINTR );
3712 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003713#else
dan592bf7f2014-12-30 19:58:31 +00003714 /* If the OS does not have posix_fallocate(), fake it. Write a
3715 ** single byte to the last byte in each block that falls entirely
3716 ** within the extended region. Then, if required, a single byte
3717 ** at offset (nSize-1), to set the size of the file correctly.
3718 ** This is a similar technique to that used by glibc on systems
3719 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003720 */
3721 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003722 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003723 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003724
dan502019c2010-07-28 14:26:17 +00003725 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003726 assert( iWrite>=buf.st_size );
3727 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3728 assert( ((iWrite+1)%nBlk)==0 );
3729 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003730 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003731 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003732 }
danef3d66c2015-01-06 21:31:47 +00003733 if( nWrite==0 || (nSize%nBlk) ){
3734 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003735 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003736 }
dan502019c2010-07-28 14:26:17 +00003737#endif
3738 }
3739 }
3740
mistachkine98844f2013-08-24 00:59:24 +00003741#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003742 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003743 int rc;
3744 if( pFile->szChunk<=0 ){
3745 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003746 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003747 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3748 }
3749 }
3750
3751 rc = unixMapfile(pFile, nByte);
3752 return rc;
3753 }
mistachkine98844f2013-08-24 00:59:24 +00003754#endif
danf23da962013-03-23 21:00:41 +00003755
dan502019c2010-07-28 14:26:17 +00003756 return SQLITE_OK;
3757}
danielk1977ad94b582007-08-20 06:44:22 +00003758
danielk1977e3026632004-06-22 11:29:02 +00003759/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003760** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003761** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3762**
3763** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3764*/
3765static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3766 if( *pArg<0 ){
3767 *pArg = (pFile->ctrlFlags & mask)!=0;
3768 }else if( (*pArg)==0 ){
3769 pFile->ctrlFlags &= ~mask;
3770 }else{
3771 pFile->ctrlFlags |= mask;
3772 }
3773}
3774
drh696b33e2012-12-06 19:01:42 +00003775/* Forward declaration */
3776static int unixGetTempname(int nBuf, char *zBuf);
3777
drhf12b3f62011-12-21 14:42:29 +00003778/*
drh9e33c2c2007-08-31 18:34:59 +00003779** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003780*/
drhcc6bb3e2007-08-31 16:11:35 +00003781static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003782 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003783 switch( op ){
3784 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003785 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003786 return SQLITE_OK;
3787 }
drh4bf66fd2015-02-19 02:43:02 +00003788 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003789 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003790 return SQLITE_OK;
3791 }
dan6e09d692010-07-27 18:34:15 +00003792 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003793 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003794 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003795 }
drh9ff27ec2010-05-19 19:26:05 +00003796 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003797 int rc;
3798 SimulateIOErrorBenign(1);
3799 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3800 SimulateIOErrorBenign(0);
3801 return rc;
drhf0b190d2011-07-26 16:03:07 +00003802 }
3803 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003804 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3805 return SQLITE_OK;
3806 }
drhcb15f352011-12-23 01:04:17 +00003807 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3808 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003809 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003810 }
drhde60fc22011-12-14 17:53:36 +00003811 case SQLITE_FCNTL_VFSNAME: {
3812 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3813 return SQLITE_OK;
3814 }
drh696b33e2012-12-06 19:01:42 +00003815 case SQLITE_FCNTL_TEMPFILENAME: {
3816 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3817 if( zTFile ){
3818 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3819 *(char**)pArg = zTFile;
3820 }
3821 return SQLITE_OK;
3822 }
drhb959a012013-12-07 12:29:22 +00003823 case SQLITE_FCNTL_HAS_MOVED: {
3824 *(int*)pArg = fileHasMoved(pFile);
3825 return SQLITE_OK;
3826 }
mistachkine98844f2013-08-24 00:59:24 +00003827#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003828 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003829 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003830 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003831 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3832 newLimit = sqlite3GlobalConfig.mxMmap;
3833 }
3834 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003835 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003836 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003837 if( pFile->mmapSize>0 ){
3838 unixUnmapfile(pFile);
3839 rc = unixMapfile(pFile, -1);
3840 }
danbcb8a862013-04-08 15:30:41 +00003841 }
drh34e258c2013-05-23 01:40:53 +00003842 return rc;
danb2d3de32013-03-14 18:34:37 +00003843 }
mistachkine98844f2013-08-24 00:59:24 +00003844#endif
drhd3d8c042012-05-29 17:02:40 +00003845#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003846 /* The pager calls this method to signal that it has done
3847 ** a rollback and that the database is therefore unchanged and
3848 ** it hence it is OK for the transaction change counter to be
3849 ** unchanged.
3850 */
3851 case SQLITE_FCNTL_DB_UNCHANGED: {
3852 ((unixFile*)id)->dbUpdate = 0;
3853 return SQLITE_OK;
3854 }
3855#endif
drhd2cb50b2009-01-09 21:41:17 +00003856#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003857 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3858 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003859 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003860 }
drhd2cb50b2009-01-09 21:41:17 +00003861#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003862 }
drh0b52b7d2011-01-26 19:46:22 +00003863 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003864}
3865
3866/*
danielk1977a3d4c882007-03-23 10:08:38 +00003867** Return the sector size in bytes of the underlying block device for
3868** the specified file. This is almost always 512 bytes, but may be
3869** larger for some devices.
3870**
3871** SQLite code assumes this function cannot fail. It also assumes that
3872** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003873** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003874** same for both.
3875*/
drh537dddf2012-10-26 13:46:24 +00003876#ifndef __QNXNTO__
3877static int unixSectorSize(sqlite3_file *NotUsed){
3878 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003879 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003880}
drh537dddf2012-10-26 13:46:24 +00003881#endif
3882
3883/*
3884** The following version of unixSectorSize() is optimized for QNX.
3885*/
3886#ifdef __QNXNTO__
3887#include <sys/dcmd_blk.h>
3888#include <sys/statvfs.h>
3889static int unixSectorSize(sqlite3_file *id){
3890 unixFile *pFile = (unixFile*)id;
3891 if( pFile->sectorSize == 0 ){
3892 struct statvfs fsInfo;
3893
3894 /* Set defaults for non-supported filesystems */
3895 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3896 pFile->deviceCharacteristics = 0;
3897 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3898 return pFile->sectorSize;
3899 }
3900
3901 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3902 pFile->sectorSize = fsInfo.f_bsize;
3903 pFile->deviceCharacteristics =
3904 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3905 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3906 ** the write succeeds */
3907 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3908 ** so it is ordered */
3909 0;
3910 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3911 pFile->sectorSize = fsInfo.f_bsize;
3912 pFile->deviceCharacteristics =
3913 /* etfs cluster size writes are atomic */
3914 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3915 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3916 ** the write succeeds */
3917 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3918 ** so it is ordered */
3919 0;
3920 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3921 pFile->sectorSize = fsInfo.f_bsize;
3922 pFile->deviceCharacteristics =
3923 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3924 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3925 ** the write succeeds */
3926 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3927 ** so it is ordered */
3928 0;
3929 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3930 pFile->sectorSize = fsInfo.f_bsize;
3931 pFile->deviceCharacteristics =
3932 /* full bitset of atomics from max sector size and smaller */
3933 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3934 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3935 ** so it is ordered */
3936 0;
3937 }else if( strstr(fsInfo.f_basetype, "dos") ){
3938 pFile->sectorSize = fsInfo.f_bsize;
3939 pFile->deviceCharacteristics =
3940 /* full bitset of atomics from max sector size and smaller */
3941 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3942 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3943 ** so it is ordered */
3944 0;
3945 }else{
3946 pFile->deviceCharacteristics =
3947 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3948 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3949 ** the write succeeds */
3950 0;
3951 }
3952 }
3953 /* Last chance verification. If the sector size isn't a multiple of 512
3954 ** then it isn't valid.*/
3955 if( pFile->sectorSize % 512 != 0 ){
3956 pFile->deviceCharacteristics = 0;
3957 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3958 }
3959 return pFile->sectorSize;
3960}
3961#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003962
danielk197790949c22007-08-17 16:50:38 +00003963/*
drhf12b3f62011-12-21 14:42:29 +00003964** Return the device characteristics for the file.
3965**
drhcb15f352011-12-23 01:04:17 +00003966** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003967** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003968** file system does not always provide powersafe overwrites. (In other
3969** words, after a power-loss event, parts of the file that were never
3970** written might end up being altered.) However, non-PSOW behavior is very,
3971** very rare. And asserting PSOW makes a large reduction in the amount
3972** of required I/O for journaling, since a lot of padding is eliminated.
3973** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3974** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003975*/
drhf12b3f62011-12-21 14:42:29 +00003976static int unixDeviceCharacteristics(sqlite3_file *id){
3977 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003978 int rc = 0;
3979#ifdef __QNXNTO__
3980 if( p->sectorSize==0 ) unixSectorSize(id);
3981 rc = p->deviceCharacteristics;
3982#endif
drhcb15f352011-12-23 01:04:17 +00003983 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003984 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003985 }
drh537dddf2012-10-26 13:46:24 +00003986 return rc;
danielk197762079062007-08-15 17:08:46 +00003987}
3988
dan702eec12014-06-23 10:04:58 +00003989#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003990
dan702eec12014-06-23 10:04:58 +00003991/*
3992** Return the system page size.
3993**
3994** This function should not be called directly by other code in this file.
3995** Instead, it should be called via macro osGetpagesize().
3996*/
3997static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003998#if OS_VXWORKS
3999 return 1024;
4000#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004001 return getpagesize();
4002#else
4003 return (int)sysconf(_SC_PAGESIZE);
4004#endif
4005}
4006
4007#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4008
4009#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004010
4011/*
drhd91c68f2010-05-14 14:52:25 +00004012** Object used to represent an shared memory buffer.
4013**
4014** When multiple threads all reference the same wal-index, each thread
4015** has its own unixShm object, but they all point to a single instance
4016** of this unixShmNode object. In other words, each wal-index is opened
4017** only once per process.
4018**
4019** Each unixShmNode object is connected to a single unixInodeInfo object.
4020** We could coalesce this object into unixInodeInfo, but that would mean
4021** every open file that does not use shared memory (in other words, most
4022** open files) would have to carry around this extra information. So
4023** the unixInodeInfo object contains a pointer to this unixShmNode object
4024** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004025**
4026** unixMutexHeld() must be true when creating or destroying
4027** this object or while reading or writing the following fields:
4028**
4029** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004030**
4031** The following fields are read-only after the object is created:
4032**
4033** fid
4034** zFilename
4035**
drhd91c68f2010-05-14 14:52:25 +00004036** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004037** unixMutexHeld() is true when reading or writing any other field
4038** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004039*/
drhd91c68f2010-05-14 14:52:25 +00004040struct unixShmNode {
4041 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004042 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004043 char *zFilename; /* Name of the mmapped file */
4044 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004045 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004046 u16 nRegion; /* Size of array apRegion */
4047 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004048 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004049 int nRef; /* Number of unixShm objects pointing to this */
4050 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004051#ifdef SQLITE_DEBUG
4052 u8 exclMask; /* Mask of exclusive locks held */
4053 u8 sharedMask; /* Mask of shared locks held */
4054 u8 nextShmId; /* Next available unixShm.id value */
4055#endif
4056};
4057
4058/*
drhd9e5c4f2010-05-12 18:01:39 +00004059** Structure used internally by this VFS to record the state of an
4060** open shared memory connection.
4061**
drhd91c68f2010-05-14 14:52:25 +00004062** The following fields are initialized when this object is created and
4063** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004064**
drhd91c68f2010-05-14 14:52:25 +00004065** unixShm.pFile
4066** unixShm.id
4067**
4068** All other fields are read/write. The unixShm.pFile->mutex must be held
4069** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004070*/
4071struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004072 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4073 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004074 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004075 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004076 u16 sharedMask; /* Mask of shared locks held */
4077 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004078};
4079
4080/*
drhd9e5c4f2010-05-12 18:01:39 +00004081** Constants used for locking
4082*/
drhbd9676c2010-06-23 17:58:38 +00004083#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004084#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004085
drhd9e5c4f2010-05-12 18:01:39 +00004086/*
drh73b64e42010-05-30 19:55:15 +00004087** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004088**
4089** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4090** otherwise.
4091*/
4092static int unixShmSystemLock(
drhd91c68f2010-05-14 14:52:25 +00004093 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
4094 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004095 int ofst, /* First byte of the locking range */
4096 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004097){
4098 struct flock f; /* The posix advisory locking structure */
drh73b64e42010-05-30 19:55:15 +00004099 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004100
drhd91c68f2010-05-14 14:52:25 +00004101 /* Access to the unixShmNode object is serialized by the caller */
4102 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004103
drh73b64e42010-05-30 19:55:15 +00004104 /* Shared locks never span more than one byte */
4105 assert( n==1 || lockType!=F_RDLCK );
4106
4107 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004108 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004109
drh3cb93392011-03-12 18:10:44 +00004110 if( pShmNode->h>=0 ){
4111 /* Initialize the locking parameters */
4112 memset(&f, 0, sizeof(f));
4113 f.l_type = lockType;
4114 f.l_whence = SEEK_SET;
4115 f.l_start = ofst;
4116 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004117
drh3cb93392011-03-12 18:10:44 +00004118 rc = osFcntl(pShmNode->h, F_SETLK, &f);
4119 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4120 }
drhd9e5c4f2010-05-12 18:01:39 +00004121
4122 /* Update the global lock state and do debug tracing */
4123#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004124 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004125 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004126 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004127 if( rc==SQLITE_OK ){
4128 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004129 OSTRACE(("unlock %d ok", ofst));
4130 pShmNode->exclMask &= ~mask;
4131 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004132 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004133 OSTRACE(("read-lock %d ok", ofst));
4134 pShmNode->exclMask &= ~mask;
4135 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004136 }else{
4137 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004138 OSTRACE(("write-lock %d ok", ofst));
4139 pShmNode->exclMask |= mask;
4140 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004141 }
4142 }else{
4143 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004144 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004145 }else if( lockType==F_RDLCK ){
4146 OSTRACE(("read-lock failed"));
4147 }else{
4148 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004149 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004150 }
4151 }
drh20e1f082010-05-31 16:10:12 +00004152 OSTRACE((" - afterwards %03x,%03x\n",
4153 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004154 }
drhd9e5c4f2010-05-12 18:01:39 +00004155#endif
4156
4157 return rc;
4158}
4159
dan781e34c2014-03-20 08:59:47 +00004160/*
dan781e34c2014-03-20 08:59:47 +00004161** Return the minimum number of 32KB shm regions that should be mapped at
4162** a time, assuming that each mapping must be an integer multiple of the
4163** current system page-size.
4164**
4165** Usually, this is 1. The exception seems to be systems that are configured
4166** to use 64KB pages - in this case each mapping must cover at least two
4167** shm regions.
4168*/
4169static int unixShmRegionPerMap(void){
4170 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004171 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004172 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4173 if( pgsz<shmsz ) return 1;
4174 return pgsz/shmsz;
4175}
drhd9e5c4f2010-05-12 18:01:39 +00004176
4177/*
drhd91c68f2010-05-14 14:52:25 +00004178** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004179**
4180** This is not a VFS shared-memory method; it is a utility function called
4181** by VFS shared-memory methods.
4182*/
drhd91c68f2010-05-14 14:52:25 +00004183static void unixShmPurge(unixFile *pFd){
4184 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004185 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004186 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004187 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004188 int i;
drhd91c68f2010-05-14 14:52:25 +00004189 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004190 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004191 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004192 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004193 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004194 }else{
4195 sqlite3_free(p->apRegion[i]);
4196 }
dan13a3cb82010-06-11 19:04:21 +00004197 }
dan18801912010-06-14 14:07:50 +00004198 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004199 if( p->h>=0 ){
4200 robust_close(pFd, p->h, __LINE__);
4201 p->h = -1;
4202 }
drhd91c68f2010-05-14 14:52:25 +00004203 p->pInode->pShmNode = 0;
4204 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004205 }
4206}
4207
4208/*
danda9fe0c2010-07-13 18:44:03 +00004209** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004210** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004211**
drh7234c6d2010-06-19 15:10:09 +00004212** The file used to implement shared-memory is in the same directory
4213** as the open database file and has the same name as the open database
4214** file with the "-shm" suffix added. For example, if the database file
4215** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004216** for shared memory will be called "/home/user1/config.db-shm".
4217**
4218** Another approach to is to use files in /dev/shm or /dev/tmp or an
4219** some other tmpfs mount. But if a file in a different directory
4220** from the database file is used, then differing access permissions
4221** or a chroot() might cause two different processes on the same
4222** database to end up using different files for shared memory -
4223** meaning that their memory would not really be shared - resulting
4224** in database corruption. Nevertheless, this tmpfs file usage
4225** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4226** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4227** option results in an incompatible build of SQLite; builds of SQLite
4228** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4229** same database file at the same time, database corruption will likely
4230** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4231** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004232**
4233** When opening a new shared-memory file, if no other instances of that
4234** file are currently open, in this process or in other processes, then
4235** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004236**
4237** If the original database file (pDbFd) is using the "unix-excl" VFS
4238** that means that an exclusive lock is held on the database file and
4239** that no other processes are able to read or write the database. In
4240** that case, we do not really need shared memory. No shared memory
4241** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004242*/
danda9fe0c2010-07-13 18:44:03 +00004243static int unixOpenSharedMemory(unixFile *pDbFd){
4244 struct unixShm *p = 0; /* The connection to be opened */
4245 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4246 int rc; /* Result code */
4247 unixInodeInfo *pInode; /* The inode of fd */
4248 char *zShmFilename; /* Name of the file used for SHM */
4249 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004250
danda9fe0c2010-07-13 18:44:03 +00004251 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004252 p = sqlite3_malloc( sizeof(*p) );
4253 if( p==0 ) return SQLITE_NOMEM;
4254 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004255 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004256
danda9fe0c2010-07-13 18:44:03 +00004257 /* Check to see if a unixShmNode object already exists. Reuse an existing
4258 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004259 */
4260 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004261 pInode = pDbFd->pInode;
4262 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004263 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004264 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004265#ifndef SQLITE_SHM_DIRECTORY
4266 const char *zBasePath = pDbFd->zPath;
4267#endif
danddb0ac42010-07-14 14:48:58 +00004268
4269 /* Call fstat() to figure out the permissions on the database file. If
4270 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004271 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004272 */
drh3cb93392011-03-12 18:10:44 +00004273 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004274 rc = SQLITE_IOERR_FSTAT;
4275 goto shm_open_err;
4276 }
4277
drha4ced192010-07-15 18:32:40 +00004278#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004279 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004280#else
drh4bf66fd2015-02-19 02:43:02 +00004281 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004282#endif
drh7234c6d2010-06-19 15:10:09 +00004283 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004284 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004285 rc = SQLITE_NOMEM;
4286 goto shm_open_err;
4287 }
drh9cb5a0d2012-01-05 21:19:54 +00004288 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004289 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004290#ifdef SQLITE_SHM_DIRECTORY
4291 sqlite3_snprintf(nShmFilename, zShmFilename,
4292 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4293 (u32)sStat.st_ino, (u32)sStat.st_dev);
4294#else
drh4bf66fd2015-02-19 02:43:02 +00004295 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004296 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004297#endif
drhd91c68f2010-05-14 14:52:25 +00004298 pShmNode->h = -1;
4299 pDbFd->pInode->pShmNode = pShmNode;
4300 pShmNode->pInode = pDbFd->pInode;
4301 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4302 if( pShmNode->mutex==0 ){
4303 rc = SQLITE_NOMEM;
4304 goto shm_open_err;
4305 }
drhd9e5c4f2010-05-12 18:01:39 +00004306
drh3cb93392011-03-12 18:10:44 +00004307 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004308 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004309 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004310 openFlags = O_RDONLY;
4311 pShmNode->isReadonly = 1;
4312 }
4313 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004314 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004315 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4316 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004317 }
drhac7c3ac2012-02-11 19:23:48 +00004318
4319 /* If this process is running as root, make sure that the SHM file
4320 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004321 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004322 */
drhed466822012-05-31 13:10:49 +00004323 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004324
4325 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004326 ** If not, truncate the file to zero length.
4327 */
4328 rc = SQLITE_OK;
4329 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
4330 if( robust_ftruncate(pShmNode->h, 0) ){
4331 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004332 }
4333 }
drh66dfec8b2011-06-01 20:01:49 +00004334 if( rc==SQLITE_OK ){
4335 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
4336 }
4337 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004338 }
drhd9e5c4f2010-05-12 18:01:39 +00004339 }
4340
drhd91c68f2010-05-14 14:52:25 +00004341 /* Make the new connection a child of the unixShmNode */
4342 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004343#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004344 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004345#endif
drhd91c68f2010-05-14 14:52:25 +00004346 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004347 pDbFd->pShm = p;
4348 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004349
4350 /* The reference count on pShmNode has already been incremented under
4351 ** the cover of the unixEnterMutex() mutex and the pointer from the
4352 ** new (struct unixShm) object to the pShmNode has been set. All that is
4353 ** left to do is to link the new object into the linked list starting
4354 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4355 ** mutex.
4356 */
4357 sqlite3_mutex_enter(pShmNode->mutex);
4358 p->pNext = pShmNode->pFirst;
4359 pShmNode->pFirst = p;
4360 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004361 return SQLITE_OK;
4362
4363 /* Jump here on any error */
4364shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004365 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004366 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004367 unixLeaveMutex();
4368 return rc;
4369}
4370
4371/*
danda9fe0c2010-07-13 18:44:03 +00004372** This function is called to obtain a pointer to region iRegion of the
4373** shared-memory associated with the database file fd. Shared-memory regions
4374** are numbered starting from zero. Each shared-memory region is szRegion
4375** bytes in size.
4376**
4377** If an error occurs, an error code is returned and *pp is set to NULL.
4378**
4379** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4380** region has not been allocated (by any client, including one running in a
4381** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4382** bExtend is non-zero and the requested shared-memory region has not yet
4383** been allocated, it is allocated by this function.
4384**
4385** If the shared-memory region has already been allocated or is allocated by
4386** this call as described above, then it is mapped into this processes
4387** address space (if it is not already), *pp is set to point to the mapped
4388** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004389*/
danda9fe0c2010-07-13 18:44:03 +00004390static int unixShmMap(
4391 sqlite3_file *fd, /* Handle open on database file */
4392 int iRegion, /* Region to retrieve */
4393 int szRegion, /* Size of regions */
4394 int bExtend, /* True to extend file if necessary */
4395 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004396){
danda9fe0c2010-07-13 18:44:03 +00004397 unixFile *pDbFd = (unixFile*)fd;
4398 unixShm *p;
4399 unixShmNode *pShmNode;
4400 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004401 int nShmPerMap = unixShmRegionPerMap();
4402 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004403
danda9fe0c2010-07-13 18:44:03 +00004404 /* If the shared-memory file has not yet been opened, open it now. */
4405 if( pDbFd->pShm==0 ){
4406 rc = unixOpenSharedMemory(pDbFd);
4407 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004408 }
drhd9e5c4f2010-05-12 18:01:39 +00004409
danda9fe0c2010-07-13 18:44:03 +00004410 p = pDbFd->pShm;
4411 pShmNode = p->pShmNode;
4412 sqlite3_mutex_enter(pShmNode->mutex);
4413 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004414 assert( pShmNode->pInode==pDbFd->pInode );
4415 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4416 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004417
dan781e34c2014-03-20 08:59:47 +00004418 /* Minimum number of regions required to be mapped. */
4419 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4420
4421 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004422 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004423 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004424 struct stat sStat; /* Used by fstat() */
4425
4426 pShmNode->szRegion = szRegion;
4427
drh3cb93392011-03-12 18:10:44 +00004428 if( pShmNode->h>=0 ){
4429 /* The requested region is not mapped into this processes address space.
4430 ** Check to see if it has been allocated (i.e. if the wal-index file is
4431 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004432 */
drh3cb93392011-03-12 18:10:44 +00004433 if( osFstat(pShmNode->h, &sStat) ){
4434 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004435 goto shmpage_out;
4436 }
drh3cb93392011-03-12 18:10:44 +00004437
4438 if( sStat.st_size<nByte ){
4439 /* The requested memory region does not exist. If bExtend is set to
4440 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004441 */
dan47a2b4a2013-04-26 16:09:29 +00004442 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004443 goto shmpage_out;
4444 }
dan47a2b4a2013-04-26 16:09:29 +00004445
4446 /* Alternatively, if bExtend is true, extend the file. Do this by
4447 ** writing a single byte to the end of each (OS) page being
4448 ** allocated or extended. Technically, we need only write to the
4449 ** last page in order to extend the file. But writing to all new
4450 ** pages forces the OS to allocate them immediately, which reduces
4451 ** the chances of SIGBUS while accessing the mapped region later on.
4452 */
4453 else{
4454 static const int pgsz = 4096;
4455 int iPg;
4456
4457 /* Write to the last byte of each newly allocated or extended page */
4458 assert( (nByte % pgsz)==0 );
4459 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4460 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4461 const char *zFile = pShmNode->zFilename;
4462 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4463 goto shmpage_out;
4464 }
4465 }
drh3cb93392011-03-12 18:10:44 +00004466 }
4467 }
danda9fe0c2010-07-13 18:44:03 +00004468 }
4469
4470 /* Map the requested memory region into this processes address space. */
4471 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004472 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004473 );
4474 if( !apNew ){
4475 rc = SQLITE_IOERR_NOMEM;
4476 goto shmpage_out;
4477 }
4478 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004479 while( pShmNode->nRegion<nReqRegion ){
4480 int nMap = szRegion*nShmPerMap;
4481 int i;
drh3cb93392011-03-12 18:10:44 +00004482 void *pMem;
4483 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004484 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004485 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004486 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004487 );
4488 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004489 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004490 goto shmpage_out;
4491 }
4492 }else{
4493 pMem = sqlite3_malloc(szRegion);
4494 if( pMem==0 ){
4495 rc = SQLITE_NOMEM;
4496 goto shmpage_out;
4497 }
4498 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004499 }
dan781e34c2014-03-20 08:59:47 +00004500
4501 for(i=0; i<nShmPerMap; i++){
4502 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4503 }
4504 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004505 }
4506 }
4507
4508shmpage_out:
4509 if( pShmNode->nRegion>iRegion ){
4510 *pp = pShmNode->apRegion[iRegion];
4511 }else{
4512 *pp = 0;
4513 }
drh66dfec8b2011-06-01 20:01:49 +00004514 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004515 sqlite3_mutex_leave(pShmNode->mutex);
4516 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004517}
4518
4519/*
drhd9e5c4f2010-05-12 18:01:39 +00004520** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004521**
4522** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4523** different here than in posix. In xShmLock(), one can go from unlocked
4524** to shared and back or from unlocked to exclusive and back. But one may
4525** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004526*/
4527static int unixShmLock(
4528 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004529 int ofst, /* First lock to acquire or release */
4530 int n, /* Number of locks to acquire or release */
4531 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004532){
drh73b64e42010-05-30 19:55:15 +00004533 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4534 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4535 unixShm *pX; /* For looping over all siblings */
4536 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4537 int rc = SQLITE_OK; /* Result code */
4538 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004539
drhd91c68f2010-05-14 14:52:25 +00004540 assert( pShmNode==pDbFd->pInode->pShmNode );
4541 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004542 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004543 assert( n>=1 );
4544 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4545 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4546 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4547 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4548 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004549 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4550 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004551
drhc99597c2010-05-31 01:41:15 +00004552 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004553 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004554 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004555 if( flags & SQLITE_SHM_UNLOCK ){
4556 u16 allMask = 0; /* Mask of locks held by siblings */
4557
4558 /* See if any siblings hold this same lock */
4559 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4560 if( pX==p ) continue;
4561 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4562 allMask |= pX->sharedMask;
4563 }
4564
4565 /* Unlock the system-level locks */
4566 if( (mask & allMask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004567 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004568 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004569 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004570 }
drh73b64e42010-05-30 19:55:15 +00004571
4572 /* Undo the local locks */
4573 if( rc==SQLITE_OK ){
4574 p->exclMask &= ~mask;
4575 p->sharedMask &= ~mask;
4576 }
4577 }else if( flags & SQLITE_SHM_SHARED ){
4578 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4579
4580 /* Find out which shared locks are already held by sibling connections.
4581 ** If any sibling already holds an exclusive lock, go ahead and return
4582 ** SQLITE_BUSY.
4583 */
4584 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004585 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004586 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004587 break;
4588 }
4589 allShared |= pX->sharedMask;
4590 }
4591
4592 /* Get shared locks at the system level, if necessary */
4593 if( rc==SQLITE_OK ){
4594 if( (allShared & mask)==0 ){
drhc99597c2010-05-31 01:41:15 +00004595 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004596 }else{
drh73b64e42010-05-30 19:55:15 +00004597 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004598 }
drhd9e5c4f2010-05-12 18:01:39 +00004599 }
drh73b64e42010-05-30 19:55:15 +00004600
4601 /* Get the local shared locks */
4602 if( rc==SQLITE_OK ){
4603 p->sharedMask |= mask;
4604 }
4605 }else{
4606 /* Make sure no sibling connections hold locks that will block this
4607 ** lock. If any do, return SQLITE_BUSY right away.
4608 */
4609 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004610 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4611 rc = SQLITE_BUSY;
4612 break;
4613 }
4614 }
4615
4616 /* Get the exclusive locks at the system level. Then if successful
4617 ** also mark the local connection as being locked.
4618 */
4619 if( rc==SQLITE_OK ){
drhc99597c2010-05-31 01:41:15 +00004620 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004621 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004622 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004623 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004624 }
drhd9e5c4f2010-05-12 18:01:39 +00004625 }
4626 }
drhd91c68f2010-05-14 14:52:25 +00004627 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004628 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh91eb93c2015-03-03 19:56:20 +00004629 p->id, osGetpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004630 return rc;
4631}
4632
drh286a2882010-05-20 23:51:06 +00004633/*
4634** Implement a memory barrier or memory fence on shared memory.
4635**
4636** All loads and stores begun before the barrier must complete before
4637** any load or store begun after the barrier.
4638*/
4639static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004640 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004641){
drhff828942010-06-26 21:34:06 +00004642 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004643 unixEnterMutex();
4644 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004645}
4646
dan18801912010-06-14 14:07:50 +00004647/*
danda9fe0c2010-07-13 18:44:03 +00004648** Close a connection to shared-memory. Delete the underlying
4649** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004650**
4651** If there is no shared memory associated with the connection then this
4652** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004653*/
danda9fe0c2010-07-13 18:44:03 +00004654static int unixShmUnmap(
4655 sqlite3_file *fd, /* The underlying database file */
4656 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004657){
danda9fe0c2010-07-13 18:44:03 +00004658 unixShm *p; /* The connection to be closed */
4659 unixShmNode *pShmNode; /* The underlying shared-memory file */
4660 unixShm **pp; /* For looping over sibling connections */
4661 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004662
danda9fe0c2010-07-13 18:44:03 +00004663 pDbFd = (unixFile*)fd;
4664 p = pDbFd->pShm;
4665 if( p==0 ) return SQLITE_OK;
4666 pShmNode = p->pShmNode;
4667
4668 assert( pShmNode==pDbFd->pInode->pShmNode );
4669 assert( pShmNode->pInode==pDbFd->pInode );
4670
4671 /* Remove connection p from the set of connections associated
4672 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004673 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004674 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4675 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004676
danda9fe0c2010-07-13 18:44:03 +00004677 /* Free the connection p */
4678 sqlite3_free(p);
4679 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004680 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004681
4682 /* If pShmNode->nRef has reached 0, then close the underlying
4683 ** shared-memory file, too */
4684 unixEnterMutex();
4685 assert( pShmNode->nRef>0 );
4686 pShmNode->nRef--;
4687 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004688 if( deleteFlag && pShmNode->h>=0 ){
4689 osUnlink(pShmNode->zFilename);
4690 }
danda9fe0c2010-07-13 18:44:03 +00004691 unixShmPurge(pDbFd);
4692 }
4693 unixLeaveMutex();
4694
4695 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004696}
drh286a2882010-05-20 23:51:06 +00004697
danda9fe0c2010-07-13 18:44:03 +00004698
drhd9e5c4f2010-05-12 18:01:39 +00004699#else
drh6b017cc2010-06-14 18:01:46 +00004700# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004701# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004702# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004703# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004704#endif /* #ifndef SQLITE_OMIT_WAL */
4705
mistachkine98844f2013-08-24 00:59:24 +00004706#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004707/*
danaef49d72013-03-25 16:28:54 +00004708** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004709*/
danf23da962013-03-23 21:00:41 +00004710static void unixUnmapfile(unixFile *pFd){
4711 assert( pFd->nFetchOut==0 );
4712 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004713 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004714 pFd->pMapRegion = 0;
4715 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004716 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004717 }
4718}
dan5d8a1372013-03-19 19:28:06 +00004719
danaef49d72013-03-25 16:28:54 +00004720/*
dane6ecd662013-04-01 17:56:59 +00004721** Attempt to set the size of the memory mapping maintained by file
4722** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4723**
4724** If successful, this function sets the following variables:
4725**
4726** unixFile.pMapRegion
4727** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004728** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004729**
4730** If unsuccessful, an error message is logged via sqlite3_log() and
4731** the three variables above are zeroed. In this case SQLite should
4732** continue accessing the database using the xRead() and xWrite()
4733** methods.
4734*/
4735static void unixRemapfile(
4736 unixFile *pFd, /* File descriptor object */
4737 i64 nNew /* Required mapping size */
4738){
dan4ff7bc42013-04-02 12:04:09 +00004739 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004740 int h = pFd->h; /* File descriptor open on db file */
4741 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004742 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004743 u8 *pNew = 0; /* Location of new mapping */
4744 int flags = PROT_READ; /* Flags to pass to mmap() */
4745
4746 assert( pFd->nFetchOut==0 );
4747 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004748 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004749 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004750 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004751 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004752
4753 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4754
4755 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004756#if HAVE_MREMAP
4757 i64 nReuse = pFd->mmapSize;
4758#else
danbc760632014-03-20 09:42:09 +00004759 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004760 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004761#endif
dane6ecd662013-04-01 17:56:59 +00004762 u8 *pReq = &pOrig[nReuse];
4763
4764 /* Unmap any pages of the existing mapping that cannot be reused. */
4765 if( nReuse!=nOrig ){
4766 osMunmap(pReq, nOrig-nReuse);
4767 }
4768
4769#if HAVE_MREMAP
4770 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004771 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004772#else
4773 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4774 if( pNew!=MAP_FAILED ){
4775 if( pNew!=pReq ){
4776 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004777 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004778 }else{
4779 pNew = pOrig;
4780 }
4781 }
4782#endif
4783
dan48ccef82013-04-02 20:55:01 +00004784 /* The attempt to extend the existing mapping failed. Free it. */
4785 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004786 osMunmap(pOrig, nReuse);
4787 }
4788 }
4789
4790 /* If pNew is still NULL, try to create an entirely new mapping. */
4791 if( pNew==0 ){
4792 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004793 }
4794
dan4ff7bc42013-04-02 12:04:09 +00004795 if( pNew==MAP_FAILED ){
4796 pNew = 0;
4797 nNew = 0;
4798 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4799
4800 /* If the mmap() above failed, assume that all subsequent mmap() calls
4801 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4802 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004803 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004804 }
dane6ecd662013-04-01 17:56:59 +00004805 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004806 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004807}
4808
4809/*
danaef49d72013-03-25 16:28:54 +00004810** Memory map or remap the file opened by file-descriptor pFd (if the file
4811** is already mapped, the existing mapping is replaced by the new). Or, if
4812** there already exists a mapping for this file, and there are still
4813** outstanding xFetch() references to it, this function is a no-op.
4814**
4815** If parameter nByte is non-negative, then it is the requested size of
4816** the mapping to create. Otherwise, if nByte is less than zero, then the
4817** requested size is the size of the file on disk. The actual size of the
4818** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004819** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004820**
4821** SQLITE_OK is returned if no error occurs (even if the mapping is not
4822** recreated as a result of outstanding references) or an SQLite error
4823** code otherwise.
4824*/
danf23da962013-03-23 21:00:41 +00004825static int unixMapfile(unixFile *pFd, i64 nByte){
4826 i64 nMap = nByte;
4827 int rc;
daneb97b292013-03-20 14:26:59 +00004828
danf23da962013-03-23 21:00:41 +00004829 assert( nMap>=0 || pFd->nFetchOut==0 );
4830 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4831
4832 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004833 struct stat statbuf; /* Low-level file information */
4834 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004835 if( rc!=SQLITE_OK ){
4836 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004837 }
drh3044b512014-06-16 16:41:52 +00004838 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004839 }
drh9b4c59f2013-04-15 17:03:42 +00004840 if( nMap>pFd->mmapSizeMax ){
4841 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004842 }
4843
danf23da962013-03-23 21:00:41 +00004844 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004845 if( nMap>0 ){
4846 unixRemapfile(pFd, nMap);
4847 }else{
danb7e3a322013-03-25 20:30:13 +00004848 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004849 }
4850 }
4851
danf23da962013-03-23 21:00:41 +00004852 return SQLITE_OK;
4853}
mistachkine98844f2013-08-24 00:59:24 +00004854#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004855
danaef49d72013-03-25 16:28:54 +00004856/*
4857** If possible, return a pointer to a mapping of file fd starting at offset
4858** iOff. The mapping must be valid for at least nAmt bytes.
4859**
4860** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4861** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4862** Finally, if an error does occur, return an SQLite error code. The final
4863** value of *pp is undefined in this case.
4864**
4865** If this function does return a pointer, the caller must eventually
4866** release the reference by calling unixUnfetch().
4867*/
danf23da962013-03-23 21:00:41 +00004868static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004869#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004870 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004871#endif
danf23da962013-03-23 21:00:41 +00004872 *pp = 0;
4873
drh9b4c59f2013-04-15 17:03:42 +00004874#if SQLITE_MAX_MMAP_SIZE>0
4875 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004876 if( pFd->pMapRegion==0 ){
4877 int rc = unixMapfile(pFd, -1);
4878 if( rc!=SQLITE_OK ) return rc;
4879 }
4880 if( pFd->mmapSize >= iOff+nAmt ){
4881 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4882 pFd->nFetchOut++;
4883 }
4884 }
drh6e0b6d52013-04-09 16:19:20 +00004885#endif
danf23da962013-03-23 21:00:41 +00004886 return SQLITE_OK;
4887}
4888
danaef49d72013-03-25 16:28:54 +00004889/*
dandf737fe2013-03-25 17:00:24 +00004890** If the third argument is non-NULL, then this function releases a
4891** reference obtained by an earlier call to unixFetch(). The second
4892** argument passed to this function must be the same as the corresponding
4893** argument that was passed to the unixFetch() invocation.
4894**
4895** Or, if the third argument is NULL, then this function is being called
4896** to inform the VFS layer that, according to POSIX, any existing mapping
4897** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004898*/
dandf737fe2013-03-25 17:00:24 +00004899static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004900#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004901 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004902 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004903
danaef49d72013-03-25 16:28:54 +00004904 /* If p==0 (unmap the entire file) then there must be no outstanding
4905 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4906 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004907 assert( (p==0)==(pFd->nFetchOut==0) );
4908
dandf737fe2013-03-25 17:00:24 +00004909 /* If p!=0, it must match the iOff value. */
4910 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4911
danf23da962013-03-23 21:00:41 +00004912 if( p ){
4913 pFd->nFetchOut--;
4914 }else{
4915 unixUnmapfile(pFd);
4916 }
4917
4918 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004919#else
4920 UNUSED_PARAMETER(fd);
4921 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004922 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004923#endif
danf23da962013-03-23 21:00:41 +00004924 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004925}
4926
4927/*
drh734c9862008-11-28 15:37:20 +00004928** Here ends the implementation of all sqlite3_file methods.
4929**
4930********************** End sqlite3_file Methods *******************************
4931******************************************************************************/
4932
4933/*
drh6b9d6dd2008-12-03 19:34:47 +00004934** This division contains definitions of sqlite3_io_methods objects that
4935** implement various file locking strategies. It also contains definitions
4936** of "finder" functions. A finder-function is used to locate the appropriate
4937** sqlite3_io_methods object for a particular database file. The pAppData
4938** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4939** the correct finder-function for that VFS.
4940**
4941** Most finder functions return a pointer to a fixed sqlite3_io_methods
4942** object. The only interesting finder-function is autolockIoFinder, which
4943** looks at the filesystem type and tries to guess the best locking
4944** strategy from that.
4945**
peter.d.reid60ec9142014-09-06 16:39:46 +00004946** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004947**
4948** (1) The real finder-function named "FImpt()".
4949**
dane946c392009-08-22 11:39:46 +00004950** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004951**
4952**
4953** A pointer to the F pointer is used as the pAppData value for VFS
4954** objects. We have to do this instead of letting pAppData point
4955** directly at the finder-function since C90 rules prevent a void*
4956** from be cast into a function pointer.
4957**
drh6b9d6dd2008-12-03 19:34:47 +00004958**
drh7708e972008-11-29 00:56:52 +00004959** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004960**
drh7708e972008-11-29 00:56:52 +00004961** * A constant sqlite3_io_methods object call METHOD that has locking
4962** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4963**
4964** * An I/O method finder function called FINDER that returns a pointer
4965** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004966*/
drhe6d41732015-02-21 00:49:00 +00004967#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004968static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004969 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004970 CLOSE, /* xClose */ \
4971 unixRead, /* xRead */ \
4972 unixWrite, /* xWrite */ \
4973 unixTruncate, /* xTruncate */ \
4974 unixSync, /* xSync */ \
4975 unixFileSize, /* xFileSize */ \
4976 LOCK, /* xLock */ \
4977 UNLOCK, /* xUnlock */ \
4978 CKLOCK, /* xCheckReservedLock */ \
4979 unixFileControl, /* xFileControl */ \
4980 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004981 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004982 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004983 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004984 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004985 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004986 unixFetch, /* xFetch */ \
4987 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004988}; \
drh0c2694b2009-09-03 16:23:44 +00004989static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4990 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004991 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004992} \
drh0c2694b2009-09-03 16:23:44 +00004993static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004994 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004995
4996/*
4997** Here are all of the sqlite3_io_methods objects for each of the
4998** locking strategies. Functions that return pointers to these methods
4999** are also created.
5000*/
5001IOMETHODS(
5002 posixIoFinder, /* Finder function name */
5003 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005004 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005005 unixClose, /* xClose method */
5006 unixLock, /* xLock method */
5007 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005008 unixCheckReservedLock, /* xCheckReservedLock method */
5009 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005010)
drh7708e972008-11-29 00:56:52 +00005011IOMETHODS(
5012 nolockIoFinder, /* Finder function name */
5013 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005014 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005015 nolockClose, /* xClose method */
5016 nolockLock, /* xLock method */
5017 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005018 nolockCheckReservedLock, /* xCheckReservedLock method */
5019 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005020)
drh7708e972008-11-29 00:56:52 +00005021IOMETHODS(
5022 dotlockIoFinder, /* Finder function name */
5023 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005024 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005025 dotlockClose, /* xClose method */
5026 dotlockLock, /* xLock method */
5027 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005028 dotlockCheckReservedLock, /* xCheckReservedLock method */
5029 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005030)
drh7708e972008-11-29 00:56:52 +00005031
chw78a13182009-04-07 05:35:03 +00005032#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005033IOMETHODS(
5034 flockIoFinder, /* Finder function name */
5035 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005036 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005037 flockClose, /* xClose method */
5038 flockLock, /* xLock method */
5039 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005040 flockCheckReservedLock, /* xCheckReservedLock method */
5041 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005042)
drh7708e972008-11-29 00:56:52 +00005043#endif
5044
drh6c7d5c52008-11-21 20:32:33 +00005045#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005046IOMETHODS(
5047 semIoFinder, /* Finder function name */
5048 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005049 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005050 semXClose, /* xClose method */
5051 semXLock, /* xLock method */
5052 semXUnlock, /* xUnlock method */
5053 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005054 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005055)
aswiftaebf4132008-11-21 00:10:35 +00005056#endif
drh7708e972008-11-29 00:56:52 +00005057
drhd2cb50b2009-01-09 21:41:17 +00005058#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005059IOMETHODS(
5060 afpIoFinder, /* Finder function name */
5061 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005062 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005063 afpClose, /* xClose method */
5064 afpLock, /* xLock method */
5065 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005066 afpCheckReservedLock, /* xCheckReservedLock method */
5067 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005068)
drh715ff302008-12-03 22:32:44 +00005069#endif
5070
5071/*
5072** The proxy locking method is a "super-method" in the sense that it
5073** opens secondary file descriptors for the conch and lock files and
5074** it uses proxy, dot-file, AFP, and flock() locking methods on those
5075** secondary files. For this reason, the division that implements
5076** proxy locking is located much further down in the file. But we need
5077** to go ahead and define the sqlite3_io_methods and finder function
5078** for proxy locking here. So we forward declare the I/O methods.
5079*/
drhd2cb50b2009-01-09 21:41:17 +00005080#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005081static int proxyClose(sqlite3_file*);
5082static int proxyLock(sqlite3_file*, int);
5083static int proxyUnlock(sqlite3_file*, int);
5084static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005085IOMETHODS(
5086 proxyIoFinder, /* Finder function name */
5087 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005088 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005089 proxyClose, /* xClose method */
5090 proxyLock, /* xLock method */
5091 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005092 proxyCheckReservedLock, /* xCheckReservedLock method */
5093 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005094)
aswiftaebf4132008-11-21 00:10:35 +00005095#endif
drh7708e972008-11-29 00:56:52 +00005096
drh7ed97b92010-01-20 13:07:21 +00005097/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5098#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5099IOMETHODS(
5100 nfsIoFinder, /* Finder function name */
5101 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005102 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005103 unixClose, /* xClose method */
5104 unixLock, /* xLock method */
5105 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005106 unixCheckReservedLock, /* xCheckReservedLock method */
5107 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005108)
5109#endif
drh7708e972008-11-29 00:56:52 +00005110
drhd2cb50b2009-01-09 21:41:17 +00005111#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005112/*
drh6b9d6dd2008-12-03 19:34:47 +00005113** This "finder" function attempts to determine the best locking strategy
5114** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005115** object that implements that strategy.
5116**
5117** This is for MacOSX only.
5118*/
drh1875f7a2008-12-08 18:19:17 +00005119static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005120 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005121 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005122){
5123 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005124 const char *zFilesystem; /* Filesystem type name */
5125 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005126 } aMap[] = {
5127 { "hfs", &posixIoMethods },
5128 { "ufs", &posixIoMethods },
5129 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005130 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005131 { "webdav", &nolockIoMethods },
5132 { 0, 0 }
5133 };
5134 int i;
5135 struct statfs fsInfo;
5136 struct flock lockInfo;
5137
5138 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005139 /* If filePath==NULL that means we are dealing with a transient file
5140 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005141 return &nolockIoMethods;
5142 }
5143 if( statfs(filePath, &fsInfo) != -1 ){
5144 if( fsInfo.f_flags & MNT_RDONLY ){
5145 return &nolockIoMethods;
5146 }
5147 for(i=0; aMap[i].zFilesystem; i++){
5148 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5149 return aMap[i].pMethods;
5150 }
5151 }
5152 }
5153
5154 /* Default case. Handles, amongst others, "nfs".
5155 ** Test byte-range lock using fcntl(). If the call succeeds,
5156 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005157 */
drh7708e972008-11-29 00:56:52 +00005158 lockInfo.l_len = 1;
5159 lockInfo.l_start = 0;
5160 lockInfo.l_whence = SEEK_SET;
5161 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005162 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005163 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5164 return &nfsIoMethods;
5165 } else {
5166 return &posixIoMethods;
5167 }
drh7708e972008-11-29 00:56:52 +00005168 }else{
5169 return &dotlockIoMethods;
5170 }
5171}
drh0c2694b2009-09-03 16:23:44 +00005172static const sqlite3_io_methods
5173 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005174
drhd2cb50b2009-01-09 21:41:17 +00005175#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005176
chw78a13182009-04-07 05:35:03 +00005177#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
5178/*
5179** This "finder" function attempts to determine the best locking strategy
5180** for the database file "filePath". It then returns the sqlite3_io_methods
5181** object that implements that strategy.
5182**
5183** This is for VXWorks only.
5184*/
5185static const sqlite3_io_methods *autolockIoFinderImpl(
5186 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005187 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005188){
5189 struct flock lockInfo;
5190
5191 if( !filePath ){
5192 /* If filePath==NULL that means we are dealing with a transient file
5193 ** that does not need to be locked. */
5194 return &nolockIoMethods;
5195 }
5196
5197 /* Test if fcntl() is supported and use POSIX style locks.
5198 ** Otherwise fall back to the named semaphore method.
5199 */
5200 lockInfo.l_len = 1;
5201 lockInfo.l_start = 0;
5202 lockInfo.l_whence = SEEK_SET;
5203 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005204 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005205 return &posixIoMethods;
5206 }else{
5207 return &semIoMethods;
5208 }
5209}
drh0c2694b2009-09-03 16:23:44 +00005210static const sqlite3_io_methods
5211 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005212
5213#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
5214
drh7708e972008-11-29 00:56:52 +00005215/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005216** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005217*/
drh0c2694b2009-09-03 16:23:44 +00005218typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005219
aswiftaebf4132008-11-21 00:10:35 +00005220
drh734c9862008-11-28 15:37:20 +00005221/****************************************************************************
5222**************************** sqlite3_vfs methods ****************************
5223**
5224** This division contains the implementation of methods on the
5225** sqlite3_vfs object.
5226*/
5227
danielk1977a3d4c882007-03-23 10:08:38 +00005228/*
danielk1977e339d652008-06-28 11:23:00 +00005229** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005230*/
5231static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005232 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005233 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005234 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005235 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005236 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005237){
drh7708e972008-11-29 00:56:52 +00005238 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005239 unixFile *pNew = (unixFile *)pId;
5240 int rc = SQLITE_OK;
5241
drh8af6c222010-05-14 12:43:01 +00005242 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005243
dan00157392010-10-05 11:33:15 +00005244 /* Usually the path zFilename should not be a relative pathname. The
5245 ** exception is when opening the proxy "conch" file in builds that
5246 ** include the special Apple locking styles.
5247 */
dan00157392010-10-05 11:33:15 +00005248#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005249 assert( zFilename==0 || zFilename[0]=='/'
5250 || pVfs->pAppData==(void*)&autolockIoFinder );
5251#else
5252 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005253#endif
dan00157392010-10-05 11:33:15 +00005254
drhb07028f2011-10-14 21:49:18 +00005255 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005256 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005257
drh308c2a52010-05-14 11:30:18 +00005258 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005259 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005260 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005261 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005262 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005263#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005264 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005265#endif
drhc02a43a2012-01-10 23:18:38 +00005266 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5267 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005268 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005269 }
drh503a6862013-03-01 01:07:17 +00005270 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005271 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005272 }
drh339eb0b2008-03-07 15:34:11 +00005273
drh6c7d5c52008-11-21 20:32:33 +00005274#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005275 pNew->pId = vxworksFindFileId(zFilename);
5276 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005277 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005278 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005279 }
5280#endif
5281
drhc02a43a2012-01-10 23:18:38 +00005282 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005283 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005284 }else{
drh0c2694b2009-09-03 16:23:44 +00005285 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005286#if SQLITE_ENABLE_LOCKING_STYLE
5287 /* Cache zFilename in the locking context (AFP and dotlock override) for
5288 ** proxyLock activation is possible (remote proxy is based on db name)
5289 ** zFilename remains valid until file is closed, to support */
5290 pNew->lockingContext = (void*)zFilename;
5291#endif
drhda0e7682008-07-30 15:27:54 +00005292 }
danielk1977e339d652008-06-28 11:23:00 +00005293
drh7ed97b92010-01-20 13:07:21 +00005294 if( pLockingStyle == &posixIoMethods
5295#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5296 || pLockingStyle == &nfsIoMethods
5297#endif
5298 ){
drh7708e972008-11-29 00:56:52 +00005299 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005300 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005301 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005302 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005303 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005304 ** in two scenarios:
5305 **
5306 ** (a) A call to fstat() failed.
5307 ** (b) A malloc failed.
5308 **
5309 ** Scenario (b) may only occur if the process is holding no other
5310 ** file descriptors open on the same file. If there were other file
5311 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005312 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005313 ** handle h - as it is guaranteed that no posix locks will be released
5314 ** by doing so.
5315 **
5316 ** If scenario (a) caused the error then things are not so safe. The
5317 ** implicit assumption here is that if fstat() fails, things are in
5318 ** such bad shape that dropping a lock or two doesn't matter much.
5319 */
drh0e9365c2011-03-02 02:08:13 +00005320 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005321 h = -1;
5322 }
drh7708e972008-11-29 00:56:52 +00005323 unixLeaveMutex();
5324 }
danielk1977e339d652008-06-28 11:23:00 +00005325
drhd2cb50b2009-01-09 21:41:17 +00005326#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005327 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005328 /* AFP locking uses the file path so it needs to be included in
5329 ** the afpLockingContext.
5330 */
5331 afpLockingContext *pCtx;
5332 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5333 if( pCtx==0 ){
5334 rc = SQLITE_NOMEM;
5335 }else{
5336 /* NB: zFilename exists and remains valid until the file is closed
5337 ** according to requirement F11141. So we do not need to make a
5338 ** copy of the filename. */
5339 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005340 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005341 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005342 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005343 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005344 if( rc!=SQLITE_OK ){
5345 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005346 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005347 h = -1;
5348 }
drh7708e972008-11-29 00:56:52 +00005349 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005350 }
drh7708e972008-11-29 00:56:52 +00005351 }
5352#endif
danielk1977e339d652008-06-28 11:23:00 +00005353
drh7708e972008-11-29 00:56:52 +00005354 else if( pLockingStyle == &dotlockIoMethods ){
5355 /* Dotfile locking uses the file path so it needs to be included in
5356 ** the dotlockLockingContext
5357 */
5358 char *zLockFile;
5359 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005360 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005361 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005362 zLockFile = (char *)sqlite3_malloc(nFilename);
5363 if( zLockFile==0 ){
5364 rc = SQLITE_NOMEM;
5365 }else{
5366 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005367 }
drh7708e972008-11-29 00:56:52 +00005368 pNew->lockingContext = zLockFile;
5369 }
danielk1977e339d652008-06-28 11:23:00 +00005370
drh6c7d5c52008-11-21 20:32:33 +00005371#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005372 else if( pLockingStyle == &semIoMethods ){
5373 /* Named semaphore locking uses the file path so it needs to be
5374 ** included in the semLockingContext
5375 */
5376 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005377 rc = findInodeInfo(pNew, &pNew->pInode);
5378 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5379 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005380 int n;
drh2238dcc2009-08-27 17:56:20 +00005381 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005382 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005383 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005384 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005385 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5386 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005387 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005388 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005389 }
chw97185482008-11-17 08:05:31 +00005390 }
drh7708e972008-11-29 00:56:52 +00005391 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005392 }
drh7708e972008-11-29 00:56:52 +00005393#endif
aswift5b1a2562008-08-22 00:22:35 +00005394
drh4bf66fd2015-02-19 02:43:02 +00005395 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005396#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005397 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005398 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005399 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005400 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005401 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005402 }
chw97185482008-11-17 08:05:31 +00005403#endif
danielk1977e339d652008-06-28 11:23:00 +00005404 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005405 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005406 }else{
drh7708e972008-11-29 00:56:52 +00005407 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005408 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005409 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005410 }
danielk1977e339d652008-06-28 11:23:00 +00005411 return rc;
drh054889e2005-11-30 03:20:31 +00005412}
drh9c06c952005-11-26 00:25:00 +00005413
danielk1977ad94b582007-08-20 06:44:22 +00005414/*
drh8b3cf822010-06-01 21:02:51 +00005415** Return the name of a directory in which to put temporary files.
5416** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005417*/
drh7234c6d2010-06-19 15:10:09 +00005418static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005419 static const char *azDirs[] = {
5420 0,
aswiftaebf4132008-11-21 00:10:35 +00005421 0,
mistachkind95a3d32013-08-30 21:52:38 +00005422 0,
danielk197717b90b52008-06-06 11:11:25 +00005423 "/var/tmp",
5424 "/usr/tmp",
5425 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005426 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005427 };
drh8b3cf822010-06-01 21:02:51 +00005428 unsigned int i;
5429 struct stat buf;
5430 const char *zDir = 0;
5431
5432 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005433 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5434 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005435 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005436 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005437 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005438 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005439 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005440 break;
5441 }
5442 return zDir;
5443}
5444
5445/*
5446** Create a temporary file name in zBuf. zBuf must be allocated
5447** by the calling process and must be big enough to hold at least
5448** pVfs->mxPathname bytes.
5449*/
5450static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005451 static const unsigned char zChars[] =
5452 "abcdefghijklmnopqrstuvwxyz"
5453 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5454 "0123456789";
drh41022642008-11-21 00:24:42 +00005455 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005456 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005457
5458 /* It's odd to simulate an io-error here, but really this is just
5459 ** using the io-error infrastructure to test that SQLite handles this
5460 ** function failing.
5461 */
5462 SimulateIOError( return SQLITE_IOERR );
5463
drh7234c6d2010-06-19 15:10:09 +00005464 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005465 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005466
5467 /* Check that the output buffer is large enough for the temporary file
5468 ** name. If it is not, return SQLITE_ERROR.
5469 */
drhc02a43a2012-01-10 23:18:38 +00005470 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005471 return SQLITE_ERROR;
5472 }
5473
5474 do{
drhc02a43a2012-01-10 23:18:38 +00005475 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005476 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005477 sqlite3_randomness(15, &zBuf[j]);
5478 for(i=0; i<15; i++, j++){
5479 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5480 }
5481 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005482 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005483 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005484 return SQLITE_OK;
5485}
5486
drhd2cb50b2009-01-09 21:41:17 +00005487#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005488/*
5489** Routine to transform a unixFile into a proxy-locking unixFile.
5490** Implementation in the proxy-lock division, but used by unixOpen()
5491** if SQLITE_PREFER_PROXY_LOCKING is defined.
5492*/
5493static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005494#endif
drhc66d5b62008-12-03 22:48:32 +00005495
dan08da86a2009-08-21 17:18:03 +00005496/*
5497** Search for an unused file descriptor that was opened on the database
5498** file (not a journal or master-journal file) identified by pathname
5499** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5500** argument to this function.
5501**
5502** Such a file descriptor may exist if a database connection was closed
5503** but the associated file descriptor could not be closed because some
5504** other file descriptor open on the same file is holding a file-lock.
5505** Refer to comments in the unixClose() function and the lengthy comment
5506** describing "Posix Advisory Locking" at the start of this file for
5507** further details. Also, ticket #4018.
5508**
5509** If a suitable file descriptor is found, then it is returned. If no
5510** such file descriptor is located, -1 is returned.
5511*/
dane946c392009-08-22 11:39:46 +00005512static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5513 UnixUnusedFd *pUnused = 0;
5514
5515 /* Do not search for an unused file descriptor on vxworks. Not because
5516 ** vxworks would not benefit from the change (it might, we're not sure),
5517 ** but because no way to test it is currently available. It is better
5518 ** not to risk breaking vxworks support for the sake of such an obscure
5519 ** feature. */
5520#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005521 struct stat sStat; /* Results of stat() call */
5522
5523 /* A stat() call may fail for various reasons. If this happens, it is
5524 ** almost certain that an open() call on the same path will also fail.
5525 ** For this reason, if an error occurs in the stat() call here, it is
5526 ** ignored and -1 is returned. The caller will try to open a new file
5527 ** descriptor on the same path, fail, and return an error to SQLite.
5528 **
5529 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005530 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005531 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005532 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005533
5534 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005535 pInode = inodeList;
5536 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5537 || pInode->fileId.ino!=sStat.st_ino) ){
5538 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005539 }
drh8af6c222010-05-14 12:43:01 +00005540 if( pInode ){
dane946c392009-08-22 11:39:46 +00005541 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005542 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005543 pUnused = *pp;
5544 if( pUnused ){
5545 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005546 }
5547 }
5548 unixLeaveMutex();
5549 }
dane946c392009-08-22 11:39:46 +00005550#endif /* if !OS_VXWORKS */
5551 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005552}
danielk197717b90b52008-06-06 11:11:25 +00005553
5554/*
danddb0ac42010-07-14 14:48:58 +00005555** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005556** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005557** and a value suitable for passing as the third argument to open(2) is
5558** written to *pMode. If an IO error occurs, an SQLite error code is
5559** returned and the value of *pMode is not modified.
5560**
peter.d.reid60ec9142014-09-06 16:39:46 +00005561** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005562** an indication to robust_open() to create the file using
5563** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5564** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005565** this function queries the file-system for the permissions on the
5566** corresponding database file and sets *pMode to this value. Whenever
5567** possible, WAL and journal files are created using the same permissions
5568** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005569**
5570** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5571** original filename is unavailable. But 8_3_NAMES is only used for
5572** FAT filesystems and permissions do not matter there, so just use
5573** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005574*/
5575static int findCreateFileMode(
5576 const char *zPath, /* Path of file (possibly) being created */
5577 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005578 mode_t *pMode, /* OUT: Permissions to open file with */
5579 uid_t *pUid, /* OUT: uid to set on the file */
5580 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005581){
5582 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005583 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005584 *pUid = 0;
5585 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005586 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005587 char zDb[MAX_PATHNAME+1]; /* Database file path */
5588 int nDb; /* Number of valid bytes in zDb */
5589 struct stat sStat; /* Output of stat() on database file */
5590
dana0c989d2010-11-05 18:07:37 +00005591 /* zPath is a path to a WAL or journal file. The following block derives
5592 ** the path to the associated database file from zPath. This block handles
5593 ** the following naming conventions:
5594 **
5595 ** "<path to db>-journal"
5596 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005597 ** "<path to db>-journalNN"
5598 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005599 **
drhd337c5b2011-10-20 18:23:35 +00005600 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005601 ** used by the test_multiplex.c module.
5602 */
5603 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005604#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005605 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005606 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005607#else
5608 while( zPath[nDb]!='-' ){
5609 assert( nDb>0 );
5610 assert( zPath[nDb]!='\n' );
5611 nDb--;
5612 }
5613#endif
danddb0ac42010-07-14 14:48:58 +00005614 memcpy(zDb, zPath, nDb);
5615 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005616
drh58384f12011-07-28 00:14:45 +00005617 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005618 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005619 *pUid = sStat.st_uid;
5620 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005621 }else{
5622 rc = SQLITE_IOERR_FSTAT;
5623 }
5624 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5625 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005626 }
5627 return rc;
5628}
5629
5630/*
danielk1977ad94b582007-08-20 06:44:22 +00005631** Open the file zPath.
5632**
danielk1977b4b47412007-08-17 15:53:36 +00005633** Previously, the SQLite OS layer used three functions in place of this
5634** one:
5635**
5636** sqlite3OsOpenReadWrite();
5637** sqlite3OsOpenReadOnly();
5638** sqlite3OsOpenExclusive();
5639**
5640** These calls correspond to the following combinations of flags:
5641**
5642** ReadWrite() -> (READWRITE | CREATE)
5643** ReadOnly() -> (READONLY)
5644** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5645**
5646** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5647** true, the file was configured to be automatically deleted when the
5648** file handle closed. To achieve the same effect using this new
5649** interface, add the DELETEONCLOSE flag to those specified above for
5650** OpenExclusive().
5651*/
5652static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005653 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5654 const char *zPath, /* Pathname of file to be opened */
5655 sqlite3_file *pFile, /* The file descriptor to be filled in */
5656 int flags, /* Input flags to control the opening */
5657 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005658){
dan08da86a2009-08-21 17:18:03 +00005659 unixFile *p = (unixFile *)pFile;
5660 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005661 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005662 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005663 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005664 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005665 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005666
5667 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5668 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5669 int isCreate = (flags & SQLITE_OPEN_CREATE);
5670 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5671 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005672#if SQLITE_ENABLE_LOCKING_STYLE
5673 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5674#endif
drh3d4435b2011-08-26 20:55:50 +00005675#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5676 struct statfs fsInfo;
5677#endif
danielk1977b4b47412007-08-17 15:53:36 +00005678
danielk1977fee2d252007-08-18 10:59:19 +00005679 /* If creating a master or main-file journal, this function will open
5680 ** a file-descriptor on the directory too. The first time unixSync()
5681 ** is called the directory file descriptor will be fsync()ed and close()d.
5682 */
drh0059eae2011-08-08 23:48:40 +00005683 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005684 eType==SQLITE_OPEN_MASTER_JOURNAL
5685 || eType==SQLITE_OPEN_MAIN_JOURNAL
5686 || eType==SQLITE_OPEN_WAL
5687 ));
danielk1977fee2d252007-08-18 10:59:19 +00005688
danielk197717b90b52008-06-06 11:11:25 +00005689 /* If argument zPath is a NULL pointer, this function is required to open
5690 ** a temporary file. Use this buffer to store the file name in.
5691 */
drhc02a43a2012-01-10 23:18:38 +00005692 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005693 const char *zName = zPath;
5694
danielk1977fee2d252007-08-18 10:59:19 +00005695 /* Check the following statements are true:
5696 **
5697 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5698 ** (b) if CREATE is set, then READWRITE must also be set, and
5699 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005700 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005701 */
danielk1977b4b47412007-08-17 15:53:36 +00005702 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005703 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005704 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005705 assert(isDelete==0 || isCreate);
5706
danddb0ac42010-07-14 14:48:58 +00005707 /* The main DB, main journal, WAL file and master journal are never
5708 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005709 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5710 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5711 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005712 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005713
danielk1977fee2d252007-08-18 10:59:19 +00005714 /* Assert that the upper layer has set one of the "file-type" flags. */
5715 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5716 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5717 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005718 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005719 );
5720
drhb00d8622014-01-01 15:18:36 +00005721 /* Detect a pid change and reset the PRNG. There is a race condition
5722 ** here such that two or more threads all trying to open databases at
5723 ** the same instant might all reset the PRNG. But multiple resets
5724 ** are harmless.
5725 */
drh91eb93c2015-03-03 19:56:20 +00005726 if( randomnessPid!=osGetpid() ){
5727 randomnessPid = osGetpid();
drhb00d8622014-01-01 15:18:36 +00005728 sqlite3_randomness(0,0);
5729 }
5730
dan08da86a2009-08-21 17:18:03 +00005731 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005732
dan08da86a2009-08-21 17:18:03 +00005733 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005734 UnixUnusedFd *pUnused;
5735 pUnused = findReusableFd(zName, flags);
5736 if( pUnused ){
5737 fd = pUnused->fd;
5738 }else{
dan6aa657f2009-08-24 18:57:58 +00005739 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005740 if( !pUnused ){
5741 return SQLITE_NOMEM;
5742 }
5743 }
5744 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005745
5746 /* Database filenames are double-zero terminated if they are not
5747 ** URIs with parameters. Hence, they can always be passed into
5748 ** sqlite3_uri_parameter(). */
5749 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5750
dan08da86a2009-08-21 17:18:03 +00005751 }else if( !zName ){
5752 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005753 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005754 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005755 if( rc!=SQLITE_OK ){
5756 return rc;
5757 }
5758 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005759
5760 /* Generated temporary filenames are always double-zero terminated
5761 ** for use by sqlite3_uri_parameter(). */
5762 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005763 }
5764
dan08da86a2009-08-21 17:18:03 +00005765 /* Determine the value of the flags parameter passed to POSIX function
5766 ** open(). These must be calculated even if open() is not called, as
5767 ** they may be stored as part of the file handle and used by the
5768 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005769 if( isReadonly ) openFlags |= O_RDONLY;
5770 if( isReadWrite ) openFlags |= O_RDWR;
5771 if( isCreate ) openFlags |= O_CREAT;
5772 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5773 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005774
danielk1977b4b47412007-08-17 15:53:36 +00005775 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005776 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005777 uid_t uid; /* Userid for the file */
5778 gid_t gid; /* Groupid for the file */
5779 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005780 if( rc!=SQLITE_OK ){
5781 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005782 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005783 return rc;
5784 }
drhad4f1e52011-03-04 15:43:57 +00005785 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005786 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005787 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5788 /* Failed to open the file for read/write access. Try read-only. */
5789 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005790 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005791 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005792 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005793 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005794 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005795 }
5796 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005797 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005798 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005799 }
drhac7c3ac2012-02-11 19:23:48 +00005800
5801 /* If this process is running as root and if creating a new rollback
5802 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005803 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005804 */
5805 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005806 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005807 }
danielk1977b4b47412007-08-17 15:53:36 +00005808 }
dan08da86a2009-08-21 17:18:03 +00005809 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005810 if( pOutFlags ){
5811 *pOutFlags = flags;
5812 }
5813
dane946c392009-08-22 11:39:46 +00005814 if( p->pUnused ){
5815 p->pUnused->fd = fd;
5816 p->pUnused->flags = flags;
5817 }
5818
danielk1977b4b47412007-08-17 15:53:36 +00005819 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005820#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005821 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005822#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5823 zPath = sqlite3_mprintf("%s", zName);
5824 if( zPath==0 ){
5825 robust_close(p, fd, __LINE__);
5826 return SQLITE_NOMEM;
5827 }
chw97185482008-11-17 08:05:31 +00005828#else
drh036ac7f2011-08-08 23:18:05 +00005829 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005830#endif
danielk1977b4b47412007-08-17 15:53:36 +00005831 }
drh41022642008-11-21 00:24:42 +00005832#if SQLITE_ENABLE_LOCKING_STYLE
5833 else{
dan08da86a2009-08-21 17:18:03 +00005834 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005835 }
5836#endif
5837
drhda0e7682008-07-30 15:27:54 +00005838 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005839
drh7ed97b92010-01-20 13:07:21 +00005840
5841#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005842 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005843 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005844 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005845 return SQLITE_IOERR_ACCESS;
5846 }
5847 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5848 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5849 }
drh4bf66fd2015-02-19 02:43:02 +00005850 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5851 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5852 }
drh7ed97b92010-01-20 13:07:21 +00005853#endif
drhc02a43a2012-01-10 23:18:38 +00005854
5855 /* Set up appropriate ctrlFlags */
5856 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5857 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5858 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5859 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5860 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5861
drh7ed97b92010-01-20 13:07:21 +00005862#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005863#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005864 isAutoProxy = 1;
5865#endif
5866 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005867 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5868 int useProxy = 0;
5869
dan08da86a2009-08-21 17:18:03 +00005870 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5871 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005872 if( envforce!=NULL ){
5873 useProxy = atoi(envforce)>0;
5874 }else{
aswiftaebf4132008-11-21 00:10:35 +00005875 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5876 }
5877 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005878 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005879 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005880 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005881 if( rc!=SQLITE_OK ){
5882 /* Use unixClose to clean up the resources added in fillInUnixFile
5883 ** and clear all the structure's references. Specifically,
5884 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5885 */
5886 unixClose(pFile);
5887 return rc;
5888 }
aswiftaebf4132008-11-21 00:10:35 +00005889 }
dane946c392009-08-22 11:39:46 +00005890 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005891 }
5892 }
5893#endif
5894
drhc02a43a2012-01-10 23:18:38 +00005895 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5896
dane946c392009-08-22 11:39:46 +00005897open_finished:
5898 if( rc!=SQLITE_OK ){
5899 sqlite3_free(p->pUnused);
5900 }
5901 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005902}
5903
dane946c392009-08-22 11:39:46 +00005904
danielk1977b4b47412007-08-17 15:53:36 +00005905/*
danielk1977fee2d252007-08-18 10:59:19 +00005906** Delete the file at zPath. If the dirSync argument is true, fsync()
5907** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005908*/
drh6b9d6dd2008-12-03 19:34:47 +00005909static int unixDelete(
5910 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5911 const char *zPath, /* Name of file to be deleted */
5912 int dirSync /* If true, fsync() directory after deleting file */
5913){
danielk1977fee2d252007-08-18 10:59:19 +00005914 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005915 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005916 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005917 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005918 if( errno==ENOENT
5919#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005920 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005921#endif
5922 ){
dan9fc5b4a2012-11-09 20:17:26 +00005923 rc = SQLITE_IOERR_DELETE_NOENT;
5924 }else{
drhb4308162012-11-09 21:40:02 +00005925 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005926 }
drhb4308162012-11-09 21:40:02 +00005927 return rc;
drh5d4feff2010-07-14 01:45:22 +00005928 }
danielk1977d39fa702008-10-16 13:27:40 +00005929#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005930 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005931 int fd;
drh90315a22011-08-10 01:52:12 +00005932 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005933 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005934#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005935 if( fsync(fd)==-1 )
5936#else
5937 if( fsync(fd) )
5938#endif
5939 {
dane18d4952011-02-21 11:46:24 +00005940 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005941 }
drh0e9365c2011-03-02 02:08:13 +00005942 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005943 }else if( rc==SQLITE_CANTOPEN ){
5944 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005945 }
5946 }
danielk1977d138dd82008-10-15 16:02:48 +00005947#endif
danielk1977fee2d252007-08-18 10:59:19 +00005948 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005949}
5950
danielk197790949c22007-08-17 16:50:38 +00005951/*
mistachkin48864df2013-03-21 21:20:32 +00005952** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005953** test performed depends on the value of flags:
5954**
5955** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5956** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5957** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5958**
5959** Otherwise return 0.
5960*/
danielk1977861f7452008-06-05 11:39:11 +00005961static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005962 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5963 const char *zPath, /* Path of the file to examine */
5964 int flags, /* What do we want to learn about the zPath file? */
5965 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005966){
rse25c0d1a2007-09-20 08:38:14 +00005967 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005968 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005969 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005970 switch( flags ){
5971 case SQLITE_ACCESS_EXISTS:
5972 amode = F_OK;
5973 break;
5974 case SQLITE_ACCESS_READWRITE:
5975 amode = W_OK|R_OK;
5976 break;
drh50d3f902007-08-27 21:10:36 +00005977 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005978 amode = R_OK;
5979 break;
5980
5981 default:
5982 assert(!"Invalid flags argument");
5983 }
drh99ab3b12011-03-02 15:09:07 +00005984 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005985 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5986 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005987 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005988 *pResOut = 0;
5989 }
5990 }
danielk1977861f7452008-06-05 11:39:11 +00005991 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005992}
5993
danielk1977b4b47412007-08-17 15:53:36 +00005994
5995/*
5996** Turn a relative pathname into a full pathname. The relative path
5997** is stored as a nul-terminated string in the buffer pointed to by
5998** zPath.
5999**
6000** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6001** (in this case, MAX_PATHNAME bytes). The full-path is written to
6002** this buffer before returning.
6003*/
danielk1977adfb9b02007-09-17 07:02:56 +00006004static int unixFullPathname(
6005 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6006 const char *zPath, /* Possibly relative input path */
6007 int nOut, /* Size of output buffer in bytes */
6008 char *zOut /* Output buffer */
6009){
danielk1977843e65f2007-09-01 16:16:15 +00006010
6011 /* It's odd to simulate an io-error here, but really this is just
6012 ** using the io-error infrastructure to test that SQLite handles this
6013 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006014 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006015 */
6016 SimulateIOError( return SQLITE_ERROR );
6017
drh153c62c2007-08-24 03:51:33 +00006018 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006019 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006020
drh3c7f2dc2007-12-06 13:26:20 +00006021 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006022 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006023 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006024 }else{
6025 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006026 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006027 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006028 }
drhea678832008-12-10 19:26:22 +00006029 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006030 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006031 }
6032 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006033}
6034
drh0ccebe72005-06-07 22:22:50 +00006035
drh761df872006-12-21 01:29:22 +00006036#ifndef SQLITE_OMIT_LOAD_EXTENSION
6037/*
6038** Interfaces for opening a shared library, finding entry points
6039** within the shared library, and closing the shared library.
6040*/
6041#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006042static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6043 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006044 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6045}
danielk197795c8a542007-09-01 06:51:27 +00006046
6047/*
6048** SQLite calls this function immediately after a call to unixDlSym() or
6049** unixDlOpen() fails (returns a null pointer). If a more detailed error
6050** message is available, it is written to zBufOut. If no error message
6051** is available, zBufOut is left unmodified and SQLite uses a default
6052** error message.
6053*/
danielk1977397d65f2008-11-19 11:35:39 +00006054static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006055 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006056 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006057 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006058 zErr = dlerror();
6059 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006060 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006061 }
drh6c7d5c52008-11-21 20:32:33 +00006062 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006063}
drh1875f7a2008-12-08 18:19:17 +00006064static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6065 /*
6066 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6067 ** cast into a pointer to a function. And yet the library dlsym() routine
6068 ** returns a void* which is really a pointer to a function. So how do we
6069 ** use dlsym() with -pedantic-errors?
6070 **
6071 ** Variable x below is defined to be a pointer to a function taking
6072 ** parameters void* and const char* and returning a pointer to a function.
6073 ** We initialize x by assigning it a pointer to the dlsym() function.
6074 ** (That assignment requires a cast.) Then we call the function that
6075 ** x points to.
6076 **
6077 ** This work-around is unlikely to work correctly on any system where
6078 ** you really cannot cast a function pointer into void*. But then, on the
6079 ** other hand, dlsym() will not work on such a system either, so we have
6080 ** not really lost anything.
6081 */
6082 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006083 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006084 x = (void(*(*)(void*,const char*))(void))dlsym;
6085 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006086}
danielk1977397d65f2008-11-19 11:35:39 +00006087static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6088 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006089 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006090}
danielk1977b4b47412007-08-17 15:53:36 +00006091#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6092 #define unixDlOpen 0
6093 #define unixDlError 0
6094 #define unixDlSym 0
6095 #define unixDlClose 0
6096#endif
6097
6098/*
danielk197790949c22007-08-17 16:50:38 +00006099** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006100*/
danielk1977397d65f2008-11-19 11:35:39 +00006101static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6102 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006103 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006104
drhbbd42a62004-05-22 17:41:58 +00006105 /* We have to initialize zBuf to prevent valgrind from reporting
6106 ** errors. The reports issued by valgrind are incorrect - we would
6107 ** prefer that the randomness be increased by making use of the
6108 ** uninitialized space in zBuf - but valgrind errors tend to worry
6109 ** some users. Rather than argue, it seems easier just to initialize
6110 ** the whole array and silence valgrind, even if that means less randomness
6111 ** in the random seed.
6112 **
6113 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006114 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006115 ** tests repeatable.
6116 */
danielk1977b4b47412007-08-17 15:53:36 +00006117 memset(zBuf, 0, nBuf);
drh91eb93c2015-03-03 19:56:20 +00006118 randomnessPid = osGetpid();
drhbbd42a62004-05-22 17:41:58 +00006119#if !defined(SQLITE_TEST)
6120 {
drhb00d8622014-01-01 15:18:36 +00006121 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006122 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006123 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006124 time_t t;
6125 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006126 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006127 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6128 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6129 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006130 }else{
drhc18b4042012-02-10 03:10:27 +00006131 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006132 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006133 }
drhbbd42a62004-05-22 17:41:58 +00006134 }
6135#endif
drh72cbd072008-10-14 17:58:38 +00006136 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006137}
6138
danielk1977b4b47412007-08-17 15:53:36 +00006139
drhbbd42a62004-05-22 17:41:58 +00006140/*
6141** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006142** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006143** The return value is the number of microseconds of sleep actually
6144** requested from the underlying operating system, a number which
6145** might be greater than or equal to the argument, but not less
6146** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006147*/
danielk1977397d65f2008-11-19 11:35:39 +00006148static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006149#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006150 struct timespec sp;
6151
6152 sp.tv_sec = microseconds / 1000000;
6153 sp.tv_nsec = (microseconds % 1000000) * 1000;
6154 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006155 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006156 return microseconds;
6157#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006158 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006159 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006160 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006161#else
danielk1977b4b47412007-08-17 15:53:36 +00006162 int seconds = (microseconds+999999)/1000000;
6163 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006164 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006165 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006166#endif
drh88f474a2006-01-02 20:00:12 +00006167}
6168
6169/*
drh6b9d6dd2008-12-03 19:34:47 +00006170** The following variable, if set to a non-zero value, is interpreted as
6171** the number of seconds since 1970 and is used to set the result of
6172** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006173*/
6174#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006175int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006176#endif
6177
6178/*
drhb7e8ea22010-05-03 14:32:30 +00006179** Find the current time (in Universal Coordinated Time). Write into *piNow
6180** the current time and date as a Julian Day number times 86_400_000. In
6181** other words, write into *piNow the number of milliseconds since the Julian
6182** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6183** proleptic Gregorian calendar.
6184**
drh31702252011-10-12 23:13:43 +00006185** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6186** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006187*/
6188static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6189 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006190 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006191#if defined(NO_GETTOD)
6192 time_t t;
6193 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006194 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006195#elif OS_VXWORKS
6196 struct timespec sNow;
6197 clock_gettime(CLOCK_REALTIME, &sNow);
6198 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6199#else
6200 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006201 if( gettimeofday(&sNow, 0)==0 ){
6202 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6203 }else{
6204 rc = SQLITE_ERROR;
6205 }
drhb7e8ea22010-05-03 14:32:30 +00006206#endif
6207
6208#ifdef SQLITE_TEST
6209 if( sqlite3_current_time ){
6210 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6211 }
6212#endif
6213 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006214 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006215}
6216
6217/*
drhbbd42a62004-05-22 17:41:58 +00006218** Find the current time (in Universal Coordinated Time). Write the
6219** current time and date as a Julian Day number into *prNow and
6220** return 0. Return 1 if the time and date cannot be found.
6221*/
danielk1977397d65f2008-11-19 11:35:39 +00006222static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006223 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006224 int rc;
drhff828942010-06-26 21:34:06 +00006225 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006226 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006227 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006228 return rc;
drhbbd42a62004-05-22 17:41:58 +00006229}
danielk1977b4b47412007-08-17 15:53:36 +00006230
drh6b9d6dd2008-12-03 19:34:47 +00006231/*
6232** We added the xGetLastError() method with the intention of providing
6233** better low-level error messages when operating-system problems come up
6234** during SQLite operation. But so far, none of that has been implemented
6235** in the core. So this routine is never called. For now, it is merely
6236** a place-holder.
6237*/
danielk1977397d65f2008-11-19 11:35:39 +00006238static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6239 UNUSED_PARAMETER(NotUsed);
6240 UNUSED_PARAMETER(NotUsed2);
6241 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006242 return 0;
6243}
6244
drhf2424c52010-04-26 00:04:55 +00006245
6246/*
drh734c9862008-11-28 15:37:20 +00006247************************ End of sqlite3_vfs methods ***************************
6248******************************************************************************/
6249
drh715ff302008-12-03 22:32:44 +00006250/******************************************************************************
6251************************** Begin Proxy Locking ********************************
6252**
6253** Proxy locking is a "uber-locking-method" in this sense: It uses the
6254** other locking methods on secondary lock files. Proxy locking is a
6255** meta-layer over top of the primitive locking implemented above. For
6256** this reason, the division that implements of proxy locking is deferred
6257** until late in the file (here) after all of the other I/O methods have
6258** been defined - so that the primitive locking methods are available
6259** as services to help with the implementation of proxy locking.
6260**
6261****
6262**
6263** The default locking schemes in SQLite use byte-range locks on the
6264** database file to coordinate safe, concurrent access by multiple readers
6265** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6266** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6267** as POSIX read & write locks over fixed set of locations (via fsctl),
6268** on AFP and SMB only exclusive byte-range locks are available via fsctl
6269** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6270** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6271** address in the shared range is taken for a SHARED lock, the entire
6272** shared range is taken for an EXCLUSIVE lock):
6273**
drhf2f105d2012-08-20 15:53:54 +00006274** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006275** RESERVED_BYTE 0x40000001
6276** SHARED_RANGE 0x40000002 -> 0x40000200
6277**
6278** This works well on the local file system, but shows a nearly 100x
6279** slowdown in read performance on AFP because the AFP client disables
6280** the read cache when byte-range locks are present. Enabling the read
6281** cache exposes a cache coherency problem that is present on all OS X
6282** supported network file systems. NFS and AFP both observe the
6283** close-to-open semantics for ensuring cache coherency
6284** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6285** address the requirements for concurrent database access by multiple
6286** readers and writers
6287** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6288**
6289** To address the performance and cache coherency issues, proxy file locking
6290** changes the way database access is controlled by limiting access to a
6291** single host at a time and moving file locks off of the database file
6292** and onto a proxy file on the local file system.
6293**
6294**
6295** Using proxy locks
6296** -----------------
6297**
6298** C APIs
6299**
drh4bf66fd2015-02-19 02:43:02 +00006300** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006301** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006302** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6303** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006304**
6305**
6306** SQL pragmas
6307**
6308** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6309** PRAGMA [database.]lock_proxy_file
6310**
6311** Specifying ":auto:" means that if there is a conch file with a matching
6312** host ID in it, the proxy path in the conch file will be used, otherwise
6313** a proxy path based on the user's temp dir
6314** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6315** actual proxy file name is generated from the name and path of the
6316** database file. For example:
6317**
6318** For database path "/Users/me/foo.db"
6319** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6320**
6321** Once a lock proxy is configured for a database connection, it can not
6322** be removed, however it may be switched to a different proxy path via
6323** the above APIs (assuming the conch file is not being held by another
6324** connection or process).
6325**
6326**
6327** How proxy locking works
6328** -----------------------
6329**
6330** Proxy file locking relies primarily on two new supporting files:
6331**
6332** * conch file to limit access to the database file to a single host
6333** at a time
6334**
6335** * proxy file to act as a proxy for the advisory locks normally
6336** taken on the database
6337**
6338** The conch file - to use a proxy file, sqlite must first "hold the conch"
6339** by taking an sqlite-style shared lock on the conch file, reading the
6340** contents and comparing the host's unique host ID (see below) and lock
6341** proxy path against the values stored in the conch. The conch file is
6342** stored in the same directory as the database file and the file name
6343** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006344** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006345** host ID and/or proxy path, then the lock is escalated to an exclusive
6346** lock and the conch file contents is updated with the host ID and proxy
6347** path and the lock is downgraded to a shared lock again. If the conch
6348** is held by another process (with a shared lock), the exclusive lock
6349** will fail and SQLITE_BUSY is returned.
6350**
6351** The proxy file - a single-byte file used for all advisory file locks
6352** normally taken on the database file. This allows for safe sharing
6353** of the database file for multiple readers and writers on the same
6354** host (the conch ensures that they all use the same local lock file).
6355**
drh715ff302008-12-03 22:32:44 +00006356** Requesting the lock proxy does not immediately take the conch, it is
6357** only taken when the first request to lock database file is made.
6358** This matches the semantics of the traditional locking behavior, where
6359** opening a connection to a database file does not take a lock on it.
6360** The shared lock and an open file descriptor are maintained until
6361** the connection to the database is closed.
6362**
6363** The proxy file and the lock file are never deleted so they only need
6364** to be created the first time they are used.
6365**
6366** Configuration options
6367** ---------------------
6368**
6369** SQLITE_PREFER_PROXY_LOCKING
6370**
6371** Database files accessed on non-local file systems are
6372** automatically configured for proxy locking, lock files are
6373** named automatically using the same logic as
6374** PRAGMA lock_proxy_file=":auto:"
6375**
6376** SQLITE_PROXY_DEBUG
6377**
6378** Enables the logging of error messages during host id file
6379** retrieval and creation
6380**
drh715ff302008-12-03 22:32:44 +00006381** LOCKPROXYDIR
6382**
6383** Overrides the default directory used for lock proxy files that
6384** are named automatically via the ":auto:" setting
6385**
6386** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6387**
6388** Permissions to use when creating a directory for storing the
6389** lock proxy files, only used when LOCKPROXYDIR is not set.
6390**
6391**
6392** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6393** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6394** force proxy locking to be used for every database file opened, and 0
6395** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006396** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006397** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6398*/
6399
6400/*
6401** Proxy locking is only available on MacOSX
6402*/
drhd2cb50b2009-01-09 21:41:17 +00006403#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006404
drh715ff302008-12-03 22:32:44 +00006405/*
6406** The proxyLockingContext has the path and file structures for the remote
6407** and local proxy files in it
6408*/
6409typedef struct proxyLockingContext proxyLockingContext;
6410struct proxyLockingContext {
6411 unixFile *conchFile; /* Open conch file */
6412 char *conchFilePath; /* Name of the conch file */
6413 unixFile *lockProxy; /* Open proxy lock file */
6414 char *lockProxyPath; /* Name of the proxy lock file */
6415 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006416 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006417 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006418 void *oldLockingContext; /* Original lockingcontext to restore on close */
6419 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6420};
6421
drh7ed97b92010-01-20 13:07:21 +00006422/*
6423** The proxy lock file path for the database at dbPath is written into lPath,
6424** which must point to valid, writable memory large enough for a maxLen length
6425** file path.
drh715ff302008-12-03 22:32:44 +00006426*/
drh715ff302008-12-03 22:32:44 +00006427static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6428 int len;
6429 int dbLen;
6430 int i;
6431
6432#ifdef LOCKPROXYDIR
6433 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6434#else
6435# ifdef _CS_DARWIN_USER_TEMP_DIR
6436 {
drh7ed97b92010-01-20 13:07:21 +00006437 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006438 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh91eb93c2015-03-03 19:56:20 +00006439 lPath, errno, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006440 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006441 }
drh7ed97b92010-01-20 13:07:21 +00006442 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006443 }
6444# else
6445 len = strlcpy(lPath, "/tmp/", maxLen);
6446# endif
6447#endif
6448
6449 if( lPath[len-1]!='/' ){
6450 len = strlcat(lPath, "/", maxLen);
6451 }
6452
6453 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006454 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006455 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006456 char c = dbPath[i];
6457 lPath[i+len] = (c=='/')?'_':c;
6458 }
6459 lPath[i+len]='\0';
6460 strlcat(lPath, ":auto:", maxLen);
drh91eb93c2015-03-03 19:56:20 +00006461 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid()));
drh715ff302008-12-03 22:32:44 +00006462 return SQLITE_OK;
6463}
6464
drh7ed97b92010-01-20 13:07:21 +00006465/*
6466 ** Creates the lock file and any missing directories in lockPath
6467 */
6468static int proxyCreateLockPath(const char *lockPath){
6469 int i, len;
6470 char buf[MAXPATHLEN];
6471 int start = 0;
6472
6473 assert(lockPath!=NULL);
6474 /* try to create all the intermediate directories */
6475 len = (int)strlen(lockPath);
6476 buf[0] = lockPath[0];
6477 for( i=1; i<len; i++ ){
6478 if( lockPath[i] == '/' && (i - start > 0) ){
6479 /* only mkdir if leaf dir != "." or "/" or ".." */
6480 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6481 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6482 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006483 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006484 int err=errno;
6485 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006486 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006487 "'%s' proxy lock path=%s pid=%d\n",
drh91eb93c2015-03-03 19:56:20 +00006488 buf, strerror(err), lockPath, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006489 return err;
6490 }
6491 }
6492 }
6493 start=i+1;
6494 }
6495 buf[i] = lockPath[i];
6496 }
drh91eb93c2015-03-03 19:56:20 +00006497 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006498 return 0;
6499}
6500
drh715ff302008-12-03 22:32:44 +00006501/*
6502** Create a new VFS file descriptor (stored in memory obtained from
6503** sqlite3_malloc) and open the file named "path" in the file descriptor.
6504**
6505** The caller is responsible not only for closing the file descriptor
6506** but also for freeing the memory associated with the file descriptor.
6507*/
drh7ed97b92010-01-20 13:07:21 +00006508static int proxyCreateUnixFile(
6509 const char *path, /* path for the new unixFile */
6510 unixFile **ppFile, /* unixFile created and returned by ref */
6511 int islockfile /* if non zero missing dirs will be created */
6512) {
6513 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006514 unixFile *pNew;
6515 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006516 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006517 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006518 int terrno = 0;
6519 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006520
drh7ed97b92010-01-20 13:07:21 +00006521 /* 1. first try to open/create the file
6522 ** 2. if that fails, and this is a lock file (not-conch), try creating
6523 ** the parent directories and then try again.
6524 ** 3. if that fails, try to open the file read-only
6525 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6526 */
6527 pUnused = findReusableFd(path, openFlags);
6528 if( pUnused ){
6529 fd = pUnused->fd;
6530 }else{
6531 pUnused = sqlite3_malloc(sizeof(*pUnused));
6532 if( !pUnused ){
6533 return SQLITE_NOMEM;
6534 }
6535 }
6536 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006537 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006538 terrno = errno;
6539 if( fd<0 && errno==ENOENT && islockfile ){
6540 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006541 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006542 }
6543 }
6544 }
6545 if( fd<0 ){
6546 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006547 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006548 terrno = errno;
6549 }
6550 if( fd<0 ){
6551 if( islockfile ){
6552 return SQLITE_BUSY;
6553 }
6554 switch (terrno) {
6555 case EACCES:
6556 return SQLITE_PERM;
6557 case EIO:
6558 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6559 default:
drh9978c972010-02-23 17:36:32 +00006560 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006561 }
6562 }
6563
6564 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6565 if( pNew==NULL ){
6566 rc = SQLITE_NOMEM;
6567 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006568 }
6569 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006570 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006571 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006572 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006573 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006574 pUnused->fd = fd;
6575 pUnused->flags = openFlags;
6576 pNew->pUnused = pUnused;
6577
drhc02a43a2012-01-10 23:18:38 +00006578 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006579 if( rc==SQLITE_OK ){
6580 *ppFile = pNew;
6581 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006582 }
drh7ed97b92010-01-20 13:07:21 +00006583end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006584 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006585 sqlite3_free(pNew);
6586 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006587 return rc;
6588}
6589
drh7ed97b92010-01-20 13:07:21 +00006590#ifdef SQLITE_TEST
6591/* simulate multiple hosts by creating unique hostid file paths */
6592int sqlite3_hostid_num = 0;
6593#endif
6594
6595#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6596
drh0ab216a2010-07-02 17:10:40 +00006597/* Not always defined in the headers as it ought to be */
6598extern int gethostuuid(uuid_t id, const struct timespec *wait);
6599
drh7ed97b92010-01-20 13:07:21 +00006600/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6601** bytes of writable memory.
6602*/
6603static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006604 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6605 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh4bf66fd2015-02-19 02:43:02 +00006606# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
6607 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
drh29ecd8a2010-12-21 00:16:40 +00006608 {
drh4bf66fd2015-02-19 02:43:02 +00006609 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006610 if( gethostuuid(pHostID, &timeout) ){
6611 int err = errno;
6612 if( pError ){
6613 *pError = err;
6614 }
6615 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006616 }
drh7ed97b92010-01-20 13:07:21 +00006617 }
drh3d4435b2011-08-26 20:55:50 +00006618#else
6619 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006620#endif
drh7ed97b92010-01-20 13:07:21 +00006621#ifdef SQLITE_TEST
6622 /* simulate multiple hosts by creating unique hostid file paths */
6623 if( sqlite3_hostid_num != 0){
6624 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6625 }
6626#endif
6627
6628 return SQLITE_OK;
6629}
6630
6631/* The conch file contains the header, host id and lock file path
6632 */
6633#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6634#define PROXY_HEADERLEN 1 /* conch file header length */
6635#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6636#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6637
6638/*
6639** Takes an open conch file, copies the contents to a new path and then moves
6640** it back. The newly created file's file descriptor is assigned to the
6641** conch file structure and finally the original conch file descriptor is
6642** closed. Returns zero if successful.
6643*/
6644static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6645 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6646 unixFile *conchFile = pCtx->conchFile;
6647 char tPath[MAXPATHLEN];
6648 char buf[PROXY_MAXCONCHLEN];
6649 char *cPath = pCtx->conchFilePath;
6650 size_t readLen = 0;
6651 size_t pathLen = 0;
6652 char errmsg[64] = "";
6653 int fd = -1;
6654 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006655 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006656
6657 /* create a new path by replace the trailing '-conch' with '-break' */
6658 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6659 if( pathLen>MAXPATHLEN || pathLen<6 ||
6660 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006661 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006662 goto end_breaklock;
6663 }
6664 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006665 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006666 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006667 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006668 goto end_breaklock;
6669 }
6670 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006671 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006672 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006673 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006674 goto end_breaklock;
6675 }
drhe562be52011-03-02 18:01:10 +00006676 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006677 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006678 goto end_breaklock;
6679 }
6680 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006681 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006682 goto end_breaklock;
6683 }
6684 rc = 0;
6685 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006686 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006687 conchFile->h = fd;
6688 conchFile->openFlags = O_RDWR | O_CREAT;
6689
6690end_breaklock:
6691 if( rc ){
6692 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006693 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006694 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006695 }
6696 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6697 }
6698 return rc;
6699}
6700
6701/* Take the requested lock on the conch file and break a stale lock if the
6702** host id matches.
6703*/
6704static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6705 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6706 unixFile *conchFile = pCtx->conchFile;
6707 int rc = SQLITE_OK;
6708 int nTries = 0;
6709 struct timespec conchModTime;
6710
drh3d4435b2011-08-26 20:55:50 +00006711 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006712 do {
6713 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6714 nTries ++;
6715 if( rc==SQLITE_BUSY ){
6716 /* If the lock failed (busy):
6717 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6718 * 2nd try: fail if the mod time changed or host id is different, wait
6719 * 10 sec and try again
6720 * 3rd try: break the lock unless the mod time has changed.
6721 */
6722 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006723 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006724 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006725 return SQLITE_IOERR_LOCK;
6726 }
6727
6728 if( nTries==1 ){
6729 conchModTime = buf.st_mtimespec;
6730 usleep(500000); /* wait 0.5 sec and try the lock again*/
6731 continue;
6732 }
6733
6734 assert( nTries>1 );
6735 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6736 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6737 return SQLITE_BUSY;
6738 }
6739
6740 if( nTries==2 ){
6741 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006742 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006743 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006744 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006745 return SQLITE_IOERR_LOCK;
6746 }
6747 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6748 /* don't break the lock if the host id doesn't match */
6749 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6750 return SQLITE_BUSY;
6751 }
6752 }else{
6753 /* don't break the lock on short read or a version mismatch */
6754 return SQLITE_BUSY;
6755 }
6756 usleep(10000000); /* wait 10 sec and try the lock again */
6757 continue;
6758 }
6759
6760 assert( nTries==3 );
6761 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6762 rc = SQLITE_OK;
6763 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006764 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006765 }
6766 if( !rc ){
6767 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6768 }
6769 }
6770 }
6771 } while( rc==SQLITE_BUSY && nTries<3 );
6772
6773 return rc;
6774}
6775
6776/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006777** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6778** lockPath means that the lockPath in the conch file will be used if the
6779** host IDs match, or a new lock path will be generated automatically
6780** and written to the conch file.
6781*/
6782static int proxyTakeConch(unixFile *pFile){
6783 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6784
drh7ed97b92010-01-20 13:07:21 +00006785 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006786 return SQLITE_OK;
6787 }else{
6788 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006789 uuid_t myHostID;
6790 int pError = 0;
6791 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006792 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006793 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006794 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006795 int createConch = 0;
6796 int hostIdMatch = 0;
6797 int readLen = 0;
6798 int tryOldLockPath = 0;
6799 int forceNewLockPath = 0;
6800
drh308c2a52010-05-14 11:30:18 +00006801 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006802 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6803 osGetpid()));
drh715ff302008-12-03 22:32:44 +00006804
drh7ed97b92010-01-20 13:07:21 +00006805 rc = proxyGetHostID(myHostID, &pError);
6806 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006807 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006808 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006809 }
drh7ed97b92010-01-20 13:07:21 +00006810 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006811 if( rc!=SQLITE_OK ){
6812 goto end_takeconch;
6813 }
drh7ed97b92010-01-20 13:07:21 +00006814 /* read the existing conch file */
6815 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6816 if( readLen<0 ){
6817 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006818 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006819 rc = SQLITE_IOERR_READ;
6820 goto end_takeconch;
6821 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6822 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6823 /* a short read or version format mismatch means we need to create a new
6824 ** conch file.
6825 */
6826 createConch = 1;
6827 }
6828 /* if the host id matches and the lock path already exists in the conch
6829 ** we'll try to use the path there, if we can't open that path, we'll
6830 ** retry with a new auto-generated path
6831 */
6832 do { /* in case we need to try again for an :auto: named lock file */
6833
6834 if( !createConch && !forceNewLockPath ){
6835 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6836 PROXY_HOSTIDLEN);
6837 /* if the conch has data compare the contents */
6838 if( !pCtx->lockProxyPath ){
6839 /* for auto-named local lock file, just check the host ID and we'll
6840 ** use the local lock file path that's already in there
6841 */
6842 if( hostIdMatch ){
6843 size_t pathLen = (readLen - PROXY_PATHINDEX);
6844
6845 if( pathLen>=MAXPATHLEN ){
6846 pathLen=MAXPATHLEN-1;
6847 }
6848 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6849 lockPath[pathLen] = 0;
6850 tempLockPath = lockPath;
6851 tryOldLockPath = 1;
6852 /* create a copy of the lock path if the conch is taken */
6853 goto end_takeconch;
6854 }
6855 }else if( hostIdMatch
6856 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6857 readLen-PROXY_PATHINDEX)
6858 ){
6859 /* conch host and lock path match */
6860 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006861 }
drh7ed97b92010-01-20 13:07:21 +00006862 }
6863
6864 /* if the conch isn't writable and doesn't match, we can't take it */
6865 if( (conchFile->openFlags&O_RDWR) == 0 ){
6866 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006867 goto end_takeconch;
6868 }
drh7ed97b92010-01-20 13:07:21 +00006869
6870 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006871 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006872 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6873 tempLockPath = lockPath;
6874 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006875 }
drh7ed97b92010-01-20 13:07:21 +00006876
6877 /* update conch with host and path (this will fail if other process
6878 ** has a shared lock already), if the host id matches, use the big
6879 ** stick.
drh715ff302008-12-03 22:32:44 +00006880 */
drh7ed97b92010-01-20 13:07:21 +00006881 futimes(conchFile->h, NULL);
6882 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006883 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006884 /* We are trying for an exclusive lock but another thread in this
6885 ** same process is still holding a shared lock. */
6886 rc = SQLITE_BUSY;
6887 } else {
6888 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006889 }
drh715ff302008-12-03 22:32:44 +00006890 }else{
drh4bf66fd2015-02-19 02:43:02 +00006891 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006892 }
drh7ed97b92010-01-20 13:07:21 +00006893 if( rc==SQLITE_OK ){
6894 char writeBuffer[PROXY_MAXCONCHLEN];
6895 int writeSize = 0;
6896
6897 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6898 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6899 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006900 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6901 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006902 }else{
6903 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6904 }
6905 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006906 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006907 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6908 fsync(conchFile->h);
6909 /* If we created a new conch file (not just updated the contents of a
6910 ** valid conch file), try to match the permissions of the database
6911 */
6912 if( rc==SQLITE_OK && createConch ){
6913 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006914 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006915 if( err==0 ){
6916 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6917 S_IROTH|S_IWOTH);
6918 /* try to match the database file R/W permissions, ignore failure */
6919#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006920 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006921#else
drhff812312011-02-23 13:33:46 +00006922 do{
drhe562be52011-03-02 18:01:10 +00006923 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006924 }while( rc==(-1) && errno==EINTR );
6925 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006926 int code = errno;
6927 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6928 cmode, code, strerror(code));
6929 } else {
6930 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6931 }
6932 }else{
6933 int code = errno;
6934 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6935 err, code, strerror(code));
6936#endif
6937 }
drh715ff302008-12-03 22:32:44 +00006938 }
6939 }
drh7ed97b92010-01-20 13:07:21 +00006940 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6941
6942 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006943 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006944 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006945 int fd;
drh7ed97b92010-01-20 13:07:21 +00006946 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006947 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006948 }
6949 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006950 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006951 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006952 if( fd>=0 ){
6953 pFile->h = fd;
6954 }else{
drh9978c972010-02-23 17:36:32 +00006955 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006956 during locking */
6957 }
6958 }
6959 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6960 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6961 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6962 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6963 /* we couldn't create the proxy lock file with the old lock file path
6964 ** so try again via auto-naming
6965 */
6966 forceNewLockPath = 1;
6967 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006968 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006969 }
6970 }
6971 if( rc==SQLITE_OK ){
6972 /* Need to make a copy of path if we extracted the value
6973 ** from the conch file or the path was allocated on the stack
6974 */
6975 if( tempLockPath ){
6976 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6977 if( !pCtx->lockProxyPath ){
6978 rc = SQLITE_NOMEM;
6979 }
6980 }
6981 }
6982 if( rc==SQLITE_OK ){
6983 pCtx->conchHeld = 1;
6984
6985 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6986 afpLockingContext *afpCtx;
6987 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6988 afpCtx->dbPath = pCtx->lockProxyPath;
6989 }
6990 } else {
6991 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6992 }
drh308c2a52010-05-14 11:30:18 +00006993 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6994 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006995 return rc;
drh308c2a52010-05-14 11:30:18 +00006996 } while (1); /* in case we need to retry the :auto: lock file -
6997 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00006998 }
6999}
7000
7001/*
7002** If pFile holds a lock on a conch file, then release that lock.
7003*/
7004static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007005 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007006 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7007 unixFile *conchFile; /* Name of the conch file */
7008
7009 pCtx = (proxyLockingContext *)pFile->lockingContext;
7010 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007011 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007012 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh91eb93c2015-03-03 19:56:20 +00007013 osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00007014 if( pCtx->conchHeld>0 ){
7015 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7016 }
drh715ff302008-12-03 22:32:44 +00007017 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007018 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7019 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007020 return rc;
7021}
7022
7023/*
7024** Given the name of a database file, compute the name of its conch file.
7025** Store the conch filename in memory obtained from sqlite3_malloc().
7026** Make *pConchPath point to the new name. Return SQLITE_OK on success
7027** or SQLITE_NOMEM if unable to obtain memory.
7028**
7029** The caller is responsible for ensuring that the allocated memory
7030** space is eventually freed.
7031**
7032** *pConchPath is set to NULL if a memory allocation error occurs.
7033*/
7034static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7035 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007036 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007037 char *conchPath; /* buffer in which to construct conch name */
7038
7039 /* Allocate space for the conch filename and initialize the name to
7040 ** the name of the original database file. */
7041 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7042 if( conchPath==0 ){
7043 return SQLITE_NOMEM;
7044 }
7045 memcpy(conchPath, dbPath, len+1);
7046
7047 /* now insert a "." before the last / character */
7048 for( i=(len-1); i>=0; i-- ){
7049 if( conchPath[i]=='/' ){
7050 i++;
7051 break;
7052 }
7053 }
7054 conchPath[i]='.';
7055 while ( i<len ){
7056 conchPath[i+1]=dbPath[i];
7057 i++;
7058 }
7059
7060 /* append the "-conch" suffix to the file */
7061 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007062 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007063
7064 return SQLITE_OK;
7065}
7066
7067
7068/* Takes a fully configured proxy locking-style unix file and switches
7069** the local lock file path
7070*/
7071static int switchLockProxyPath(unixFile *pFile, const char *path) {
7072 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7073 char *oldPath = pCtx->lockProxyPath;
7074 int rc = SQLITE_OK;
7075
drh308c2a52010-05-14 11:30:18 +00007076 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007077 return SQLITE_BUSY;
7078 }
7079
7080 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7081 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7082 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7083 return SQLITE_OK;
7084 }else{
7085 unixFile *lockProxy = pCtx->lockProxy;
7086 pCtx->lockProxy=NULL;
7087 pCtx->conchHeld = 0;
7088 if( lockProxy!=NULL ){
7089 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7090 if( rc ) return rc;
7091 sqlite3_free(lockProxy);
7092 }
7093 sqlite3_free(oldPath);
7094 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7095 }
7096
7097 return rc;
7098}
7099
7100/*
7101** pFile is a file that has been opened by a prior xOpen call. dbPath
7102** is a string buffer at least MAXPATHLEN+1 characters in size.
7103**
7104** This routine find the filename associated with pFile and writes it
7105** int dbPath.
7106*/
7107static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007108#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007109 if( pFile->pMethod == &afpIoMethods ){
7110 /* afp style keeps a reference to the db path in the filePath field
7111 ** of the struct */
drhea678832008-12-10 19:26:22 +00007112 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007113 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7114 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007115 } else
drh715ff302008-12-03 22:32:44 +00007116#endif
7117 if( pFile->pMethod == &dotlockIoMethods ){
7118 /* dot lock style uses the locking context to store the dot lock
7119 ** file path */
7120 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7121 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7122 }else{
7123 /* all other styles use the locking context to store the db file path */
7124 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007125 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007126 }
7127 return SQLITE_OK;
7128}
7129
7130/*
7131** Takes an already filled in unix file and alters it so all file locking
7132** will be performed on the local proxy lock file. The following fields
7133** are preserved in the locking context so that they can be restored and
7134** the unix structure properly cleaned up at close time:
7135** ->lockingContext
7136** ->pMethod
7137*/
7138static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7139 proxyLockingContext *pCtx;
7140 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7141 char *lockPath=NULL;
7142 int rc = SQLITE_OK;
7143
drh308c2a52010-05-14 11:30:18 +00007144 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007145 return SQLITE_BUSY;
7146 }
7147 proxyGetDbPathForUnixFile(pFile, dbPath);
7148 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7149 lockPath=NULL;
7150 }else{
7151 lockPath=(char *)path;
7152 }
7153
drh308c2a52010-05-14 11:30:18 +00007154 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh91eb93c2015-03-03 19:56:20 +00007155 (lockPath ? lockPath : ":auto:"), osGetpid()));
drh715ff302008-12-03 22:32:44 +00007156
7157 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7158 if( pCtx==0 ){
7159 return SQLITE_NOMEM;
7160 }
7161 memset(pCtx, 0, sizeof(*pCtx));
7162
7163 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7164 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007165 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7166 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7167 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7168 ** (c) the file system is read-only, then enable no-locking access.
7169 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7170 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7171 */
7172 struct statfs fsInfo;
7173 struct stat conchInfo;
7174 int goLockless = 0;
7175
drh99ab3b12011-03-02 15:09:07 +00007176 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007177 int err = errno;
7178 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7179 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7180 }
7181 }
7182 if( goLockless ){
7183 pCtx->conchHeld = -1; /* read only FS/ lockless */
7184 rc = SQLITE_OK;
7185 }
7186 }
drh715ff302008-12-03 22:32:44 +00007187 }
7188 if( rc==SQLITE_OK && lockPath ){
7189 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7190 }
7191
7192 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007193 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7194 if( pCtx->dbPath==NULL ){
7195 rc = SQLITE_NOMEM;
7196 }
7197 }
7198 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007199 /* all memory is allocated, proxys are created and assigned,
7200 ** switch the locking context and pMethod then return.
7201 */
drh715ff302008-12-03 22:32:44 +00007202 pCtx->oldLockingContext = pFile->lockingContext;
7203 pFile->lockingContext = pCtx;
7204 pCtx->pOldMethod = pFile->pMethod;
7205 pFile->pMethod = &proxyIoMethods;
7206 }else{
7207 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007208 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007209 sqlite3_free(pCtx->conchFile);
7210 }
drhd56b1212010-08-11 06:14:15 +00007211 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007212 sqlite3_free(pCtx->conchFilePath);
7213 sqlite3_free(pCtx);
7214 }
drh308c2a52010-05-14 11:30:18 +00007215 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7216 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007217 return rc;
7218}
7219
7220
7221/*
7222** This routine handles sqlite3_file_control() calls that are specific
7223** to proxy locking.
7224*/
7225static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7226 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007227 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007228 unixFile *pFile = (unixFile*)id;
7229 if( pFile->pMethod == &proxyIoMethods ){
7230 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7231 proxyTakeConch(pFile);
7232 if( pCtx->lockProxyPath ){
7233 *(const char **)pArg = pCtx->lockProxyPath;
7234 }else{
7235 *(const char **)pArg = ":auto: (not held)";
7236 }
7237 } else {
7238 *(const char **)pArg = NULL;
7239 }
7240 return SQLITE_OK;
7241 }
drh4bf66fd2015-02-19 02:43:02 +00007242 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007243 unixFile *pFile = (unixFile*)id;
7244 int rc = SQLITE_OK;
7245 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7246 if( pArg==NULL || (const char *)pArg==0 ){
7247 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007248 /* turn off proxy locking - not supported. If support is added for
7249 ** switching proxy locking mode off then it will need to fail if
7250 ** the journal mode is WAL mode.
7251 */
drh715ff302008-12-03 22:32:44 +00007252 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7253 }else{
7254 /* turn off proxy locking - already off - NOOP */
7255 rc = SQLITE_OK;
7256 }
7257 }else{
7258 const char *proxyPath = (const char *)pArg;
7259 if( isProxyStyle ){
7260 proxyLockingContext *pCtx =
7261 (proxyLockingContext*)pFile->lockingContext;
7262 if( !strcmp(pArg, ":auto:")
7263 || (pCtx->lockProxyPath &&
7264 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7265 ){
7266 rc = SQLITE_OK;
7267 }else{
7268 rc = switchLockProxyPath(pFile, proxyPath);
7269 }
7270 }else{
7271 /* turn on proxy file locking */
7272 rc = proxyTransformUnixFile(pFile, proxyPath);
7273 }
7274 }
7275 return rc;
7276 }
7277 default: {
7278 assert( 0 ); /* The call assures that only valid opcodes are sent */
7279 }
7280 }
7281 /*NOTREACHED*/
7282 return SQLITE_ERROR;
7283}
7284
7285/*
7286** Within this division (the proxying locking implementation) the procedures
7287** above this point are all utilities. The lock-related methods of the
7288** proxy-locking sqlite3_io_method object follow.
7289*/
7290
7291
7292/*
7293** This routine checks if there is a RESERVED lock held on the specified
7294** file by this or any other process. If such a lock is held, set *pResOut
7295** to a non-zero value otherwise *pResOut is set to zero. The return value
7296** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7297*/
7298static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7299 unixFile *pFile = (unixFile*)id;
7300 int rc = proxyTakeConch(pFile);
7301 if( rc==SQLITE_OK ){
7302 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007303 if( pCtx->conchHeld>0 ){
7304 unixFile *proxy = pCtx->lockProxy;
7305 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7306 }else{ /* conchHeld < 0 is lockless */
7307 pResOut=0;
7308 }
drh715ff302008-12-03 22:32:44 +00007309 }
7310 return rc;
7311}
7312
7313/*
drh308c2a52010-05-14 11:30:18 +00007314** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007315** of the following:
7316**
7317** (1) SHARED_LOCK
7318** (2) RESERVED_LOCK
7319** (3) PENDING_LOCK
7320** (4) EXCLUSIVE_LOCK
7321**
7322** Sometimes when requesting one lock state, additional lock states
7323** are inserted in between. The locking might fail on one of the later
7324** transitions leaving the lock state different from what it started but
7325** still short of its goal. The following chart shows the allowed
7326** transitions and the inserted intermediate states:
7327**
7328** UNLOCKED -> SHARED
7329** SHARED -> RESERVED
7330** SHARED -> (PENDING) -> EXCLUSIVE
7331** RESERVED -> (PENDING) -> EXCLUSIVE
7332** PENDING -> EXCLUSIVE
7333**
7334** This routine will only increase a lock. Use the sqlite3OsUnlock()
7335** routine to lower a locking level.
7336*/
drh308c2a52010-05-14 11:30:18 +00007337static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007338 unixFile *pFile = (unixFile*)id;
7339 int rc = proxyTakeConch(pFile);
7340 if( rc==SQLITE_OK ){
7341 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007342 if( pCtx->conchHeld>0 ){
7343 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007344 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7345 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007346 }else{
7347 /* conchHeld < 0 is lockless */
7348 }
drh715ff302008-12-03 22:32:44 +00007349 }
7350 return rc;
7351}
7352
7353
7354/*
drh308c2a52010-05-14 11:30:18 +00007355** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007356** must be either NO_LOCK or SHARED_LOCK.
7357**
7358** If the locking level of the file descriptor is already at or below
7359** the requested locking level, this routine is a no-op.
7360*/
drh308c2a52010-05-14 11:30:18 +00007361static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007362 unixFile *pFile = (unixFile*)id;
7363 int rc = proxyTakeConch(pFile);
7364 if( rc==SQLITE_OK ){
7365 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007366 if( pCtx->conchHeld>0 ){
7367 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007368 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7369 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007370 }else{
7371 /* conchHeld < 0 is lockless */
7372 }
drh715ff302008-12-03 22:32:44 +00007373 }
7374 return rc;
7375}
7376
7377/*
7378** Close a file that uses proxy locks.
7379*/
7380static int proxyClose(sqlite3_file *id) {
7381 if( id ){
7382 unixFile *pFile = (unixFile*)id;
7383 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7384 unixFile *lockProxy = pCtx->lockProxy;
7385 unixFile *conchFile = pCtx->conchFile;
7386 int rc = SQLITE_OK;
7387
7388 if( lockProxy ){
7389 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7390 if( rc ) return rc;
7391 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7392 if( rc ) return rc;
7393 sqlite3_free(lockProxy);
7394 pCtx->lockProxy = 0;
7395 }
7396 if( conchFile ){
7397 if( pCtx->conchHeld ){
7398 rc = proxyReleaseConch(pFile);
7399 if( rc ) return rc;
7400 }
7401 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7402 if( rc ) return rc;
7403 sqlite3_free(conchFile);
7404 }
drhd56b1212010-08-11 06:14:15 +00007405 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007406 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007407 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007408 /* restore the original locking context and pMethod then close it */
7409 pFile->lockingContext = pCtx->oldLockingContext;
7410 pFile->pMethod = pCtx->pOldMethod;
7411 sqlite3_free(pCtx);
7412 return pFile->pMethod->xClose(id);
7413 }
7414 return SQLITE_OK;
7415}
7416
7417
7418
drhd2cb50b2009-01-09 21:41:17 +00007419#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007420/*
7421** The proxy locking style is intended for use with AFP filesystems.
7422** And since AFP is only supported on MacOSX, the proxy locking is also
7423** restricted to MacOSX.
7424**
7425**
7426******************* End of the proxy lock implementation **********************
7427******************************************************************************/
7428
drh734c9862008-11-28 15:37:20 +00007429/*
danielk1977e339d652008-06-28 11:23:00 +00007430** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007431**
7432** This routine registers all VFS implementations for unix-like operating
7433** systems. This routine, and the sqlite3_os_end() routine that follows,
7434** should be the only routines in this file that are visible from other
7435** files.
drh6b9d6dd2008-12-03 19:34:47 +00007436**
7437** This routine is called once during SQLite initialization and by a
7438** single thread. The memory allocation and mutex subsystems have not
7439** necessarily been initialized when this routine is called, and so they
7440** should not be used.
drh153c62c2007-08-24 03:51:33 +00007441*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007442int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007443 /*
7444 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007445 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7446 ** to the "finder" function. (pAppData is a pointer to a pointer because
7447 ** silly C90 rules prohibit a void* from being cast to a function pointer
7448 ** and so we have to go through the intermediate pointer to avoid problems
7449 ** when compiling with -pedantic-errors on GCC.)
7450 **
7451 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007452 ** finder-function. The finder-function returns a pointer to the
7453 ** sqlite_io_methods object that implements the desired locking
7454 ** behaviors. See the division above that contains the IOMETHODS
7455 ** macro for addition information on finder-functions.
7456 **
7457 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7458 ** object. But the "autolockIoFinder" available on MacOSX does a little
7459 ** more than that; it looks at the filesystem type that hosts the
7460 ** database file and tries to choose an locking method appropriate for
7461 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007462 */
drh7708e972008-11-29 00:56:52 +00007463 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007464 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007465 sizeof(unixFile), /* szOsFile */ \
7466 MAX_PATHNAME, /* mxPathname */ \
7467 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007468 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007469 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007470 unixOpen, /* xOpen */ \
7471 unixDelete, /* xDelete */ \
7472 unixAccess, /* xAccess */ \
7473 unixFullPathname, /* xFullPathname */ \
7474 unixDlOpen, /* xDlOpen */ \
7475 unixDlError, /* xDlError */ \
7476 unixDlSym, /* xDlSym */ \
7477 unixDlClose, /* xDlClose */ \
7478 unixRandomness, /* xRandomness */ \
7479 unixSleep, /* xSleep */ \
7480 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007481 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007482 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007483 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007484 unixGetSystemCall, /* xGetSystemCall */ \
7485 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007486 }
7487
drh6b9d6dd2008-12-03 19:34:47 +00007488 /*
7489 ** All default VFSes for unix are contained in the following array.
7490 **
7491 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7492 ** by the SQLite core when the VFS is registered. So the following
7493 ** array cannot be const.
7494 */
danielk1977e339d652008-06-28 11:23:00 +00007495 static sqlite3_vfs aVfs[] = {
chw78a13182009-04-07 05:35:03 +00007496#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
drh7708e972008-11-29 00:56:52 +00007497 UNIXVFS("unix", autolockIoFinder ),
7498#else
7499 UNIXVFS("unix", posixIoFinder ),
7500#endif
7501 UNIXVFS("unix-none", nolockIoFinder ),
7502 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007503 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007504#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007505 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007506#endif
7507#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00007508 UNIXVFS("unix-posix", posixIoFinder ),
chw78a13182009-04-07 05:35:03 +00007509#if !OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007510 UNIXVFS("unix-flock", flockIoFinder ),
drh734c9862008-11-28 15:37:20 +00007511#endif
chw78a13182009-04-07 05:35:03 +00007512#endif
drhd2cb50b2009-01-09 21:41:17 +00007513#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007514 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007515 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007516 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007517#endif
drh153c62c2007-08-24 03:51:33 +00007518 };
drh6b9d6dd2008-12-03 19:34:47 +00007519 unsigned int i; /* Loop counter */
7520
drh2aa5a002011-04-13 13:42:25 +00007521 /* Double-check that the aSyscall[] array has been constructed
7522 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007523 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007524
drh6b9d6dd2008-12-03 19:34:47 +00007525 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007526 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007527 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007528 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007529 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007530}
danielk1977e339d652008-06-28 11:23:00 +00007531
7532/*
drh6b9d6dd2008-12-03 19:34:47 +00007533** Shutdown the operating system interface.
7534**
7535** Some operating systems might need to do some cleanup in this routine,
7536** to release dynamically allocated objects. But not on unix.
7537** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007538*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007539int sqlite3_os_end(void){
7540 return SQLITE_OK;
7541}
drhdce8bdb2007-08-16 13:01:44 +00007542
danielk197729bafea2008-06-26 10:41:19 +00007543#endif /* SQLITE_OS_UNIX */