blob: 16cb935decf587d1a2913b365b00400d1c56d352 [file] [log] [blame]
drhbbd42a62004-05-22 17:41:58 +00001/*
2** 2004 May 22
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
drh734c9862008-11-28 15:37:20 +000013** This file contains the VFS implementation for unix-like operating systems
14** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
danielk1977822a5162008-05-16 04:51:54 +000015**
drh734c9862008-11-28 15:37:20 +000016** There are actually several different VFS implementations in this file.
17** The differences are in the way that file locking is done. The default
18** implementation uses Posix Advisory Locks. Alternative implementations
19** use flock(), dot-files, various proprietary locking schemas, or simply
20** skip locking all together.
21**
drh9b35ea62008-11-29 02:20:26 +000022** This source file is organized into divisions where the logic for various
drh734c9862008-11-28 15:37:20 +000023** subfunctions is contained within the appropriate division. PLEASE
24** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
25** in the correct division and should be clearly labeled.
26**
drh6b9d6dd2008-12-03 19:34:47 +000027** The layout of divisions is as follows:
drh734c9862008-11-28 15:37:20 +000028**
29** * General-purpose declarations and utility functions.
30** * Unique file ID logic used by VxWorks.
drh715ff302008-12-03 22:32:44 +000031** * Various locking primitive implementations (all except proxy locking):
drh734c9862008-11-28 15:37:20 +000032** + for Posix Advisory Locks
33** + for no-op locks
34** + for dot-file locks
35** + for flock() locking
36** + for named semaphore locks (VxWorks only)
37** + for AFP filesystem locks (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000038** * sqlite3_file methods not associated with locking.
39** * Definitions of sqlite3_io_methods objects for all locking
40** methods plus "finder" functions for each locking method.
drh6b9d6dd2008-12-03 19:34:47 +000041** * sqlite3_vfs method implementations.
drh715ff302008-12-03 22:32:44 +000042** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
drh9b35ea62008-11-29 02:20:26 +000043** * Definitions of sqlite3_vfs objects for all locking methods
44** plus implementations of sqlite3_os_init() and sqlite3_os_end().
drhbbd42a62004-05-22 17:41:58 +000045*/
drhbbd42a62004-05-22 17:41:58 +000046#include "sqliteInt.h"
danielk197729bafea2008-06-26 10:41:19 +000047#if SQLITE_OS_UNIX /* This file is used on unix only */
drh66560ad2006-01-06 14:32:19 +000048
danielk1977e339d652008-06-28 11:23:00 +000049/*
drh6b9d6dd2008-12-03 19:34:47 +000050** There are various methods for file locking used for concurrency
51** control:
danielk1977e339d652008-06-28 11:23:00 +000052**
drh734c9862008-11-28 15:37:20 +000053** 1. POSIX locking (the default),
54** 2. No locking,
55** 3. Dot-file locking,
56** 4. flock() locking,
57** 5. AFP locking (OSX only),
58** 6. Named POSIX semaphores (VXWorks only),
59** 7. proxy locking. (OSX only)
60**
61** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
62** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
63** selection of the appropriate locking style based on the filesystem
64** where the database is located.
danielk1977e339d652008-06-28 11:23:00 +000065*/
drh40bbb0a2008-09-23 10:23:26 +000066#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
drhd2cb50b2009-01-09 21:41:17 +000067# if defined(__APPLE__)
drh40bbb0a2008-09-23 10:23:26 +000068# define SQLITE_ENABLE_LOCKING_STYLE 1
69# else
70# define SQLITE_ENABLE_LOCKING_STYLE 0
71# endif
72#endif
drhbfe66312006-10-03 17:40:40 +000073
drh9cbe6352005-11-29 03:13:21 +000074/*
drh9cbe6352005-11-29 03:13:21 +000075** standard include files.
76*/
77#include <sys/types.h>
78#include <sys/stat.h>
79#include <fcntl.h>
80#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000081#include <time.h>
drh19e2d372005-08-29 23:00:03 +000082#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000083#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000084#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000085# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000086#endif
drh1da88f02011-12-17 16:09:16 +000087
drhe89b2912015-03-03 20:42:01 +000088#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +000089# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +000090# include <sys/file.h>
91# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +000092#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +000093
drhe89b2912015-03-03 20:42:01 +000094#if OS_VXWORKS
95# include <sys/ioctl.h>
96# include <semaphore.h>
97# include <limits.h>
98#endif /* OS_VXWORKS */
99
100#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000101# include <sys/mount.h>
102#endif
103
drhdbe4b882011-06-20 18:00:17 +0000104#ifdef HAVE_UTIME
105# include <utime.h>
106#endif
107
drh9cbe6352005-11-29 03:13:21 +0000108/*
drh7ed97b92010-01-20 13:07:21 +0000109** Allowed values of unixFile.fsFlags
110*/
111#define SQLITE_FSFLAGS_IS_MSDOS 0x1
112
113/*
drhf1a221e2006-01-15 17:27:17 +0000114** If we are to be thread-safe, include the pthreads header and define
115** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000116*/
drhd677b3d2007-08-20 22:48:41 +0000117#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000118# include <pthread.h>
119# define SQLITE_UNIX_THREADS 1
120#endif
121
122/*
123** Default permissions when creating a new file
124*/
125#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
126# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
127#endif
128
danielk1977b4b47412007-08-17 15:53:36 +0000129/*
drh5adc60b2012-04-14 13:25:11 +0000130** Default permissions when creating auto proxy dir
131*/
aswiftaebf4132008-11-21 00:10:35 +0000132#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
133# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
134#endif
135
136/*
danielk1977b4b47412007-08-17 15:53:36 +0000137** Maximum supported path-length.
138*/
139#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000140
drh91eb93c2015-03-03 19:56:20 +0000141/* Always cast the getpid() return type for compatibility with
142** kernel modules in VxWorks. */
143#define osGetpid(X) (pid_t)getpid()
144
drh734c9862008-11-28 15:37:20 +0000145/*
drh734c9862008-11-28 15:37:20 +0000146** Only set the lastErrno if the error code is a real error and not
147** a normal expected return code of SQLITE_BUSY or SQLITE_OK
148*/
149#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
150
drhd91c68f2010-05-14 14:52:25 +0000151/* Forward references */
152typedef struct unixShm unixShm; /* Connection shared memory */
153typedef struct unixShmNode unixShmNode; /* Shared memory instance */
154typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
155typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000156
157/*
dane946c392009-08-22 11:39:46 +0000158** Sometimes, after a file handle is closed by SQLite, the file descriptor
159** cannot be closed immediately. In these cases, instances of the following
160** structure are used to store the file descriptor while waiting for an
161** opportunity to either close or reuse it.
162*/
dane946c392009-08-22 11:39:46 +0000163struct UnixUnusedFd {
164 int fd; /* File descriptor to close */
165 int flags; /* Flags this file descriptor was opened with */
166 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
167};
168
169/*
drh9b35ea62008-11-29 02:20:26 +0000170** The unixFile structure is subclass of sqlite3_file specific to the unix
171** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000172*/
drh054889e2005-11-30 03:20:31 +0000173typedef struct unixFile unixFile;
174struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000175 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000176 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000177 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000178 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000179 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000180 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000181 int lastErrno; /* The unix errno from last I/O error */
182 void *lockingContext; /* Locking style specific state */
183 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000184 const char *zPath; /* Name of the file */
185 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000186 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000187#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000188 int nFetchOut; /* Number of outstanding xFetch refs */
189 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000190 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
191 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000192 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000193#endif
drh537dddf2012-10-26 13:46:24 +0000194#ifdef __QNXNTO__
195 int sectorSize; /* Device sector size */
196 int deviceCharacteristics; /* Precomputed device characteristics */
197#endif
drh08c6d442009-02-09 17:34:07 +0000198#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000199 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000200#endif
drh7ed97b92010-01-20 13:07:21 +0000201#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000202 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000203#endif
204#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000205 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000206#endif
drhd3d8c042012-05-29 17:02:40 +0000207#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000208 /* The next group of variables are used to track whether or not the
209 ** transaction counter in bytes 24-27 of database files are updated
210 ** whenever any part of the database changes. An assertion fault will
211 ** occur if a file is updated without also updating the transaction
212 ** counter. This test is made to avoid new problems similar to the
213 ** one described by ticket #3584.
214 */
215 unsigned char transCntrChng; /* True if the transaction counter changed */
216 unsigned char dbUpdate; /* True if any part of database file changed */
217 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000218
drh8f941bc2009-01-14 23:03:40 +0000219#endif
danf23da962013-03-23 21:00:41 +0000220
danielk1977967a4a12007-08-20 14:23:44 +0000221#ifdef SQLITE_TEST
222 /* In test mode, increase the size of this structure a bit so that
223 ** it is larger than the struct CrashFile defined in test6.c.
224 */
225 char aPadding[32];
226#endif
drh9cbe6352005-11-29 03:13:21 +0000227};
228
drhb00d8622014-01-01 15:18:36 +0000229/* This variable holds the process id (pid) from when the xRandomness()
230** method was called. If xOpen() is called from a different process id,
231** indicating that a fork() has occurred, the PRNG will be reset.
232*/
drh8cd5b252015-03-02 22:06:43 +0000233static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000234
drh0ccebe72005-06-07 22:22:50 +0000235/*
drha7e61d82011-03-12 17:02:57 +0000236** Allowed values for the unixFile.ctrlFlags bitmask:
237*/
drhf0b190d2011-07-26 16:03:07 +0000238#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
239#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
240#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000241#ifndef SQLITE_DISABLE_DIRSYNC
242# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
243#else
244# define UNIXFILE_DIRSYNC 0x00
245#endif
drhcb15f352011-12-23 01:04:17 +0000246#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000247#define UNIXFILE_DELETE 0x20 /* Delete on close */
248#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
249#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000250#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drhbbf76ee2015-03-10 20:22:35 +0000251#define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
drha7e61d82011-03-12 17:02:57 +0000252
253/*
drh198bf392006-01-06 21:52:49 +0000254** Include code that is common to all os_*.c files
255*/
256#include "os_common.h"
257
258/*
drh0ccebe72005-06-07 22:22:50 +0000259** Define various macros that are missing from some systems.
260*/
drhbbd42a62004-05-22 17:41:58 +0000261#ifndef O_LARGEFILE
262# define O_LARGEFILE 0
263#endif
264#ifdef SQLITE_DISABLE_LFS
265# undef O_LARGEFILE
266# define O_LARGEFILE 0
267#endif
268#ifndef O_NOFOLLOW
269# define O_NOFOLLOW 0
270#endif
271#ifndef O_BINARY
272# define O_BINARY 0
273#endif
274
275/*
drh2b4b5962005-06-15 17:47:55 +0000276** The threadid macro resolves to the thread-id or to 0. Used for
277** testing and debugging only.
278*/
drhd677b3d2007-08-20 22:48:41 +0000279#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000280#define threadid pthread_self()
281#else
282#define threadid 0
283#endif
284
drh99ab3b12011-03-02 15:09:07 +0000285/*
dane6ecd662013-04-01 17:56:59 +0000286** HAVE_MREMAP defaults to true on Linux and false everywhere else.
287*/
288#if !defined(HAVE_MREMAP)
289# if defined(__linux__) && defined(_GNU_SOURCE)
290# define HAVE_MREMAP 1
291# else
292# define HAVE_MREMAP 0
293# endif
294#endif
295
296/*
dan2ee53412014-09-06 16:49:40 +0000297** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
298** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
299*/
300#ifdef __ANDROID__
301# define lseek lseek64
302#endif
303
304/*
drh9a3baf12011-04-25 18:01:27 +0000305** Different Unix systems declare open() in different ways. Same use
306** open(const char*,int,mode_t). Others use open(const char*,int,...).
307** The difference is important when using a pointer to the function.
308**
309** The safest way to deal with the problem is to always use this wrapper
310** which always has the same well-defined interface.
311*/
312static int posixOpen(const char *zFile, int flags, int mode){
313 return open(zFile, flags, mode);
314}
315
drhed466822012-05-31 13:10:49 +0000316/*
317** On some systems, calls to fchown() will trigger a message in a security
318** log if they come from non-root processes. So avoid calling fchown() if
319** we are not running as root.
320*/
321static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000322#if OS_VXWORKS
323 return 0;
324#else
drhed466822012-05-31 13:10:49 +0000325 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000326#endif
drhed466822012-05-31 13:10:49 +0000327}
328
drh90315a22011-08-10 01:52:12 +0000329/* Forward reference */
330static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000331static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000332
drh9a3baf12011-04-25 18:01:27 +0000333/*
drh99ab3b12011-03-02 15:09:07 +0000334** Many system calls are accessed through pointer-to-functions so that
335** they may be overridden at runtime to facilitate fault injection during
336** testing and sandboxing. The following array holds the names and pointers
337** to all overrideable system calls.
338*/
339static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000340 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000341 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
342 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000343} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000344 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
345#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000346
drh58ad5802011-03-23 22:02:23 +0000347 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000348#define osClose ((int(*)(int))aSyscall[1].pCurrent)
349
drh58ad5802011-03-23 22:02:23 +0000350 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000351#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
352
drh58ad5802011-03-23 22:02:23 +0000353 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000354#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
355
drh58ad5802011-03-23 22:02:23 +0000356 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000357#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
358
359/*
360** The DJGPP compiler environment looks mostly like Unix, but it
361** lacks the fcntl() system call. So redefine fcntl() to be something
362** that always succeeds. This means that locking does not occur under
363** DJGPP. But it is DOS - what did you expect?
364*/
365#ifdef __DJGPP__
366 { "fstat", 0, 0 },
367#define osFstat(a,b,c) 0
368#else
drh58ad5802011-03-23 22:02:23 +0000369 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000370#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
371#endif
372
drh58ad5802011-03-23 22:02:23 +0000373 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000378
drh58ad5802011-03-23 22:02:23 +0000379 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000380#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
381
drhe89b2912015-03-03 20:42:01 +0000382#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000383 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000384#else
drh58ad5802011-03-23 22:02:23 +0000385 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000386#endif
387#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
388
389#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000390 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000391#else
drh58ad5802011-03-23 22:02:23 +0000392 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000393#endif
394#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
395
drh58ad5802011-03-23 22:02:23 +0000396 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000397#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
398
drhe89b2912015-03-03 20:42:01 +0000399#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000400 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000401#else
drh58ad5802011-03-23 22:02:23 +0000402 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000403#endif
404#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
405 aSyscall[12].pCurrent)
406
407#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000408 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000409#else
drh58ad5802011-03-23 22:02:23 +0000410 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000411#endif
412#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
413 aSyscall[13].pCurrent)
414
drh58ad5802011-03-23 22:02:23 +0000415 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000416#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000417
418#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000419 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000420#else
drh58ad5802011-03-23 22:02:23 +0000421 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000422#endif
dan0fd7d862011-03-29 10:04:23 +0000423#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000424
drh036ac7f2011-08-08 23:18:05 +0000425 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
426#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
427
drh90315a22011-08-10 01:52:12 +0000428 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
429#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
430
drh9ef6bc42011-11-04 02:24:02 +0000431 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
432#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
433
434 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
435#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
436
drhed466822012-05-31 13:10:49 +0000437 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000438#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000439
dan4dd51442013-08-26 14:30:25 +0000440#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000441 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
442#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
443
drhd1ab8062013-03-25 20:50:25 +0000444 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
445#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
446
dane6ecd662013-04-01 17:56:59 +0000447#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000448 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
449#else
450 { "mremap", (sqlite3_syscall_ptr)0, 0 },
451#endif
452#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000453 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
454#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
455
dan702eec12014-06-23 10:04:58 +0000456#endif
457
drhe562be52011-03-02 18:01:10 +0000458}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000459
460/*
461** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000462** "unix" VFSes. Return SQLITE_OK opon successfully updating the
463** system call pointer, or SQLITE_NOTFOUND if there is no configurable
464** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000465*/
466static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000467 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
468 const char *zName, /* Name of system call to override */
469 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000470){
drh58ad5802011-03-23 22:02:23 +0000471 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000472 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000473
474 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000475 if( zName==0 ){
476 /* If no zName is given, restore all system calls to their default
477 ** settings and return NULL
478 */
dan51438a72011-04-02 17:00:47 +0000479 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000480 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
481 if( aSyscall[i].pDefault ){
482 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000483 }
484 }
485 }else{
486 /* If zName is specified, operate on only the one system call
487 ** specified.
488 */
489 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
490 if( strcmp(zName, aSyscall[i].zName)==0 ){
491 if( aSyscall[i].pDefault==0 ){
492 aSyscall[i].pDefault = aSyscall[i].pCurrent;
493 }
drh1df30962011-03-02 19:06:42 +0000494 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000495 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
496 aSyscall[i].pCurrent = pNewFunc;
497 break;
498 }
499 }
500 }
501 return rc;
502}
503
drh1df30962011-03-02 19:06:42 +0000504/*
505** Return the value of a system call. Return NULL if zName is not a
506** recognized system call name. NULL is also returned if the system call
507** is currently undefined.
508*/
drh58ad5802011-03-23 22:02:23 +0000509static sqlite3_syscall_ptr unixGetSystemCall(
510 sqlite3_vfs *pNotUsed,
511 const char *zName
512){
513 unsigned int i;
514
515 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000516 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
517 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
518 }
519 return 0;
520}
521
522/*
523** Return the name of the first system call after zName. If zName==NULL
524** then return the name of the first system call. Return NULL if zName
525** is the last system call or if zName is not the name of a valid
526** system call.
527*/
528static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000529 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000530
531 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000532 if( zName ){
533 for(i=0; i<ArraySize(aSyscall)-1; i++){
534 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000535 }
536 }
dan0fd7d862011-03-29 10:04:23 +0000537 for(i++; i<ArraySize(aSyscall); i++){
538 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000539 }
540 return 0;
541}
542
drhad4f1e52011-03-04 15:43:57 +0000543/*
drh77a3fdc2013-08-30 14:24:12 +0000544** Do not accept any file descriptor less than this value, in order to avoid
545** opening database file using file descriptors that are commonly used for
546** standard input, output, and error.
547*/
548#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
549# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
550#endif
551
552/*
drh8c815d12012-02-13 20:16:37 +0000553** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000554** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000555**
556** If the file creation mode "m" is 0 then set it to the default for
557** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
558** 0644) as modified by the system umask. If m is not 0, then
559** make the file creation mode be exactly m ignoring the umask.
560**
561** The m parameter will be non-zero only when creating -wal, -journal,
562** and -shm files. We want those files to have *exactly* the same
563** permissions as their original database, unadulterated by the umask.
564** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
565** transaction crashes and leaves behind hot journals, then any
566** process that is able to write to the database will also be able to
567** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000568*/
drh8c815d12012-02-13 20:16:37 +0000569static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000570 int fd;
drhe1186ab2013-01-04 20:45:13 +0000571 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000572 while(1){
drh5adc60b2012-04-14 13:25:11 +0000573#if defined(O_CLOEXEC)
574 fd = osOpen(z,f|O_CLOEXEC,m2);
575#else
576 fd = osOpen(z,f,m2);
577#endif
drh5128d002013-08-30 06:20:23 +0000578 if( fd<0 ){
579 if( errno==EINTR ) continue;
580 break;
581 }
drh77a3fdc2013-08-30 14:24:12 +0000582 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000583 osClose(fd);
584 sqlite3_log(SQLITE_WARNING,
585 "attempt to open \"%s\" as file descriptor %d", z, fd);
586 fd = -1;
587 if( osOpen("/dev/null", f, m)<0 ) break;
588 }
drhe1186ab2013-01-04 20:45:13 +0000589 if( fd>=0 ){
590 if( m!=0 ){
591 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000592 if( osFstat(fd, &statbuf)==0
593 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000594 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000595 ){
drhe1186ab2013-01-04 20:45:13 +0000596 osFchmod(fd, m);
597 }
598 }
drh5adc60b2012-04-14 13:25:11 +0000599#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000600 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000601#endif
drhe1186ab2013-01-04 20:45:13 +0000602 }
drh5adc60b2012-04-14 13:25:11 +0000603 return fd;
drhad4f1e52011-03-04 15:43:57 +0000604}
danielk197713adf8a2004-06-03 16:08:41 +0000605
drh107886a2008-11-21 22:21:50 +0000606/*
dan9359c7b2009-08-21 08:29:10 +0000607** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000608** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000609** vxworksFileId objects used by this file, all of which may be
610** shared by multiple threads.
611**
612** Function unixMutexHeld() is used to assert() that the global mutex
613** is held when required. This function is only used as part of assert()
614** statements. e.g.
615**
616** unixEnterMutex()
617** assert( unixMutexHeld() );
618** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000619*/
620static void unixEnterMutex(void){
621 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
622}
623static void unixLeaveMutex(void){
624 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
625}
dan9359c7b2009-08-21 08:29:10 +0000626#ifdef SQLITE_DEBUG
627static int unixMutexHeld(void) {
628 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
629}
630#endif
drh107886a2008-11-21 22:21:50 +0000631
drh734c9862008-11-28 15:37:20 +0000632
drh30ddce62011-10-15 00:16:30 +0000633#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
drh734c9862008-11-28 15:37:20 +0000634/*
635** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000636** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000637** integer lock-type.
638*/
drh308c2a52010-05-14 11:30:18 +0000639static const char *azFileLock(int eFileLock){
640 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000641 case NO_LOCK: return "NONE";
642 case SHARED_LOCK: return "SHARED";
643 case RESERVED_LOCK: return "RESERVED";
644 case PENDING_LOCK: return "PENDING";
645 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000646 }
647 return "ERROR";
648}
649#endif
650
651#ifdef SQLITE_LOCK_TRACE
652/*
653** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000654**
drh734c9862008-11-28 15:37:20 +0000655** This routine is used for troubleshooting locks on multithreaded
656** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
657** command-line option on the compiler. This code is normally
658** turned off.
659*/
660static int lockTrace(int fd, int op, struct flock *p){
661 char *zOpName, *zType;
662 int s;
663 int savedErrno;
664 if( op==F_GETLK ){
665 zOpName = "GETLK";
666 }else if( op==F_SETLK ){
667 zOpName = "SETLK";
668 }else{
drh99ab3b12011-03-02 15:09:07 +0000669 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000670 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
671 return s;
672 }
673 if( p->l_type==F_RDLCK ){
674 zType = "RDLCK";
675 }else if( p->l_type==F_WRLCK ){
676 zType = "WRLCK";
677 }else if( p->l_type==F_UNLCK ){
678 zType = "UNLCK";
679 }else{
680 assert( 0 );
681 }
682 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000683 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000684 savedErrno = errno;
685 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
686 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
687 (int)p->l_pid, s);
688 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
689 struct flock l2;
690 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000691 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000692 if( l2.l_type==F_RDLCK ){
693 zType = "RDLCK";
694 }else if( l2.l_type==F_WRLCK ){
695 zType = "WRLCK";
696 }else if( l2.l_type==F_UNLCK ){
697 zType = "UNLCK";
698 }else{
699 assert( 0 );
700 }
701 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
702 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
703 }
704 errno = savedErrno;
705 return s;
706}
drh99ab3b12011-03-02 15:09:07 +0000707#undef osFcntl
708#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000709#endif /* SQLITE_LOCK_TRACE */
710
drhff812312011-02-23 13:33:46 +0000711/*
712** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000713**
drhe6d41732015-02-21 00:49:00 +0000714** All calls to ftruncate() within this file should be made through
715** this wrapper. On the Android platform, bypassing the logic below
716** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000717*/
drhff812312011-02-23 13:33:46 +0000718static int robust_ftruncate(int h, sqlite3_int64 sz){
719 int rc;
dan2ee53412014-09-06 16:49:40 +0000720#ifdef __ANDROID__
721 /* On Android, ftruncate() always uses 32-bit offsets, even if
722 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000723 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000724 ** such attempts. */
725 if( sz>(sqlite3_int64)0x7FFFFFFF ){
726 rc = SQLITE_OK;
727 }else
728#endif
drh99ab3b12011-03-02 15:09:07 +0000729 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000730 return rc;
731}
drh734c9862008-11-28 15:37:20 +0000732
733/*
734** This routine translates a standard POSIX errno code into something
735** useful to the clients of the sqlite3 functions. Specifically, it is
736** intended to translate a variety of "try again" errors into SQLITE_BUSY
737** and a variety of "please close the file descriptor NOW" errors into
738** SQLITE_IOERR
739**
740** Errors during initialization of locks, or file system support for locks,
741** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
742*/
743static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
744 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000745#if 0
746 /* At one point this code was not commented out. In theory, this branch
747 ** should never be hit, as this function should only be called after
748 ** a locking-related function (i.e. fcntl()) has returned non-zero with
749 ** the value of errno as the first argument. Since a system call has failed,
750 ** errno should be non-zero.
751 **
752 ** Despite this, if errno really is zero, we still don't want to return
753 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
754 ** propagated back to the caller. Commenting this branch out means errno==0
755 ** will be handled by the "default:" case below.
756 */
drh734c9862008-11-28 15:37:20 +0000757 case 0:
758 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000759#endif
760
drh734c9862008-11-28 15:37:20 +0000761 case EAGAIN:
762 case ETIMEDOUT:
763 case EBUSY:
764 case EINTR:
765 case ENOLCK:
766 /* random NFS retry error, unless during file system support
767 * introspection, in which it actually means what it says */
768 return SQLITE_BUSY;
769
770 case EACCES:
771 /* EACCES is like EAGAIN during locking operations, but not any other time*/
772 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000773 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
774 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
775 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000776 return SQLITE_BUSY;
777 }
778 /* else fall through */
779 case EPERM:
780 return SQLITE_PERM;
781
drh734c9862008-11-28 15:37:20 +0000782#if EOPNOTSUPP!=ENOTSUP
783 case EOPNOTSUPP:
784 /* something went terribly awry, unless during file system support
785 * introspection, in which it actually means what it says */
786#endif
787#ifdef ENOTSUP
788 case ENOTSUP:
789 /* invalid fd, unless during file system support introspection, in which
790 * it actually means what it says */
791#endif
792 case EIO:
793 case EBADF:
794 case EINVAL:
795 case ENOTCONN:
796 case ENODEV:
797 case ENXIO:
798 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000799#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000800 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000801#endif
drh734c9862008-11-28 15:37:20 +0000802 case ENOSYS:
803 /* these should force the client to close the file and reconnect */
804
805 default:
806 return sqliteIOErr;
807 }
808}
809
810
drh734c9862008-11-28 15:37:20 +0000811/******************************************************************************
812****************** Begin Unique File ID Utility Used By VxWorks ***************
813**
814** On most versions of unix, we can get a unique ID for a file by concatenating
815** the device number and the inode number. But this does not work on VxWorks.
816** On VxWorks, a unique file id must be based on the canonical filename.
817**
818** A pointer to an instance of the following structure can be used as a
819** unique file ID in VxWorks. Each instance of this structure contains
820** a copy of the canonical filename. There is also a reference count.
821** The structure is reclaimed when the number of pointers to it drops to
822** zero.
823**
824** There are never very many files open at one time and lookups are not
825** a performance-critical path, so it is sufficient to put these
826** structures on a linked list.
827*/
828struct vxworksFileId {
829 struct vxworksFileId *pNext; /* Next in a list of them all */
830 int nRef; /* Number of references to this one */
831 int nName; /* Length of the zCanonicalName[] string */
832 char *zCanonicalName; /* Canonical filename */
833};
834
835#if OS_VXWORKS
836/*
drh9b35ea62008-11-29 02:20:26 +0000837** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000838** variable:
839*/
840static struct vxworksFileId *vxworksFileList = 0;
841
842/*
843** Simplify a filename into its canonical form
844** by making the following changes:
845**
846** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000847** * convert /./ into just /
848** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000849**
850** Changes are made in-place. Return the new name length.
851**
852** The original filename is in z[0..n-1]. Return the number of
853** characters in the simplified name.
854*/
855static int vxworksSimplifyName(char *z, int n){
856 int i, j;
857 while( n>1 && z[n-1]=='/' ){ n--; }
858 for(i=j=0; i<n; i++){
859 if( z[i]=='/' ){
860 if( z[i+1]=='/' ) continue;
861 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
862 i += 1;
863 continue;
864 }
865 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
866 while( j>0 && z[j-1]!='/' ){ j--; }
867 if( j>0 ){ j--; }
868 i += 2;
869 continue;
870 }
871 }
872 z[j++] = z[i];
873 }
874 z[j] = 0;
875 return j;
876}
877
878/*
879** Find a unique file ID for the given absolute pathname. Return
880** a pointer to the vxworksFileId object. This pointer is the unique
881** file ID.
882**
883** The nRef field of the vxworksFileId object is incremented before
884** the object is returned. A new vxworksFileId object is created
885** and added to the global list if necessary.
886**
887** If a memory allocation error occurs, return NULL.
888*/
889static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
890 struct vxworksFileId *pNew; /* search key and new file ID */
891 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
892 int n; /* Length of zAbsoluteName string */
893
894 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000895 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000896 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
897 if( pNew==0 ) return 0;
898 pNew->zCanonicalName = (char*)&pNew[1];
899 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
900 n = vxworksSimplifyName(pNew->zCanonicalName, n);
901
902 /* Search for an existing entry that matching the canonical name.
903 ** If found, increment the reference count and return a pointer to
904 ** the existing file ID.
905 */
906 unixEnterMutex();
907 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
908 if( pCandidate->nName==n
909 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
910 ){
911 sqlite3_free(pNew);
912 pCandidate->nRef++;
913 unixLeaveMutex();
914 return pCandidate;
915 }
916 }
917
918 /* No match was found. We will make a new file ID */
919 pNew->nRef = 1;
920 pNew->nName = n;
921 pNew->pNext = vxworksFileList;
922 vxworksFileList = pNew;
923 unixLeaveMutex();
924 return pNew;
925}
926
927/*
928** Decrement the reference count on a vxworksFileId object. Free
929** the object when the reference count reaches zero.
930*/
931static void vxworksReleaseFileId(struct vxworksFileId *pId){
932 unixEnterMutex();
933 assert( pId->nRef>0 );
934 pId->nRef--;
935 if( pId->nRef==0 ){
936 struct vxworksFileId **pp;
937 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
938 assert( *pp==pId );
939 *pp = pId->pNext;
940 sqlite3_free(pId);
941 }
942 unixLeaveMutex();
943}
944#endif /* OS_VXWORKS */
945/*************** End of Unique File ID Utility Used By VxWorks ****************
946******************************************************************************/
947
948
949/******************************************************************************
950*************************** Posix Advisory Locking ****************************
951**
drh9b35ea62008-11-29 02:20:26 +0000952** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000953** section 6.5.2.2 lines 483 through 490 specify that when a process
954** sets or clears a lock, that operation overrides any prior locks set
955** by the same process. It does not explicitly say so, but this implies
956** that it overrides locks set by the same process using a different
957** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000958**
959** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000960** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
961**
962** Suppose ./file1 and ./file2 are really the same file (because
963** one is a hard or symbolic link to the other) then if you set
964** an exclusive lock on fd1, then try to get an exclusive lock
965** on fd2, it works. I would have expected the second lock to
966** fail since there was already a lock on the file due to fd1.
967** But not so. Since both locks came from the same process, the
968** second overrides the first, even though they were on different
969** file descriptors opened on different file names.
970**
drh734c9862008-11-28 15:37:20 +0000971** This means that we cannot use POSIX locks to synchronize file access
972** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000973** to synchronize access for threads in separate processes, but not
974** threads within the same process.
975**
976** To work around the problem, SQLite has to manage file locks internally
977** on its own. Whenever a new database is opened, we have to find the
978** specific inode of the database file (the inode is determined by the
979** st_dev and st_ino fields of the stat structure that fstat() fills in)
980** and check for locks already existing on that inode. When locks are
981** created or removed, we have to look at our own internal record of the
982** locks to see if another thread has previously set a lock on that same
983** inode.
984**
drh9b35ea62008-11-29 02:20:26 +0000985** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
986** For VxWorks, we have to use the alternative unique ID system based on
987** canonical filename and implemented in the previous division.)
988**
danielk1977ad94b582007-08-20 06:44:22 +0000989** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +0000990** descriptor. It is now a structure that holds the integer file
991** descriptor and a pointer to a structure that describes the internal
992** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +0000993** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +0000994** point to the same locking structure. The locking structure keeps
995** a reference count (so we will know when to delete it) and a "cnt"
996** field that tells us its internal lock status. cnt==0 means the
997** file is unlocked. cnt==-1 means the file has an exclusive lock.
998** cnt>0 means there are cnt shared locks on the file.
999**
1000** Any attempt to lock or unlock a file first checks the locking
1001** structure. The fcntl() system call is only invoked to set a
1002** POSIX lock if the internal lock structure transitions between
1003** a locked and an unlocked state.
1004**
drh734c9862008-11-28 15:37:20 +00001005** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001006**
1007** If you close a file descriptor that points to a file that has locks,
1008** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001009** released. To work around this problem, each unixInodeInfo object
1010** maintains a count of the number of pending locks on tha inode.
1011** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001012** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001013** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001014** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001015** be closed and that list is walked (and cleared) when the last lock
1016** clears.
1017**
drh9b35ea62008-11-29 02:20:26 +00001018** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001019**
drh9b35ea62008-11-29 02:20:26 +00001020** Many older versions of linux use the LinuxThreads library which is
1021** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001022** A cannot be modified or overridden by a different thread B.
1023** Only thread A can modify the lock. Locking behavior is correct
1024** if the appliation uses the newer Native Posix Thread Library (NPTL)
1025** on linux - with NPTL a lock created by thread A can override locks
1026** in thread B. But there is no way to know at compile-time which
1027** threading library is being used. So there is no way to know at
1028** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001029** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001030** current process.
drh5fdae772004-06-29 03:29:00 +00001031**
drh8af6c222010-05-14 12:43:01 +00001032** SQLite used to support LinuxThreads. But support for LinuxThreads
1033** was dropped beginning with version 3.7.0. SQLite will still work with
1034** LinuxThreads provided that (1) there is no more than one connection
1035** per database file in the same process and (2) database connections
1036** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001037*/
1038
1039/*
1040** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001041** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001042*/
1043struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001044 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001045#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001046 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001047#else
drh107886a2008-11-21 22:21:50 +00001048 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001049#endif
1050};
1051
1052/*
drhbbd42a62004-05-22 17:41:58 +00001053** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001054** inode. Or, on LinuxThreads, there is one of these structures for
1055** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001056**
danielk1977ad94b582007-08-20 06:44:22 +00001057** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001058** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001059** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001060*/
drh8af6c222010-05-14 12:43:01 +00001061struct unixInodeInfo {
1062 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001063 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001064 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1065 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001066 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001067 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1068 int nLock; /* Number of outstanding file locks */
1069 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1070 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1071 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001072#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001073 unsigned long long sharedByte; /* for AFP simulated shared lock */
1074#endif
drh6c7d5c52008-11-21 20:32:33 +00001075#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001076 sem_t *pSem; /* Named POSIX semaphore */
1077 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001078#endif
drhbbd42a62004-05-22 17:41:58 +00001079};
1080
drhda0e7682008-07-30 15:27:54 +00001081/*
drh8af6c222010-05-14 12:43:01 +00001082** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001083*/
drhd91c68f2010-05-14 14:52:25 +00001084static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001085
drh5fdae772004-06-29 03:29:00 +00001086/*
dane18d4952011-02-21 11:46:24 +00001087**
1088** This function - unixLogError_x(), is only ever called via the macro
1089** unixLogError().
1090**
1091** It is invoked after an error occurs in an OS function and errno has been
1092** set. It logs a message using sqlite3_log() containing the current value of
1093** errno and, if possible, the human-readable equivalent from strerror() or
1094** strerror_r().
1095**
1096** The first argument passed to the macro should be the error code that
1097** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1098** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001099** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001100** if any.
1101*/
drh0e9365c2011-03-02 02:08:13 +00001102#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1103static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001104 int errcode, /* SQLite error code */
1105 const char *zFunc, /* Name of OS function that failed */
1106 const char *zPath, /* File path associated with error */
1107 int iLine /* Source line number where error occurred */
1108){
1109 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001110 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001111
1112 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1113 ** the strerror() function to obtain the human-readable error message
1114 ** equivalent to errno. Otherwise, use strerror_r().
1115 */
1116#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1117 char aErr[80];
1118 memset(aErr, 0, sizeof(aErr));
1119 zErr = aErr;
1120
1121 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001122 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001123 ** returns a pointer to a buffer containing the error message. That pointer
1124 ** may point to aErr[], or it may point to some static storage somewhere.
1125 ** Otherwise, assume that the system provides the POSIX version of
1126 ** strerror_r(), which always writes an error message into aErr[].
1127 **
1128 ** If the code incorrectly assumes that it is the POSIX version that is
1129 ** available, the error message will often be an empty string. Not a
1130 ** huge problem. Incorrectly concluding that the GNU version is available
1131 ** could lead to a segfault though.
1132 */
1133#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1134 zErr =
1135# endif
drh0e9365c2011-03-02 02:08:13 +00001136 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001137
1138#elif SQLITE_THREADSAFE
1139 /* This is a threadsafe build, but strerror_r() is not available. */
1140 zErr = "";
1141#else
1142 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001143 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001144#endif
1145
drh0e9365c2011-03-02 02:08:13 +00001146 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001147 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001148 "os_unix.c:%d: (%d) %s(%s) - %s",
1149 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001150 );
1151
1152 return errcode;
1153}
1154
drh0e9365c2011-03-02 02:08:13 +00001155/*
1156** Close a file descriptor.
1157**
1158** We assume that close() almost always works, since it is only in a
1159** very sick application or on a very sick platform that it might fail.
1160** If it does fail, simply leak the file descriptor, but do log the
1161** error.
1162**
1163** Note that it is not safe to retry close() after EINTR since the
1164** file descriptor might have already been reused by another thread.
1165** So we don't even try to recover from an EINTR. Just log the error
1166** and move on.
1167*/
1168static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001169 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001170 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1171 pFile ? pFile->zPath : 0, lineno);
1172 }
1173}
dane18d4952011-02-21 11:46:24 +00001174
1175/*
drhe6d41732015-02-21 00:49:00 +00001176** Set the pFile->lastErrno. Do this in a subroutine as that provides
1177** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001178*/
1179static void storeLastErrno(unixFile *pFile, int error){
1180 pFile->lastErrno = error;
1181}
1182
1183/*
danb0ac3e32010-06-16 10:55:42 +00001184** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001185*/
drh0e9365c2011-03-02 02:08:13 +00001186static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001187 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001188 UnixUnusedFd *p;
1189 UnixUnusedFd *pNext;
1190 for(p=pInode->pUnused; p; p=pNext){
1191 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001192 robust_close(pFile, p->fd, __LINE__);
1193 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001194 }
drh0e9365c2011-03-02 02:08:13 +00001195 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001196}
1197
1198/*
drh8af6c222010-05-14 12:43:01 +00001199** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001200**
1201** The mutex entered using the unixEnterMutex() function must be held
1202** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001203*/
danb0ac3e32010-06-16 10:55:42 +00001204static void releaseInodeInfo(unixFile *pFile){
1205 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001206 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001207 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001208 pInode->nRef--;
1209 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001210 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001211 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001212 if( pInode->pPrev ){
1213 assert( pInode->pPrev->pNext==pInode );
1214 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001215 }else{
drh8af6c222010-05-14 12:43:01 +00001216 assert( inodeList==pInode );
1217 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001218 }
drh8af6c222010-05-14 12:43:01 +00001219 if( pInode->pNext ){
1220 assert( pInode->pNext->pPrev==pInode );
1221 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001222 }
drh8af6c222010-05-14 12:43:01 +00001223 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001224 }
drhbbd42a62004-05-22 17:41:58 +00001225 }
1226}
1227
1228/*
drh8af6c222010-05-14 12:43:01 +00001229** Given a file descriptor, locate the unixInodeInfo object that
1230** describes that file descriptor. Create a new one if necessary. The
1231** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001232**
dan9359c7b2009-08-21 08:29:10 +00001233** The mutex entered using the unixEnterMutex() function must be held
1234** when this function is called.
1235**
drh6c7d5c52008-11-21 20:32:33 +00001236** Return an appropriate error code.
1237*/
drh8af6c222010-05-14 12:43:01 +00001238static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001239 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001240 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001241){
1242 int rc; /* System call return code */
1243 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001244 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1245 struct stat statbuf; /* Low-level file information */
1246 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001247
dan9359c7b2009-08-21 08:29:10 +00001248 assert( unixMutexHeld() );
1249
drh6c7d5c52008-11-21 20:32:33 +00001250 /* Get low-level information about the file that we can used to
1251 ** create a unique name for the file.
1252 */
1253 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001254 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001255 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001256 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001257#ifdef EOVERFLOW
1258 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1259#endif
1260 return SQLITE_IOERR;
1261 }
1262
drheb0d74f2009-02-03 15:27:02 +00001263#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001264 /* On OS X on an msdos filesystem, the inode number is reported
1265 ** incorrectly for zero-size files. See ticket #3260. To work
1266 ** around this problem (we consider it a bug in OS X, not SQLite)
1267 ** we always increase the file size to 1 by writing a single byte
1268 ** prior to accessing the inode number. The one byte written is
1269 ** an ASCII 'S' character which also happens to be the first byte
1270 ** in the header of every SQLite database. In this way, if there
1271 ** is a race condition such that another thread has already populated
1272 ** the first page of the database, no damage is done.
1273 */
drh7ed97b92010-01-20 13:07:21 +00001274 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001275 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001276 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001277 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001278 return SQLITE_IOERR;
1279 }
drh99ab3b12011-03-02 15:09:07 +00001280 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001281 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001282 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001283 return SQLITE_IOERR;
1284 }
1285 }
drheb0d74f2009-02-03 15:27:02 +00001286#endif
drh6c7d5c52008-11-21 20:32:33 +00001287
drh8af6c222010-05-14 12:43:01 +00001288 memset(&fileId, 0, sizeof(fileId));
1289 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001290#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001291 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001292#else
drh8af6c222010-05-14 12:43:01 +00001293 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001294#endif
drh8af6c222010-05-14 12:43:01 +00001295 pInode = inodeList;
1296 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1297 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001298 }
drh8af6c222010-05-14 12:43:01 +00001299 if( pInode==0 ){
1300 pInode = sqlite3_malloc( sizeof(*pInode) );
1301 if( pInode==0 ){
1302 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001303 }
drh8af6c222010-05-14 12:43:01 +00001304 memset(pInode, 0, sizeof(*pInode));
1305 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1306 pInode->nRef = 1;
1307 pInode->pNext = inodeList;
1308 pInode->pPrev = 0;
1309 if( inodeList ) inodeList->pPrev = pInode;
1310 inodeList = pInode;
1311 }else{
1312 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001313 }
drh8af6c222010-05-14 12:43:01 +00001314 *ppInode = pInode;
1315 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001316}
drh6c7d5c52008-11-21 20:32:33 +00001317
drhb959a012013-12-07 12:29:22 +00001318/*
1319** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1320*/
1321static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001322#if OS_VXWORKS
1323 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1324#else
drhb959a012013-12-07 12:29:22 +00001325 struct stat buf;
1326 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001327 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001328#endif
drhb959a012013-12-07 12:29:22 +00001329}
1330
aswift5b1a2562008-08-22 00:22:35 +00001331
1332/*
drhfbc7e882013-04-11 01:16:15 +00001333** Check a unixFile that is a database. Verify the following:
1334**
1335** (1) There is exactly one hard link on the file
1336** (2) The file is not a symbolic link
1337** (3) The file has not been renamed or unlinked
1338**
1339** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1340*/
1341static void verifyDbFile(unixFile *pFile){
1342 struct stat buf;
1343 int rc;
drh3044b512014-06-16 16:41:52 +00001344 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1345 /* One or more of the following warnings have already been issued. Do not
1346 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001347 return;
1348 }
1349 rc = osFstat(pFile->h, &buf);
1350 if( rc!=0 ){
1351 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1352 pFile->ctrlFlags |= UNIXFILE_WARNED;
1353 return;
1354 }
drh3044b512014-06-16 16:41:52 +00001355 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001356 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1357 pFile->ctrlFlags |= UNIXFILE_WARNED;
1358 return;
1359 }
1360 if( buf.st_nlink>1 ){
1361 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1362 pFile->ctrlFlags |= UNIXFILE_WARNED;
1363 return;
1364 }
drhb959a012013-12-07 12:29:22 +00001365 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001366 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1367 pFile->ctrlFlags |= UNIXFILE_WARNED;
1368 return;
1369 }
1370}
1371
1372
1373/*
danielk197713adf8a2004-06-03 16:08:41 +00001374** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001375** file by this or any other process. If such a lock is held, set *pResOut
1376** to a non-zero value otherwise *pResOut is set to zero. The return value
1377** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001378*/
danielk1977861f7452008-06-05 11:39:11 +00001379static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001380 int rc = SQLITE_OK;
1381 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001382 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001383
danielk1977861f7452008-06-05 11:39:11 +00001384 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1385
drh054889e2005-11-30 03:20:31 +00001386 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001387 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001388
1389 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001390 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001391 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001392 }
1393
drh2ac3ee92004-06-07 16:27:46 +00001394 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001395 */
danielk197709480a92009-02-09 05:32:32 +00001396#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001397 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001398 struct flock lock;
1399 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001400 lock.l_start = RESERVED_BYTE;
1401 lock.l_len = 1;
1402 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001403 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1404 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001405 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001406 } else if( lock.l_type!=F_UNLCK ){
1407 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001408 }
1409 }
danielk197709480a92009-02-09 05:32:32 +00001410#endif
danielk197713adf8a2004-06-03 16:08:41 +00001411
drh6c7d5c52008-11-21 20:32:33 +00001412 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001413 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001414
aswift5b1a2562008-08-22 00:22:35 +00001415 *pResOut = reserved;
1416 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001417}
1418
1419/*
drha7e61d82011-03-12 17:02:57 +00001420** Attempt to set a system-lock on the file pFile. The lock is
1421** described by pLock.
1422**
drh77197112011-03-15 19:08:48 +00001423** If the pFile was opened read/write from unix-excl, then the only lock
1424** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001425** the first time any lock is attempted. All subsequent system locking
1426** operations become no-ops. Locking operations still happen internally,
1427** in order to coordinate access between separate database connections
1428** within this process, but all of that is handled in memory and the
1429** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001430**
1431** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1432** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1433** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001434**
1435** Zero is returned if the call completes successfully, or -1 if a call
1436** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001437*/
1438static int unixFileLock(unixFile *pFile, struct flock *pLock){
1439 int rc;
drh3cb93392011-03-12 18:10:44 +00001440 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001441 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001442 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001443 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1444 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1445 ){
drh3cb93392011-03-12 18:10:44 +00001446 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001447 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001448 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001449 lock.l_whence = SEEK_SET;
1450 lock.l_start = SHARED_FIRST;
1451 lock.l_len = SHARED_SIZE;
1452 lock.l_type = F_WRLCK;
1453 rc = osFcntl(pFile->h, F_SETLK, &lock);
1454 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001455 pInode->bProcessLock = 1;
1456 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001457 }else{
1458 rc = 0;
1459 }
1460 }else{
1461 rc = osFcntl(pFile->h, F_SETLK, pLock);
1462 }
1463 return rc;
1464}
1465
1466/*
drh308c2a52010-05-14 11:30:18 +00001467** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001468** of the following:
1469**
drh2ac3ee92004-06-07 16:27:46 +00001470** (1) SHARED_LOCK
1471** (2) RESERVED_LOCK
1472** (3) PENDING_LOCK
1473** (4) EXCLUSIVE_LOCK
1474**
drhb3e04342004-06-08 00:47:47 +00001475** Sometimes when requesting one lock state, additional lock states
1476** are inserted in between. The locking might fail on one of the later
1477** transitions leaving the lock state different from what it started but
1478** still short of its goal. The following chart shows the allowed
1479** transitions and the inserted intermediate states:
1480**
1481** UNLOCKED -> SHARED
1482** SHARED -> RESERVED
1483** SHARED -> (PENDING) -> EXCLUSIVE
1484** RESERVED -> (PENDING) -> EXCLUSIVE
1485** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001486**
drha6abd042004-06-09 17:37:22 +00001487** This routine will only increase a lock. Use the sqlite3OsUnlock()
1488** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001489*/
drh308c2a52010-05-14 11:30:18 +00001490static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001491 /* The following describes the implementation of the various locks and
1492 ** lock transitions in terms of the POSIX advisory shared and exclusive
1493 ** lock primitives (called read-locks and write-locks below, to avoid
1494 ** confusion with SQLite lock names). The algorithms are complicated
1495 ** slightly in order to be compatible with windows systems simultaneously
1496 ** accessing the same database file, in case that is ever required.
1497 **
1498 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1499 ** byte', each single bytes at well known offsets, and the 'shared byte
1500 ** range', a range of 510 bytes at a well known offset.
1501 **
1502 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1503 ** byte'. If this is successful, a random byte from the 'shared byte
1504 ** range' is read-locked and the lock on the 'pending byte' released.
1505 **
danielk197790ba3bd2004-06-25 08:32:25 +00001506 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1507 ** A RESERVED lock is implemented by grabbing a write-lock on the
1508 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001509 **
1510 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001511 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1512 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1513 ** obtained, but existing SHARED locks are allowed to persist. A process
1514 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1515 ** This property is used by the algorithm for rolling back a journal file
1516 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001517 **
danielk197790ba3bd2004-06-25 08:32:25 +00001518 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1519 ** implemented by obtaining a write-lock on the entire 'shared byte
1520 ** range'. Since all other locks require a read-lock on one of the bytes
1521 ** within this range, this ensures that no other locks are held on the
1522 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001523 **
1524 ** The reason a single byte cannot be used instead of the 'shared byte
1525 ** range' is that some versions of windows do not support read-locks. By
1526 ** locking a random byte from a range, concurrent SHARED locks may exist
1527 ** even if the locking primitive used is always a write-lock.
1528 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001529 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001530 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001531 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001532 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001533 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001534
drh054889e2005-11-30 03:20:31 +00001535 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001536 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1537 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001538 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
1539 osGetpid()));
danielk19779a1d0ab2004-06-01 14:09:28 +00001540
1541 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001542 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001543 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001544 */
drh308c2a52010-05-14 11:30:18 +00001545 if( pFile->eFileLock>=eFileLock ){
1546 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1547 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001548 return SQLITE_OK;
1549 }
1550
drh0c2694b2009-09-03 16:23:44 +00001551 /* Make sure the locking sequence is correct.
1552 ** (1) We never move from unlocked to anything higher than shared lock.
1553 ** (2) SQLite never explicitly requests a pendig lock.
1554 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001555 */
drh308c2a52010-05-14 11:30:18 +00001556 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1557 assert( eFileLock!=PENDING_LOCK );
1558 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001559
drh8af6c222010-05-14 12:43:01 +00001560 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001561 */
drh6c7d5c52008-11-21 20:32:33 +00001562 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001563 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001564
danielk1977ad94b582007-08-20 06:44:22 +00001565 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001566 ** handle that precludes the requested lock, return BUSY.
1567 */
drh8af6c222010-05-14 12:43:01 +00001568 if( (pFile->eFileLock!=pInode->eFileLock &&
1569 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001570 ){
1571 rc = SQLITE_BUSY;
1572 goto end_lock;
1573 }
1574
1575 /* If a SHARED lock is requested, and some thread using this PID already
1576 ** has a SHARED or RESERVED lock, then increment reference counts and
1577 ** return SQLITE_OK.
1578 */
drh308c2a52010-05-14 11:30:18 +00001579 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001580 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001581 assert( eFileLock==SHARED_LOCK );
1582 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001583 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001584 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001585 pInode->nShared++;
1586 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001587 goto end_lock;
1588 }
1589
danielk19779a1d0ab2004-06-01 14:09:28 +00001590
drh3cde3bb2004-06-12 02:17:14 +00001591 /* A PENDING lock is needed before acquiring a SHARED lock and before
1592 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1593 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001594 */
drh0c2694b2009-09-03 16:23:44 +00001595 lock.l_len = 1L;
1596 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001597 if( eFileLock==SHARED_LOCK
1598 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001599 ){
drh308c2a52010-05-14 11:30:18 +00001600 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001601 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001602 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001603 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001604 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001605 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001606 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001607 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001608 goto end_lock;
1609 }
drh3cde3bb2004-06-12 02:17:14 +00001610 }
1611
1612
1613 /* If control gets to this point, then actually go ahead and make
1614 ** operating system calls for the specified lock.
1615 */
drh308c2a52010-05-14 11:30:18 +00001616 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001617 assert( pInode->nShared==0 );
1618 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001619 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001620
drh2ac3ee92004-06-07 16:27:46 +00001621 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001622 lock.l_start = SHARED_FIRST;
1623 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001624 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001625 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001626 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001627 }
dan661d71a2011-03-30 19:08:03 +00001628
drh2ac3ee92004-06-07 16:27:46 +00001629 /* Drop the temporary PENDING lock */
1630 lock.l_start = PENDING_BYTE;
1631 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001632 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001633 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1634 /* This could happen with a network mount */
1635 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001636 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001637 }
dan661d71a2011-03-30 19:08:03 +00001638
1639 if( rc ){
1640 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001641 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001642 }
dan661d71a2011-03-30 19:08:03 +00001643 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001644 }else{
drh308c2a52010-05-14 11:30:18 +00001645 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001646 pInode->nLock++;
1647 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001648 }
drh8af6c222010-05-14 12:43:01 +00001649 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001650 /* We are trying for an exclusive lock but another thread in this
1651 ** same process is still holding a shared lock. */
1652 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001653 }else{
drh3cde3bb2004-06-12 02:17:14 +00001654 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001655 ** assumed that there is a SHARED or greater lock on the file
1656 ** already.
1657 */
drh308c2a52010-05-14 11:30:18 +00001658 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001659 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001660
1661 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1662 if( eFileLock==RESERVED_LOCK ){
1663 lock.l_start = RESERVED_BYTE;
1664 lock.l_len = 1L;
1665 }else{
1666 lock.l_start = SHARED_FIRST;
1667 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001668 }
dan661d71a2011-03-30 19:08:03 +00001669
1670 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001671 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001672 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001673 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001674 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001675 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001676 }
drhbbd42a62004-05-22 17:41:58 +00001677 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001678
drh8f941bc2009-01-14 23:03:40 +00001679
drhd3d8c042012-05-29 17:02:40 +00001680#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001681 /* Set up the transaction-counter change checking flags when
1682 ** transitioning from a SHARED to a RESERVED lock. The change
1683 ** from SHARED to RESERVED marks the beginning of a normal
1684 ** write operation (not a hot journal rollback).
1685 */
1686 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001687 && pFile->eFileLock<=SHARED_LOCK
1688 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001689 ){
1690 pFile->transCntrChng = 0;
1691 pFile->dbUpdate = 0;
1692 pFile->inNormalWrite = 1;
1693 }
1694#endif
1695
1696
danielk1977ecb2a962004-06-02 06:30:16 +00001697 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001698 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001699 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001700 }else if( eFileLock==EXCLUSIVE_LOCK ){
1701 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001702 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001703 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001704
1705end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001706 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001707 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1708 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001709 return rc;
1710}
1711
1712/*
dan08da86a2009-08-21 17:18:03 +00001713** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001714** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001715*/
1716static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001717 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001718 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001719 p->pNext = pInode->pUnused;
1720 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001721 pFile->h = -1;
1722 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001723}
1724
1725/*
drh308c2a52010-05-14 11:30:18 +00001726** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001727** must be either NO_LOCK or SHARED_LOCK.
1728**
1729** If the locking level of the file descriptor is already at or below
1730** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001731**
1732** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1733** the byte range is divided into 2 parts and the first part is unlocked then
1734** set to a read lock, then the other part is simply unlocked. This works
1735** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1736** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001737*/
drha7e61d82011-03-12 17:02:57 +00001738static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001739 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001740 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001741 struct flock lock;
1742 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001743
drh054889e2005-11-30 03:20:31 +00001744 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001745 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001746 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh91eb93c2015-03-03 19:56:20 +00001747 osGetpid()));
drha6abd042004-06-09 17:37:22 +00001748
drh308c2a52010-05-14 11:30:18 +00001749 assert( eFileLock<=SHARED_LOCK );
1750 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001751 return SQLITE_OK;
1752 }
drh6c7d5c52008-11-21 20:32:33 +00001753 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001754 pInode = pFile->pInode;
1755 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001756 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001757 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001758
drhd3d8c042012-05-29 17:02:40 +00001759#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001760 /* When reducing a lock such that other processes can start
1761 ** reading the database file again, make sure that the
1762 ** transaction counter was updated if any part of the database
1763 ** file changed. If the transaction counter is not updated,
1764 ** other connections to the same file might not realize that
1765 ** the file has changed and hence might not know to flush their
1766 ** cache. The use of a stale cache can lead to database corruption.
1767 */
drh8f941bc2009-01-14 23:03:40 +00001768 pFile->inNormalWrite = 0;
1769#endif
1770
drh7ed97b92010-01-20 13:07:21 +00001771 /* downgrading to a shared lock on NFS involves clearing the write lock
1772 ** before establishing the readlock - to avoid a race condition we downgrade
1773 ** the lock in 2 blocks, so that part of the range will be covered by a
1774 ** write lock until the rest is covered by a read lock:
1775 ** 1: [WWWWW]
1776 ** 2: [....W]
1777 ** 3: [RRRRW]
1778 ** 4: [RRRR.]
1779 */
drh308c2a52010-05-14 11:30:18 +00001780 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001781#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001782 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001783 assert( handleNFSUnlock==0 );
1784#endif
1785#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001786 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001787 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001788 off_t divSize = SHARED_SIZE - 1;
1789
1790 lock.l_type = F_UNLCK;
1791 lock.l_whence = SEEK_SET;
1792 lock.l_start = SHARED_FIRST;
1793 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001794 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001795 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001796 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001797 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001798 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001799 }
1800 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001801 }
drh7ed97b92010-01-20 13:07:21 +00001802 lock.l_type = F_RDLCK;
1803 lock.l_whence = SEEK_SET;
1804 lock.l_start = SHARED_FIRST;
1805 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001806 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001807 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001808 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1809 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001810 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001811 }
1812 goto end_unlock;
1813 }
1814 lock.l_type = F_UNLCK;
1815 lock.l_whence = SEEK_SET;
1816 lock.l_start = SHARED_FIRST+divSize;
1817 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001818 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001819 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001820 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001821 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001822 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001823 }
1824 goto end_unlock;
1825 }
drh30f776f2011-02-25 03:25:07 +00001826 }else
1827#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1828 {
drh7ed97b92010-01-20 13:07:21 +00001829 lock.l_type = F_RDLCK;
1830 lock.l_whence = SEEK_SET;
1831 lock.l_start = SHARED_FIRST;
1832 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001833 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001834 /* In theory, the call to unixFileLock() cannot fail because another
1835 ** process is holding an incompatible lock. If it does, this
1836 ** indicates that the other process is not following the locking
1837 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1838 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1839 ** an assert to fail). */
1840 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001841 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001842 goto end_unlock;
1843 }
drh9c105bb2004-10-02 20:38:28 +00001844 }
1845 }
drhbbd42a62004-05-22 17:41:58 +00001846 lock.l_type = F_UNLCK;
1847 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001848 lock.l_start = PENDING_BYTE;
1849 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001850 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001851 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001852 }else{
danea83bc62011-04-01 11:56:32 +00001853 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001854 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001855 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001856 }
drhbbd42a62004-05-22 17:41:58 +00001857 }
drh308c2a52010-05-14 11:30:18 +00001858 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001859 /* Decrement the shared lock counter. Release the lock using an
1860 ** OS call only when all threads in this same process have released
1861 ** the lock.
1862 */
drh8af6c222010-05-14 12:43:01 +00001863 pInode->nShared--;
1864 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001865 lock.l_type = F_UNLCK;
1866 lock.l_whence = SEEK_SET;
1867 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001868 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001869 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001870 }else{
danea83bc62011-04-01 11:56:32 +00001871 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001872 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001873 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001874 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001875 }
drha6abd042004-06-09 17:37:22 +00001876 }
1877
drhbbd42a62004-05-22 17:41:58 +00001878 /* Decrement the count of locks against this same file. When the
1879 ** count reaches zero, close any other file descriptors whose close
1880 ** was deferred because of outstanding locks.
1881 */
drh8af6c222010-05-14 12:43:01 +00001882 pInode->nLock--;
1883 assert( pInode->nLock>=0 );
1884 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001885 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001886 }
1887 }
drhf2f105d2012-08-20 15:53:54 +00001888
aswift5b1a2562008-08-22 00:22:35 +00001889end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001890 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001891 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001892 return rc;
drhbbd42a62004-05-22 17:41:58 +00001893}
1894
1895/*
drh308c2a52010-05-14 11:30:18 +00001896** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001897** must be either NO_LOCK or SHARED_LOCK.
1898**
1899** If the locking level of the file descriptor is already at or below
1900** the requested locking level, this routine is a no-op.
1901*/
drh308c2a52010-05-14 11:30:18 +00001902static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001903#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001904 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001905#endif
drha7e61d82011-03-12 17:02:57 +00001906 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001907}
1908
mistachkine98844f2013-08-24 00:59:24 +00001909#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001910static int unixMapfile(unixFile *pFd, i64 nByte);
1911static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001912#endif
danf23da962013-03-23 21:00:41 +00001913
drh7ed97b92010-01-20 13:07:21 +00001914/*
danielk1977e339d652008-06-28 11:23:00 +00001915** This function performs the parts of the "close file" operation
1916** common to all locking schemes. It closes the directory and file
1917** handles, if they are valid, and sets all fields of the unixFile
1918** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001919**
1920** It is *not* necessary to hold the mutex when this routine is called,
1921** even on VxWorks. A mutex will be acquired on VxWorks by the
1922** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001923*/
1924static int closeUnixFile(sqlite3_file *id){
1925 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001926#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001927 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001928#endif
dan661d71a2011-03-30 19:08:03 +00001929 if( pFile->h>=0 ){
1930 robust_close(pFile, pFile->h, __LINE__);
1931 pFile->h = -1;
1932 }
1933#if OS_VXWORKS
1934 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001935 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001936 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001937 }
1938 vxworksReleaseFileId(pFile->pId);
1939 pFile->pId = 0;
1940 }
1941#endif
drh0bdbc902014-06-16 18:35:06 +00001942#ifdef SQLITE_UNLINK_AFTER_CLOSE
1943 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1944 osUnlink(pFile->zPath);
1945 sqlite3_free(*(char**)&pFile->zPath);
1946 pFile->zPath = 0;
1947 }
1948#endif
dan661d71a2011-03-30 19:08:03 +00001949 OSTRACE(("CLOSE %-3d\n", pFile->h));
1950 OpenCounter(-1);
1951 sqlite3_free(pFile->pUnused);
1952 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001953 return SQLITE_OK;
1954}
1955
1956/*
danielk1977e3026632004-06-22 11:29:02 +00001957** Close a file.
1958*/
danielk197762079062007-08-15 17:08:46 +00001959static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001960 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001961 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001962 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001963 unixUnlock(id, NO_LOCK);
1964 unixEnterMutex();
1965
1966 /* unixFile.pInode is always valid here. Otherwise, a different close
1967 ** routine (e.g. nolockClose()) would be called instead.
1968 */
1969 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1970 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1971 /* If there are outstanding locks, do not actually close the file just
1972 ** yet because that would clear those locks. Instead, add the file
1973 ** descriptor to pInode->pUnused list. It will be automatically closed
1974 ** when the last lock is cleared.
1975 */
1976 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001977 }
dan661d71a2011-03-30 19:08:03 +00001978 releaseInodeInfo(pFile);
1979 rc = closeUnixFile(id);
1980 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001981 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001982}
1983
drh734c9862008-11-28 15:37:20 +00001984/************** End of the posix advisory lock implementation *****************
1985******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001986
drh734c9862008-11-28 15:37:20 +00001987/******************************************************************************
1988****************************** No-op Locking **********************************
1989**
1990** Of the various locking implementations available, this is by far the
1991** simplest: locking is ignored. No attempt is made to lock the database
1992** file for reading or writing.
1993**
1994** This locking mode is appropriate for use on read-only databases
1995** (ex: databases that are burned into CD-ROM, for example.) It can
1996** also be used if the application employs some external mechanism to
1997** prevent simultaneous access of the same database by two or more
1998** database connections. But there is a serious risk of database
1999** corruption if this locking mode is used in situations where multiple
2000** database connections are accessing the same database file at the same
2001** time and one or more of those connections are writing.
2002*/
drhbfe66312006-10-03 17:40:40 +00002003
drh734c9862008-11-28 15:37:20 +00002004static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2005 UNUSED_PARAMETER(NotUsed);
2006 *pResOut = 0;
2007 return SQLITE_OK;
2008}
drh734c9862008-11-28 15:37:20 +00002009static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2010 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2011 return SQLITE_OK;
2012}
drh734c9862008-11-28 15:37:20 +00002013static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2014 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2015 return SQLITE_OK;
2016}
2017
2018/*
drh9b35ea62008-11-29 02:20:26 +00002019** Close the file.
drh734c9862008-11-28 15:37:20 +00002020*/
2021static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002022 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002023}
2024
2025/******************* End of the no-op lock implementation *********************
2026******************************************************************************/
2027
2028/******************************************************************************
2029************************* Begin dot-file Locking ******************************
2030**
mistachkin48864df2013-03-21 21:20:32 +00002031** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002032** files (really a directory) to control access to the database. This works
2033** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002034**
2035** (1) There is zero concurrency. A single reader blocks all other
2036** connections from reading or writing the database.
2037**
2038** (2) An application crash or power loss can leave stale lock files
2039** sitting around that need to be cleared manually.
2040**
2041** Nevertheless, a dotlock is an appropriate locking mode for use if no
2042** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002043**
drh9ef6bc42011-11-04 02:24:02 +00002044** Dotfile locking works by creating a subdirectory in the same directory as
2045** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002046** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002047** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002048*/
2049
2050/*
2051** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002052** lock directory.
drh734c9862008-11-28 15:37:20 +00002053*/
2054#define DOTLOCK_SUFFIX ".lock"
2055
drh7708e972008-11-29 00:56:52 +00002056/*
2057** This routine checks if there is a RESERVED lock held on the specified
2058** file by this or any other process. If such a lock is held, set *pResOut
2059** to a non-zero value otherwise *pResOut is set to zero. The return value
2060** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2061**
2062** In dotfile locking, either a lock exists or it does not. So in this
2063** variation of CheckReservedLock(), *pResOut is set to true if any lock
2064** is held on the file and false if the file is unlocked.
2065*/
drh734c9862008-11-28 15:37:20 +00002066static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2067 int rc = SQLITE_OK;
2068 int reserved = 0;
2069 unixFile *pFile = (unixFile*)id;
2070
2071 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2072
2073 assert( pFile );
2074
2075 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002076 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002077 /* Either this connection or some other connection in the same process
2078 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002079 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002080 }else{
2081 /* The lock is held if and only if the lockfile exists */
2082 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002083 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002084 }
drh308c2a52010-05-14 11:30:18 +00002085 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002086 *pResOut = reserved;
2087 return rc;
2088}
2089
drh7708e972008-11-29 00:56:52 +00002090/*
drh308c2a52010-05-14 11:30:18 +00002091** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002092** of the following:
2093**
2094** (1) SHARED_LOCK
2095** (2) RESERVED_LOCK
2096** (3) PENDING_LOCK
2097** (4) EXCLUSIVE_LOCK
2098**
2099** Sometimes when requesting one lock state, additional lock states
2100** are inserted in between. The locking might fail on one of the later
2101** transitions leaving the lock state different from what it started but
2102** still short of its goal. The following chart shows the allowed
2103** transitions and the inserted intermediate states:
2104**
2105** UNLOCKED -> SHARED
2106** SHARED -> RESERVED
2107** SHARED -> (PENDING) -> EXCLUSIVE
2108** RESERVED -> (PENDING) -> EXCLUSIVE
2109** PENDING -> EXCLUSIVE
2110**
2111** This routine will only increase a lock. Use the sqlite3OsUnlock()
2112** routine to lower a locking level.
2113**
2114** With dotfile locking, we really only support state (4): EXCLUSIVE.
2115** But we track the other locking levels internally.
2116*/
drh308c2a52010-05-14 11:30:18 +00002117static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002118 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002119 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002120 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002121
drh7708e972008-11-29 00:56:52 +00002122
2123 /* If we have any lock, then the lock file already exists. All we have
2124 ** to do is adjust our internal record of the lock level.
2125 */
drh308c2a52010-05-14 11:30:18 +00002126 if( pFile->eFileLock > NO_LOCK ){
2127 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002128 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002129#ifdef HAVE_UTIME
2130 utime(zLockFile, NULL);
2131#else
drh734c9862008-11-28 15:37:20 +00002132 utimes(zLockFile, NULL);
2133#endif
drh7708e972008-11-29 00:56:52 +00002134 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002135 }
2136
2137 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002138 rc = osMkdir(zLockFile, 0777);
2139 if( rc<0 ){
2140 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002141 int tErrno = errno;
2142 if( EEXIST == tErrno ){
2143 rc = SQLITE_BUSY;
2144 } else {
2145 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2146 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002147 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002148 }
2149 }
drh7708e972008-11-29 00:56:52 +00002150 return rc;
drh734c9862008-11-28 15:37:20 +00002151 }
drh734c9862008-11-28 15:37:20 +00002152
2153 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002154 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002155 return rc;
2156}
2157
drh7708e972008-11-29 00:56:52 +00002158/*
drh308c2a52010-05-14 11:30:18 +00002159** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002160** must be either NO_LOCK or SHARED_LOCK.
2161**
2162** If the locking level of the file descriptor is already at or below
2163** the requested locking level, this routine is a no-op.
2164**
2165** When the locking level reaches NO_LOCK, delete the lock file.
2166*/
drh308c2a52010-05-14 11:30:18 +00002167static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002168 unixFile *pFile = (unixFile*)id;
2169 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002170 int rc;
drh734c9862008-11-28 15:37:20 +00002171
2172 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002173 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002174 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002175 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002176
2177 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002178 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002179 return SQLITE_OK;
2180 }
drh7708e972008-11-29 00:56:52 +00002181
2182 /* To downgrade to shared, simply update our internal notion of the
2183 ** lock state. No need to mess with the file on disk.
2184 */
drh308c2a52010-05-14 11:30:18 +00002185 if( eFileLock==SHARED_LOCK ){
2186 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002187 return SQLITE_OK;
2188 }
2189
drh7708e972008-11-29 00:56:52 +00002190 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002191 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002192 rc = osRmdir(zLockFile);
2193 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2194 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002195 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002196 rc = 0;
drh734c9862008-11-28 15:37:20 +00002197 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002198 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002199 }
2200 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002201 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002202 }
2203 return rc;
2204 }
drh308c2a52010-05-14 11:30:18 +00002205 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002206 return SQLITE_OK;
2207}
2208
2209/*
drh9b35ea62008-11-29 02:20:26 +00002210** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002211*/
2212static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002213 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002214 if( id ){
2215 unixFile *pFile = (unixFile*)id;
2216 dotlockUnlock(id, NO_LOCK);
2217 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002218 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002219 }
drh734c9862008-11-28 15:37:20 +00002220 return rc;
2221}
2222/****************** End of the dot-file lock implementation *******************
2223******************************************************************************/
2224
2225/******************************************************************************
2226************************** Begin flock Locking ********************************
2227**
2228** Use the flock() system call to do file locking.
2229**
drh6b9d6dd2008-12-03 19:34:47 +00002230** flock() locking is like dot-file locking in that the various
2231** fine-grain locking levels supported by SQLite are collapsed into
2232** a single exclusive lock. In other words, SHARED, RESERVED, and
2233** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2234** still works when you do this, but concurrency is reduced since
2235** only a single process can be reading the database at a time.
2236**
drhe89b2912015-03-03 20:42:01 +00002237** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002238*/
drhe89b2912015-03-03 20:42:01 +00002239#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002240
drh6b9d6dd2008-12-03 19:34:47 +00002241/*
drhff812312011-02-23 13:33:46 +00002242** Retry flock() calls that fail with EINTR
2243*/
2244#ifdef EINTR
2245static int robust_flock(int fd, int op){
2246 int rc;
2247 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2248 return rc;
2249}
2250#else
drh5c819272011-02-23 14:00:12 +00002251# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002252#endif
2253
2254
2255/*
drh6b9d6dd2008-12-03 19:34:47 +00002256** This routine checks if there is a RESERVED lock held on the specified
2257** file by this or any other process. If such a lock is held, set *pResOut
2258** to a non-zero value otherwise *pResOut is set to zero. The return value
2259** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2260*/
drh734c9862008-11-28 15:37:20 +00002261static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2262 int rc = SQLITE_OK;
2263 int reserved = 0;
2264 unixFile *pFile = (unixFile*)id;
2265
2266 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2267
2268 assert( pFile );
2269
2270 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002271 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002272 reserved = 1;
2273 }
2274
2275 /* Otherwise see if some other process holds it. */
2276 if( !reserved ){
2277 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002278 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002279 if( !lrc ){
2280 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002281 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002282 if ( lrc ) {
2283 int tErrno = errno;
2284 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002285 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002286 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002287 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002288 rc = lrc;
2289 }
2290 }
2291 } else {
2292 int tErrno = errno;
2293 reserved = 1;
2294 /* someone else might have it reserved */
2295 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2296 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002297 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002298 rc = lrc;
2299 }
2300 }
2301 }
drh308c2a52010-05-14 11:30:18 +00002302 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002303
2304#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2305 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2306 rc = SQLITE_OK;
2307 reserved=1;
2308 }
2309#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2310 *pResOut = reserved;
2311 return rc;
2312}
2313
drh6b9d6dd2008-12-03 19:34:47 +00002314/*
drh308c2a52010-05-14 11:30:18 +00002315** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002316** of the following:
2317**
2318** (1) SHARED_LOCK
2319** (2) RESERVED_LOCK
2320** (3) PENDING_LOCK
2321** (4) EXCLUSIVE_LOCK
2322**
2323** Sometimes when requesting one lock state, additional lock states
2324** are inserted in between. The locking might fail on one of the later
2325** transitions leaving the lock state different from what it started but
2326** still short of its goal. The following chart shows the allowed
2327** transitions and the inserted intermediate states:
2328**
2329** UNLOCKED -> SHARED
2330** SHARED -> RESERVED
2331** SHARED -> (PENDING) -> EXCLUSIVE
2332** RESERVED -> (PENDING) -> EXCLUSIVE
2333** PENDING -> EXCLUSIVE
2334**
2335** flock() only really support EXCLUSIVE locks. We track intermediate
2336** lock states in the sqlite3_file structure, but all locks SHARED or
2337** above are really EXCLUSIVE locks and exclude all other processes from
2338** access the file.
2339**
2340** This routine will only increase a lock. Use the sqlite3OsUnlock()
2341** routine to lower a locking level.
2342*/
drh308c2a52010-05-14 11:30:18 +00002343static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002344 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002345 unixFile *pFile = (unixFile*)id;
2346
2347 assert( pFile );
2348
2349 /* if we already have a lock, it is exclusive.
2350 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002351 if (pFile->eFileLock > NO_LOCK) {
2352 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002353 return SQLITE_OK;
2354 }
2355
2356 /* grab an exclusive lock */
2357
drhff812312011-02-23 13:33:46 +00002358 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002359 int tErrno = errno;
2360 /* didn't get, must be busy */
2361 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2362 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002363 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002364 }
2365 } else {
2366 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002367 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002368 }
drh308c2a52010-05-14 11:30:18 +00002369 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2370 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002371#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2372 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2373 rc = SQLITE_BUSY;
2374 }
2375#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2376 return rc;
2377}
2378
drh6b9d6dd2008-12-03 19:34:47 +00002379
2380/*
drh308c2a52010-05-14 11:30:18 +00002381** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002382** must be either NO_LOCK or SHARED_LOCK.
2383**
2384** If the locking level of the file descriptor is already at or below
2385** the requested locking level, this routine is a no-op.
2386*/
drh308c2a52010-05-14 11:30:18 +00002387static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002388 unixFile *pFile = (unixFile*)id;
2389
2390 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002391 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002392 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002393 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002394
2395 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002396 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002397 return SQLITE_OK;
2398 }
2399
2400 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002401 if (eFileLock==SHARED_LOCK) {
2402 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002403 return SQLITE_OK;
2404 }
2405
2406 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002407 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002408#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002409 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002410#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002411 return SQLITE_IOERR_UNLOCK;
2412 }else{
drh308c2a52010-05-14 11:30:18 +00002413 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002414 return SQLITE_OK;
2415 }
2416}
2417
2418/*
2419** Close a file.
2420*/
2421static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002422 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002423 if( id ){
2424 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002425 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002426 }
drh5a05be12012-10-09 18:51:44 +00002427 return rc;
drh734c9862008-11-28 15:37:20 +00002428}
2429
2430#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2431
2432/******************* End of the flock lock implementation *********************
2433******************************************************************************/
2434
2435/******************************************************************************
2436************************ Begin Named Semaphore Locking ************************
2437**
2438** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002439**
2440** Semaphore locking is like dot-lock and flock in that it really only
2441** supports EXCLUSIVE locking. Only a single process can read or write
2442** the database file at a time. This reduces potential concurrency, but
2443** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002444*/
2445#if OS_VXWORKS
2446
drh6b9d6dd2008-12-03 19:34:47 +00002447/*
2448** This routine checks if there is a RESERVED lock held on the specified
2449** file by this or any other process. If such a lock is held, set *pResOut
2450** to a non-zero value otherwise *pResOut is set to zero. The return value
2451** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2452*/
drh8cd5b252015-03-02 22:06:43 +00002453static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002454 int rc = SQLITE_OK;
2455 int reserved = 0;
2456 unixFile *pFile = (unixFile*)id;
2457
2458 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2459
2460 assert( pFile );
2461
2462 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002463 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002464 reserved = 1;
2465 }
2466
2467 /* Otherwise see if some other process holds it. */
2468 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002469 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002470
2471 if( sem_trywait(pSem)==-1 ){
2472 int tErrno = errno;
2473 if( EAGAIN != tErrno ){
2474 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002475 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002476 } else {
2477 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002478 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002479 }
2480 }else{
2481 /* we could have it if we want it */
2482 sem_post(pSem);
2483 }
2484 }
drh308c2a52010-05-14 11:30:18 +00002485 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002486
2487 *pResOut = reserved;
2488 return rc;
2489}
2490
drh6b9d6dd2008-12-03 19:34:47 +00002491/*
drh308c2a52010-05-14 11:30:18 +00002492** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002493** of the following:
2494**
2495** (1) SHARED_LOCK
2496** (2) RESERVED_LOCK
2497** (3) PENDING_LOCK
2498** (4) EXCLUSIVE_LOCK
2499**
2500** Sometimes when requesting one lock state, additional lock states
2501** are inserted in between. The locking might fail on one of the later
2502** transitions leaving the lock state different from what it started but
2503** still short of its goal. The following chart shows the allowed
2504** transitions and the inserted intermediate states:
2505**
2506** UNLOCKED -> SHARED
2507** SHARED -> RESERVED
2508** SHARED -> (PENDING) -> EXCLUSIVE
2509** RESERVED -> (PENDING) -> EXCLUSIVE
2510** PENDING -> EXCLUSIVE
2511**
2512** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2513** lock states in the sqlite3_file structure, but all locks SHARED or
2514** above are really EXCLUSIVE locks and exclude all other processes from
2515** access the file.
2516**
2517** This routine will only increase a lock. Use the sqlite3OsUnlock()
2518** routine to lower a locking level.
2519*/
drh8cd5b252015-03-02 22:06:43 +00002520static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002521 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002522 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002523 int rc = SQLITE_OK;
2524
2525 /* if we already have a lock, it is exclusive.
2526 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002527 if (pFile->eFileLock > NO_LOCK) {
2528 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002529 rc = SQLITE_OK;
2530 goto sem_end_lock;
2531 }
2532
2533 /* lock semaphore now but bail out when already locked. */
2534 if( sem_trywait(pSem)==-1 ){
2535 rc = SQLITE_BUSY;
2536 goto sem_end_lock;
2537 }
2538
2539 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002540 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002541
2542 sem_end_lock:
2543 return rc;
2544}
2545
drh6b9d6dd2008-12-03 19:34:47 +00002546/*
drh308c2a52010-05-14 11:30:18 +00002547** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002548** must be either NO_LOCK or SHARED_LOCK.
2549**
2550** If the locking level of the file descriptor is already at or below
2551** the requested locking level, this routine is a no-op.
2552*/
drh8cd5b252015-03-02 22:06:43 +00002553static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002554 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002555 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002556
2557 assert( pFile );
2558 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002559 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh91eb93c2015-03-03 19:56:20 +00002560 pFile->eFileLock, osGetpid()));
drh308c2a52010-05-14 11:30:18 +00002561 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002562
2563 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002564 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002565 return SQLITE_OK;
2566 }
2567
2568 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002569 if (eFileLock==SHARED_LOCK) {
2570 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002571 return SQLITE_OK;
2572 }
2573
2574 /* no, really unlock. */
2575 if ( sem_post(pSem)==-1 ) {
2576 int rc, tErrno = errno;
2577 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2578 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002579 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002580 }
2581 return rc;
2582 }
drh308c2a52010-05-14 11:30:18 +00002583 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002584 return SQLITE_OK;
2585}
2586
2587/*
2588 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002589 */
drh8cd5b252015-03-02 22:06:43 +00002590static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002591 if( id ){
2592 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002593 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002594 assert( pFile );
2595 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002596 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002597 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002598 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002599 }
2600 return SQLITE_OK;
2601}
2602
2603#endif /* OS_VXWORKS */
2604/*
2605** Named semaphore locking is only available on VxWorks.
2606**
2607*************** End of the named semaphore lock implementation ****************
2608******************************************************************************/
2609
2610
2611/******************************************************************************
2612*************************** Begin AFP Locking *********************************
2613**
2614** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2615** on Apple Macintosh computers - both OS9 and OSX.
2616**
2617** Third-party implementations of AFP are available. But this code here
2618** only works on OSX.
2619*/
2620
drhd2cb50b2009-01-09 21:41:17 +00002621#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002622/*
2623** The afpLockingContext structure contains all afp lock specific state
2624*/
drhbfe66312006-10-03 17:40:40 +00002625typedef struct afpLockingContext afpLockingContext;
2626struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002627 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002628 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002629};
2630
2631struct ByteRangeLockPB2
2632{
2633 unsigned long long offset; /* offset to first byte to lock */
2634 unsigned long long length; /* nbr of bytes to lock */
2635 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2636 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2637 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2638 int fd; /* file desc to assoc this lock with */
2639};
2640
drhfd131da2007-08-07 17:13:03 +00002641#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002642
drh6b9d6dd2008-12-03 19:34:47 +00002643/*
2644** This is a utility for setting or clearing a bit-range lock on an
2645** AFP filesystem.
2646**
2647** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2648*/
2649static int afpSetLock(
2650 const char *path, /* Name of the file to be locked or unlocked */
2651 unixFile *pFile, /* Open file descriptor on path */
2652 unsigned long long offset, /* First byte to be locked */
2653 unsigned long long length, /* Number of bytes to lock */
2654 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002655){
drh6b9d6dd2008-12-03 19:34:47 +00002656 struct ByteRangeLockPB2 pb;
2657 int err;
drhbfe66312006-10-03 17:40:40 +00002658
2659 pb.unLockFlag = setLockFlag ? 0 : 1;
2660 pb.startEndFlag = 0;
2661 pb.offset = offset;
2662 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002663 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002664
drh308c2a52010-05-14 11:30:18 +00002665 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002666 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002667 offset, length));
drhbfe66312006-10-03 17:40:40 +00002668 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2669 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002670 int rc;
2671 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002672 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2673 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002674#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2675 rc = SQLITE_BUSY;
2676#else
drh734c9862008-11-28 15:37:20 +00002677 rc = sqliteErrorFromPosixError(tErrno,
2678 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002679#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002680 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002681 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002682 }
2683 return rc;
drhbfe66312006-10-03 17:40:40 +00002684 } else {
aswift5b1a2562008-08-22 00:22:35 +00002685 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002686 }
2687}
2688
drh6b9d6dd2008-12-03 19:34:47 +00002689/*
2690** This routine checks if there is a RESERVED lock held on the specified
2691** file by this or any other process. If such a lock is held, set *pResOut
2692** to a non-zero value otherwise *pResOut is set to zero. The return value
2693** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2694*/
danielk1977e339d652008-06-28 11:23:00 +00002695static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002696 int rc = SQLITE_OK;
2697 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002698 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002699 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002700
aswift5b1a2562008-08-22 00:22:35 +00002701 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2702
2703 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002704 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002705 if( context->reserved ){
2706 *pResOut = 1;
2707 return SQLITE_OK;
2708 }
drh8af6c222010-05-14 12:43:01 +00002709 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002710
2711 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002712 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002713 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002714 }
2715
2716 /* Otherwise see if some other process holds it.
2717 */
aswift5b1a2562008-08-22 00:22:35 +00002718 if( !reserved ){
2719 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002720 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002721 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002722 /* if we succeeded in taking the reserved lock, unlock it to restore
2723 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002724 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002725 } else {
2726 /* if we failed to get the lock then someone else must have it */
2727 reserved = 1;
2728 }
2729 if( IS_LOCK_ERROR(lrc) ){
2730 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002731 }
2732 }
drhbfe66312006-10-03 17:40:40 +00002733
drh7ed97b92010-01-20 13:07:21 +00002734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002735 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002736
2737 *pResOut = reserved;
2738 return rc;
drhbfe66312006-10-03 17:40:40 +00002739}
2740
drh6b9d6dd2008-12-03 19:34:47 +00002741/*
drh308c2a52010-05-14 11:30:18 +00002742** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002743** of the following:
2744**
2745** (1) SHARED_LOCK
2746** (2) RESERVED_LOCK
2747** (3) PENDING_LOCK
2748** (4) EXCLUSIVE_LOCK
2749**
2750** Sometimes when requesting one lock state, additional lock states
2751** are inserted in between. The locking might fail on one of the later
2752** transitions leaving the lock state different from what it started but
2753** still short of its goal. The following chart shows the allowed
2754** transitions and the inserted intermediate states:
2755**
2756** UNLOCKED -> SHARED
2757** SHARED -> RESERVED
2758** SHARED -> (PENDING) -> EXCLUSIVE
2759** RESERVED -> (PENDING) -> EXCLUSIVE
2760** PENDING -> EXCLUSIVE
2761**
2762** This routine will only increase a lock. Use the sqlite3OsUnlock()
2763** routine to lower a locking level.
2764*/
drh308c2a52010-05-14 11:30:18 +00002765static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002766 int rc = SQLITE_OK;
2767 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002768 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002769 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002770
2771 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002772 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2773 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00002774 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid()));
drh339eb0b2008-03-07 15:34:11 +00002775
drhbfe66312006-10-03 17:40:40 +00002776 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002777 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002778 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002779 */
drh308c2a52010-05-14 11:30:18 +00002780 if( pFile->eFileLock>=eFileLock ){
2781 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2782 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002783 return SQLITE_OK;
2784 }
2785
2786 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002787 ** (1) We never move from unlocked to anything higher than shared lock.
2788 ** (2) SQLite never explicitly requests a pendig lock.
2789 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002790 */
drh308c2a52010-05-14 11:30:18 +00002791 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2792 assert( eFileLock!=PENDING_LOCK );
2793 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002794
drh8af6c222010-05-14 12:43:01 +00002795 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002796 */
drh6c7d5c52008-11-21 20:32:33 +00002797 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002798 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002799
2800 /* If some thread using this PID has a lock via a different unixFile*
2801 ** handle that precludes the requested lock, return BUSY.
2802 */
drh8af6c222010-05-14 12:43:01 +00002803 if( (pFile->eFileLock!=pInode->eFileLock &&
2804 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002805 ){
2806 rc = SQLITE_BUSY;
2807 goto afp_end_lock;
2808 }
2809
2810 /* If a SHARED lock is requested, and some thread using this PID already
2811 ** has a SHARED or RESERVED lock, then increment reference counts and
2812 ** return SQLITE_OK.
2813 */
drh308c2a52010-05-14 11:30:18 +00002814 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002815 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002816 assert( eFileLock==SHARED_LOCK );
2817 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002818 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002819 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002820 pInode->nShared++;
2821 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002822 goto afp_end_lock;
2823 }
drhbfe66312006-10-03 17:40:40 +00002824
2825 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002826 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2827 ** be released.
2828 */
drh308c2a52010-05-14 11:30:18 +00002829 if( eFileLock==SHARED_LOCK
2830 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002831 ){
2832 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002833 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002834 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002835 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002836 goto afp_end_lock;
2837 }
2838 }
2839
2840 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002841 ** operating system calls for the specified lock.
2842 */
drh308c2a52010-05-14 11:30:18 +00002843 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002844 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002845 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002846
drh8af6c222010-05-14 12:43:01 +00002847 assert( pInode->nShared==0 );
2848 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002849
2850 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002851 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002852 /* note that the quality of the randomness doesn't matter that much */
2853 lk = random();
drh8af6c222010-05-14 12:43:01 +00002854 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002855 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002856 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002857 if( IS_LOCK_ERROR(lrc1) ){
2858 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002859 }
aswift5b1a2562008-08-22 00:22:35 +00002860 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002861 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002862
aswift5b1a2562008-08-22 00:22:35 +00002863 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002864 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002865 rc = lrc1;
2866 goto afp_end_lock;
2867 } else if( IS_LOCK_ERROR(lrc2) ){
2868 rc = lrc2;
2869 goto afp_end_lock;
2870 } else if( lrc1 != SQLITE_OK ) {
2871 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002872 } else {
drh308c2a52010-05-14 11:30:18 +00002873 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002874 pInode->nLock++;
2875 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002876 }
drh8af6c222010-05-14 12:43:01 +00002877 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002878 /* We are trying for an exclusive lock but another thread in this
2879 ** same process is still holding a shared lock. */
2880 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002881 }else{
2882 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2883 ** assumed that there is a SHARED or greater lock on the file
2884 ** already.
2885 */
2886 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002887 assert( 0!=pFile->eFileLock );
2888 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002889 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002890 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002891 if( !failed ){
2892 context->reserved = 1;
2893 }
drhbfe66312006-10-03 17:40:40 +00002894 }
drh308c2a52010-05-14 11:30:18 +00002895 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002896 /* Acquire an EXCLUSIVE lock */
2897
2898 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002899 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002900 */
drh6b9d6dd2008-12-03 19:34:47 +00002901 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002902 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002903 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002904 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002905 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002906 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002907 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002908 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002909 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2910 ** a critical I/O error
2911 */
2912 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2913 SQLITE_IOERR_LOCK;
2914 goto afp_end_lock;
2915 }
2916 }else{
aswift5b1a2562008-08-22 00:22:35 +00002917 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002918 }
2919 }
aswift5b1a2562008-08-22 00:22:35 +00002920 if( failed ){
2921 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002922 }
2923 }
2924
2925 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002926 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002927 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002928 }else if( eFileLock==EXCLUSIVE_LOCK ){
2929 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002930 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002931 }
2932
2933afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002934 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002935 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2936 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002937 return rc;
2938}
2939
2940/*
drh308c2a52010-05-14 11:30:18 +00002941** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002942** must be either NO_LOCK or SHARED_LOCK.
2943**
2944** If the locking level of the file descriptor is already at or below
2945** the requested locking level, this routine is a no-op.
2946*/
drh308c2a52010-05-14 11:30:18 +00002947static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002948 int rc = SQLITE_OK;
2949 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002950 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002951 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2952 int skipShared = 0;
2953#ifdef SQLITE_TEST
2954 int h = pFile->h;
2955#endif
drhbfe66312006-10-03 17:40:40 +00002956
2957 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002958 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002959 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh91eb93c2015-03-03 19:56:20 +00002960 osGetpid()));
aswift5b1a2562008-08-22 00:22:35 +00002961
drh308c2a52010-05-14 11:30:18 +00002962 assert( eFileLock<=SHARED_LOCK );
2963 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002964 return SQLITE_OK;
2965 }
drh6c7d5c52008-11-21 20:32:33 +00002966 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002967 pInode = pFile->pInode;
2968 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002969 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002970 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002971 SimulateIOErrorBenign(1);
2972 SimulateIOError( h=(-1) )
2973 SimulateIOErrorBenign(0);
2974
drhd3d8c042012-05-29 17:02:40 +00002975#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002976 /* When reducing a lock such that other processes can start
2977 ** reading the database file again, make sure that the
2978 ** transaction counter was updated if any part of the database
2979 ** file changed. If the transaction counter is not updated,
2980 ** other connections to the same file might not realize that
2981 ** the file has changed and hence might not know to flush their
2982 ** cache. The use of a stale cache can lead to database corruption.
2983 */
2984 assert( pFile->inNormalWrite==0
2985 || pFile->dbUpdate==0
2986 || pFile->transCntrChng==1 );
2987 pFile->inNormalWrite = 0;
2988#endif
aswiftaebf4132008-11-21 00:10:35 +00002989
drh308c2a52010-05-14 11:30:18 +00002990 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002991 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002992 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002993 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002994 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002995 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2996 } else {
2997 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002998 }
2999 }
drh308c2a52010-05-14 11:30:18 +00003000 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003001 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003002 }
drh308c2a52010-05-14 11:30:18 +00003003 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003004 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3005 if( !rc ){
3006 context->reserved = 0;
3007 }
aswiftaebf4132008-11-21 00:10:35 +00003008 }
drh8af6c222010-05-14 12:43:01 +00003009 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3010 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003011 }
aswiftaebf4132008-11-21 00:10:35 +00003012 }
drh308c2a52010-05-14 11:30:18 +00003013 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003014
drh7ed97b92010-01-20 13:07:21 +00003015 /* Decrement the shared lock counter. Release the lock using an
3016 ** OS call only when all threads in this same process have released
3017 ** the lock.
3018 */
drh8af6c222010-05-14 12:43:01 +00003019 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3020 pInode->nShared--;
3021 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003022 SimulateIOErrorBenign(1);
3023 SimulateIOError( h=(-1) )
3024 SimulateIOErrorBenign(0);
3025 if( !skipShared ){
3026 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3027 }
3028 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003029 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003030 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003031 }
3032 }
3033 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003034 pInode->nLock--;
3035 assert( pInode->nLock>=0 );
3036 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003037 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003038 }
3039 }
drhbfe66312006-10-03 17:40:40 +00003040 }
drh7ed97b92010-01-20 13:07:21 +00003041
drh6c7d5c52008-11-21 20:32:33 +00003042 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003043 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003044 return rc;
3045}
3046
3047/*
drh339eb0b2008-03-07 15:34:11 +00003048** Close a file & cleanup AFP specific locking context
3049*/
danielk1977e339d652008-06-28 11:23:00 +00003050static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003051 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003052 if( id ){
3053 unixFile *pFile = (unixFile*)id;
3054 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003055 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003056 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003057 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003058 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003059 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003060 ** the last lock is cleared.
3061 */
dan08da86a2009-08-21 17:18:03 +00003062 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003063 }
danb0ac3e32010-06-16 10:55:42 +00003064 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003065 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003066 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003067 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003068 }
drh7ed97b92010-01-20 13:07:21 +00003069 return rc;
drhbfe66312006-10-03 17:40:40 +00003070}
3071
drhd2cb50b2009-01-09 21:41:17 +00003072#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003073/*
3074** The code above is the AFP lock implementation. The code is specific
3075** to MacOSX and does not work on other unix platforms. No alternative
3076** is available. If you don't compile for a mac, then the "unix-afp"
3077** VFS is not available.
3078**
3079********************* End of the AFP lock implementation **********************
3080******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003081
drh7ed97b92010-01-20 13:07:21 +00003082/******************************************************************************
3083*************************** Begin NFS Locking ********************************/
3084
3085#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3086/*
drh308c2a52010-05-14 11:30:18 +00003087 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003088 ** must be either NO_LOCK or SHARED_LOCK.
3089 **
3090 ** If the locking level of the file descriptor is already at or below
3091 ** the requested locking level, this routine is a no-op.
3092 */
drh308c2a52010-05-14 11:30:18 +00003093static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003094 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003095}
3096
3097#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3098/*
3099** The code above is the NFS lock implementation. The code is specific
3100** to MacOSX and does not work on other unix platforms. No alternative
3101** is available.
3102**
3103********************* End of the NFS lock implementation **********************
3104******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003105
3106/******************************************************************************
3107**************** Non-locking sqlite3_file methods *****************************
3108**
3109** The next division contains implementations for all methods of the
3110** sqlite3_file object other than the locking methods. The locking
3111** methods were defined in divisions above (one locking method per
3112** division). Those methods that are common to all locking modes
3113** are gather together into this division.
3114*/
drhbfe66312006-10-03 17:40:40 +00003115
3116/*
drh734c9862008-11-28 15:37:20 +00003117** Seek to the offset passed as the second argument, then read cnt
3118** bytes into pBuf. Return the number of bytes actually read.
3119**
3120** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3121** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3122** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003123** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003124** See tickets #2741 and #2681.
3125**
3126** To avoid stomping the errno value on a failed read the lastErrno value
3127** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003128*/
drh734c9862008-11-28 15:37:20 +00003129static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3130 int got;
drh58024642011-11-07 18:16:00 +00003131 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003132#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003133 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003134#endif
drh734c9862008-11-28 15:37:20 +00003135 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003136 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003137 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003138 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003139 do{
drh734c9862008-11-28 15:37:20 +00003140#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003141 got = osPread(id->h, pBuf, cnt, offset);
3142 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003143#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003144 got = osPread64(id->h, pBuf, cnt, offset);
3145 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003146#else
drh58024642011-11-07 18:16:00 +00003147 newOffset = lseek(id->h, offset, SEEK_SET);
3148 SimulateIOError( newOffset-- );
3149 if( newOffset!=offset ){
3150 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003151 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003152 }else{
drh4bf66fd2015-02-19 02:43:02 +00003153 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003154 }
3155 return -1;
drh734c9862008-11-28 15:37:20 +00003156 }
drh58024642011-11-07 18:16:00 +00003157 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003158#endif
drh58024642011-11-07 18:16:00 +00003159 if( got==cnt ) break;
3160 if( got<0 ){
3161 if( errno==EINTR ){ got = 1; continue; }
3162 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003163 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003164 break;
3165 }else if( got>0 ){
3166 cnt -= got;
3167 offset += got;
3168 prior += got;
3169 pBuf = (void*)(got + (char*)pBuf);
3170 }
3171 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003172 TIMER_END;
drh58024642011-11-07 18:16:00 +00003173 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3174 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3175 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003176}
3177
3178/*
drh734c9862008-11-28 15:37:20 +00003179** Read data from a file into a buffer. Return SQLITE_OK if all
3180** bytes were read successfully and SQLITE_IOERR if anything goes
3181** wrong.
drh339eb0b2008-03-07 15:34:11 +00003182*/
drh734c9862008-11-28 15:37:20 +00003183static int unixRead(
3184 sqlite3_file *id,
3185 void *pBuf,
3186 int amt,
3187 sqlite3_int64 offset
3188){
dan08da86a2009-08-21 17:18:03 +00003189 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003190 int got;
3191 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003192 assert( offset>=0 );
3193 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003194
dan08da86a2009-08-21 17:18:03 +00003195 /* If this is a database file (not a journal, master-journal or temp
3196 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003197#if 0
dane946c392009-08-22 11:39:46 +00003198 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003199 || offset>=PENDING_BYTE+512
3200 || offset+amt<=PENDING_BYTE
3201 );
dan7c246102010-04-12 19:00:29 +00003202#endif
drh08c6d442009-02-09 17:34:07 +00003203
drh9b4c59f2013-04-15 17:03:42 +00003204#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003205 /* Deal with as much of this read request as possible by transfering
3206 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003207 if( offset<pFile->mmapSize ){
3208 if( offset+amt <= pFile->mmapSize ){
3209 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3210 return SQLITE_OK;
3211 }else{
3212 int nCopy = pFile->mmapSize - offset;
3213 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3214 pBuf = &((u8 *)pBuf)[nCopy];
3215 amt -= nCopy;
3216 offset += nCopy;
3217 }
3218 }
drh6e0b6d52013-04-09 16:19:20 +00003219#endif
danf23da962013-03-23 21:00:41 +00003220
dan08da86a2009-08-21 17:18:03 +00003221 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003222 if( got==amt ){
3223 return SQLITE_OK;
3224 }else if( got<0 ){
3225 /* lastErrno set by seekAndRead */
3226 return SQLITE_IOERR_READ;
3227 }else{
drh4bf66fd2015-02-19 02:43:02 +00003228 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003229 /* Unread parts of the buffer must be zero-filled */
3230 memset(&((char*)pBuf)[got], 0, amt-got);
3231 return SQLITE_IOERR_SHORT_READ;
3232 }
3233}
3234
3235/*
dan47a2b4a2013-04-26 16:09:29 +00003236** Attempt to seek the file-descriptor passed as the first argument to
3237** absolute offset iOff, then attempt to write nBuf bytes of data from
3238** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3239** return the actual number of bytes written (which may be less than
3240** nBuf).
3241*/
3242static int seekAndWriteFd(
3243 int fd, /* File descriptor to write to */
3244 i64 iOff, /* File offset to begin writing at */
3245 const void *pBuf, /* Copy data from this buffer to the file */
3246 int nBuf, /* Size of buffer pBuf in bytes */
3247 int *piErrno /* OUT: Error number if error occurs */
3248){
3249 int rc = 0; /* Value returned by system call */
3250
3251 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003252 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003253 nBuf &= 0x1ffff;
3254 TIMER_START;
3255
3256#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003257 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003258#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003259 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003260#else
3261 do{
3262 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3263 SimulateIOError( iSeek-- );
3264
3265 if( iSeek!=iOff ){
3266 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3267 return -1;
3268 }
3269 rc = osWrite(fd, pBuf, nBuf);
3270 }while( rc<0 && errno==EINTR );
3271#endif
3272
3273 TIMER_END;
3274 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3275
3276 if( rc<0 && piErrno ) *piErrno = errno;
3277 return rc;
3278}
3279
3280
3281/*
drh734c9862008-11-28 15:37:20 +00003282** Seek to the offset in id->offset then read cnt bytes into pBuf.
3283** Return the number of bytes actually read. Update the offset.
3284**
3285** To avoid stomping the errno value on a failed write the lastErrno value
3286** is set before returning.
3287*/
3288static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003289 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003290}
3291
3292
3293/*
3294** Write data from a buffer into a file. Return SQLITE_OK on success
3295** or some other error code on failure.
3296*/
3297static int unixWrite(
3298 sqlite3_file *id,
3299 const void *pBuf,
3300 int amt,
3301 sqlite3_int64 offset
3302){
dan08da86a2009-08-21 17:18:03 +00003303 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003304 int wrote = 0;
3305 assert( id );
3306 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003307
dan08da86a2009-08-21 17:18:03 +00003308 /* If this is a database file (not a journal, master-journal or temp
3309 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003310#if 0
dane946c392009-08-22 11:39:46 +00003311 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003312 || offset>=PENDING_BYTE+512
3313 || offset+amt<=PENDING_BYTE
3314 );
dan7c246102010-04-12 19:00:29 +00003315#endif
drh08c6d442009-02-09 17:34:07 +00003316
drhd3d8c042012-05-29 17:02:40 +00003317#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003318 /* If we are doing a normal write to a database file (as opposed to
3319 ** doing a hot-journal rollback or a write to some file other than a
3320 ** normal database file) then record the fact that the database
3321 ** has changed. If the transaction counter is modified, record that
3322 ** fact too.
3323 */
dan08da86a2009-08-21 17:18:03 +00003324 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003325 pFile->dbUpdate = 1; /* The database has been modified */
3326 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003327 int rc;
drh8f941bc2009-01-14 23:03:40 +00003328 char oldCntr[4];
3329 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003330 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003331 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003332 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003333 pFile->transCntrChng = 1; /* The transaction counter has changed */
3334 }
3335 }
3336 }
3337#endif
3338
drh9b4c59f2013-04-15 17:03:42 +00003339#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003340 /* Deal with as much of this write request as possible by transfering
3341 ** data from the memory mapping using memcpy(). */
3342 if( offset<pFile->mmapSize ){
3343 if( offset+amt <= pFile->mmapSize ){
3344 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3345 return SQLITE_OK;
3346 }else{
3347 int nCopy = pFile->mmapSize - offset;
3348 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3349 pBuf = &((u8 *)pBuf)[nCopy];
3350 amt -= nCopy;
3351 offset += nCopy;
3352 }
3353 }
drh6e0b6d52013-04-09 16:19:20 +00003354#endif
danf23da962013-03-23 21:00:41 +00003355
dan08da86a2009-08-21 17:18:03 +00003356 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003357 amt -= wrote;
3358 offset += wrote;
3359 pBuf = &((char*)pBuf)[wrote];
3360 }
3361 SimulateIOError(( wrote=(-1), amt=1 ));
3362 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003363
drh734c9862008-11-28 15:37:20 +00003364 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003365 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003366 /* lastErrno set by seekAndWrite */
3367 return SQLITE_IOERR_WRITE;
3368 }else{
drh4bf66fd2015-02-19 02:43:02 +00003369 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003370 return SQLITE_FULL;
3371 }
3372 }
dan6e09d692010-07-27 18:34:15 +00003373
drh734c9862008-11-28 15:37:20 +00003374 return SQLITE_OK;
3375}
3376
3377#ifdef SQLITE_TEST
3378/*
3379** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003380** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003381*/
3382int sqlite3_sync_count = 0;
3383int sqlite3_fullsync_count = 0;
3384#endif
3385
3386/*
drh89240432009-03-25 01:06:01 +00003387** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003388** Others do no. To be safe, we will stick with the (slightly slower)
3389** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003390** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003391*/
drhf7a4a1b2015-01-10 18:02:45 +00003392#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003393# define fdatasync fsync
3394#endif
3395
3396/*
3397** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3398** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3399** only available on Mac OS X. But that could change.
3400*/
3401#ifdef F_FULLFSYNC
3402# define HAVE_FULLFSYNC 1
3403#else
3404# define HAVE_FULLFSYNC 0
3405#endif
3406
3407
3408/*
3409** The fsync() system call does not work as advertised on many
3410** unix systems. The following procedure is an attempt to make
3411** it work better.
3412**
3413** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3414** for testing when we want to run through the test suite quickly.
3415** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3416** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3417** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003418**
3419** SQLite sets the dataOnly flag if the size of the file is unchanged.
3420** The idea behind dataOnly is that it should only write the file content
3421** to disk, not the inode. We only set dataOnly if the file size is
3422** unchanged since the file size is part of the inode. However,
3423** Ted Ts'o tells us that fdatasync() will also write the inode if the
3424** file size has changed. The only real difference between fdatasync()
3425** and fsync(), Ted tells us, is that fdatasync() will not flush the
3426** inode if the mtime or owner or other inode attributes have changed.
3427** We only care about the file size, not the other file attributes, so
3428** as far as SQLite is concerned, an fdatasync() is always adequate.
3429** So, we always use fdatasync() if it is available, regardless of
3430** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003431*/
3432static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003433 int rc;
drh734c9862008-11-28 15:37:20 +00003434
3435 /* The following "ifdef/elif/else/" block has the same structure as
3436 ** the one below. It is replicated here solely to avoid cluttering
3437 ** up the real code with the UNUSED_PARAMETER() macros.
3438 */
3439#ifdef SQLITE_NO_SYNC
3440 UNUSED_PARAMETER(fd);
3441 UNUSED_PARAMETER(fullSync);
3442 UNUSED_PARAMETER(dataOnly);
3443#elif HAVE_FULLFSYNC
3444 UNUSED_PARAMETER(dataOnly);
3445#else
3446 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003447 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003448#endif
3449
3450 /* Record the number of times that we do a normal fsync() and
3451 ** FULLSYNC. This is used during testing to verify that this procedure
3452 ** gets called with the correct arguments.
3453 */
3454#ifdef SQLITE_TEST
3455 if( fullSync ) sqlite3_fullsync_count++;
3456 sqlite3_sync_count++;
3457#endif
3458
3459 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3460 ** no-op
3461 */
3462#ifdef SQLITE_NO_SYNC
3463 rc = SQLITE_OK;
3464#elif HAVE_FULLFSYNC
3465 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003466 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003467 }else{
3468 rc = 1;
3469 }
3470 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003471 ** It shouldn't be possible for fullfsync to fail on the local
3472 ** file system (on OSX), so failure indicates that FULLFSYNC
3473 ** isn't supported for this file system. So, attempt an fsync
3474 ** and (for now) ignore the overhead of a superfluous fcntl call.
3475 ** It'd be better to detect fullfsync support once and avoid
3476 ** the fcntl call every time sync is called.
3477 */
drh734c9862008-11-28 15:37:20 +00003478 if( rc ) rc = fsync(fd);
3479
drh7ed97b92010-01-20 13:07:21 +00003480#elif defined(__APPLE__)
3481 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3482 ** so currently we default to the macro that redefines fdatasync to fsync
3483 */
3484 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003485#else
drh0b647ff2009-03-21 14:41:04 +00003486 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003487#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003488 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003489 rc = fsync(fd);
3490 }
drh0b647ff2009-03-21 14:41:04 +00003491#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003492#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3493
3494 if( OS_VXWORKS && rc!= -1 ){
3495 rc = 0;
3496 }
chw97185482008-11-17 08:05:31 +00003497 return rc;
drhbfe66312006-10-03 17:40:40 +00003498}
3499
drh734c9862008-11-28 15:37:20 +00003500/*
drh0059eae2011-08-08 23:48:40 +00003501** Open a file descriptor to the directory containing file zFilename.
3502** If successful, *pFd is set to the opened file descriptor and
3503** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3504** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3505** value.
3506**
drh90315a22011-08-10 01:52:12 +00003507** The directory file descriptor is used for only one thing - to
3508** fsync() a directory to make sure file creation and deletion events
3509** are flushed to disk. Such fsyncs are not needed on newer
3510** journaling filesystems, but are required on older filesystems.
3511**
3512** This routine can be overridden using the xSetSysCall interface.
3513** The ability to override this routine was added in support of the
3514** chromium sandbox. Opening a directory is a security risk (we are
3515** told) so making it overrideable allows the chromium sandbox to
3516** replace this routine with a harmless no-op. To make this routine
3517** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3518** *pFd set to a negative number.
3519**
drh0059eae2011-08-08 23:48:40 +00003520** If SQLITE_OK is returned, the caller is responsible for closing
3521** the file descriptor *pFd using close().
3522*/
3523static int openDirectory(const char *zFilename, int *pFd){
3524 int ii;
3525 int fd = -1;
3526 char zDirname[MAX_PATHNAME+1];
3527
3528 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3529 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3530 if( ii>0 ){
3531 zDirname[ii] = '\0';
3532 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3533 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003534 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3535 }
3536 }
3537 *pFd = fd;
3538 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3539}
3540
3541/*
drh734c9862008-11-28 15:37:20 +00003542** Make sure all writes to a particular file are committed to disk.
3543**
3544** If dataOnly==0 then both the file itself and its metadata (file
3545** size, access time, etc) are synced. If dataOnly!=0 then only the
3546** file data is synced.
3547**
3548** Under Unix, also make sure that the directory entry for the file
3549** has been created by fsync-ing the directory that contains the file.
3550** If we do not do this and we encounter a power failure, the directory
3551** entry for the journal might not exist after we reboot. The next
3552** SQLite to access the file will not know that the journal exists (because
3553** the directory entry for the journal was never created) and the transaction
3554** will not roll back - possibly leading to database corruption.
3555*/
3556static int unixSync(sqlite3_file *id, int flags){
3557 int rc;
3558 unixFile *pFile = (unixFile*)id;
3559
3560 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3561 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3562
3563 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3564 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3565 || (flags&0x0F)==SQLITE_SYNC_FULL
3566 );
3567
3568 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3569 ** line is to test that doing so does not cause any problems.
3570 */
3571 SimulateDiskfullError( return SQLITE_FULL );
3572
3573 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003574 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003575 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3576 SimulateIOError( rc=1 );
3577 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003578 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003579 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003580 }
drh0059eae2011-08-08 23:48:40 +00003581
3582 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003583 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003584 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003585 */
3586 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3587 int dirfd;
3588 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003589 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003590 rc = osOpenDirectory(pFile->zPath, &dirfd);
3591 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003592 full_fsync(dirfd, 0, 0);
3593 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003594 }else if( rc==SQLITE_CANTOPEN ){
3595 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003596 }
drh0059eae2011-08-08 23:48:40 +00003597 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003598 }
3599 return rc;
3600}
3601
3602/*
3603** Truncate an open file to a specified size
3604*/
3605static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003606 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003607 int rc;
dan6e09d692010-07-27 18:34:15 +00003608 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003609 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003610
3611 /* If the user has configured a chunk-size for this file, truncate the
3612 ** file so that it consists of an integer number of chunks (i.e. the
3613 ** actual file size after the operation may be larger than the requested
3614 ** size).
3615 */
drhb8af4b72012-04-05 20:04:39 +00003616 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003617 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3618 }
3619
dan2ee53412014-09-06 16:49:40 +00003620 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003621 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003622 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003623 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003624 }else{
drhd3d8c042012-05-29 17:02:40 +00003625#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003626 /* If we are doing a normal write to a database file (as opposed to
3627 ** doing a hot-journal rollback or a write to some file other than a
3628 ** normal database file) and we truncate the file to zero length,
3629 ** that effectively updates the change counter. This might happen
3630 ** when restoring a database using the backup API from a zero-length
3631 ** source.
3632 */
dan6e09d692010-07-27 18:34:15 +00003633 if( pFile->inNormalWrite && nByte==0 ){
3634 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003635 }
danf23da962013-03-23 21:00:41 +00003636#endif
danc0003312013-03-22 17:46:11 +00003637
mistachkine98844f2013-08-24 00:59:24 +00003638#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003639 /* If the file was just truncated to a size smaller than the currently
3640 ** mapped region, reduce the effective mapping size as well. SQLite will
3641 ** use read() and write() to access data beyond this point from now on.
3642 */
3643 if( nByte<pFile->mmapSize ){
3644 pFile->mmapSize = nByte;
3645 }
mistachkine98844f2013-08-24 00:59:24 +00003646#endif
drh3313b142009-11-06 04:13:18 +00003647
drh734c9862008-11-28 15:37:20 +00003648 return SQLITE_OK;
3649 }
3650}
3651
3652/*
3653** Determine the current size of a file in bytes
3654*/
3655static int unixFileSize(sqlite3_file *id, i64 *pSize){
3656 int rc;
3657 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003658 assert( id );
3659 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003660 SimulateIOError( rc=1 );
3661 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003662 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003663 return SQLITE_IOERR_FSTAT;
3664 }
3665 *pSize = buf.st_size;
3666
drh8af6c222010-05-14 12:43:01 +00003667 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003668 ** writes a single byte into that file in order to work around a bug
3669 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3670 ** layers, we need to report this file size as zero even though it is
3671 ** really 1. Ticket #3260.
3672 */
3673 if( *pSize==1 ) *pSize = 0;
3674
3675
3676 return SQLITE_OK;
3677}
3678
drhd2cb50b2009-01-09 21:41:17 +00003679#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003680/*
3681** Handler for proxy-locking file-control verbs. Defined below in the
3682** proxying locking division.
3683*/
3684static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003685#endif
drh715ff302008-12-03 22:32:44 +00003686
dan502019c2010-07-28 14:26:17 +00003687/*
3688** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003689** file-control operation. Enlarge the database to nBytes in size
3690** (rounded up to the next chunk-size). If the database is already
3691** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003692*/
3693static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003694 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003695 i64 nSize; /* Required file size */
3696 struct stat buf; /* Used to hold return values of fstat() */
3697
drh4bf66fd2015-02-19 02:43:02 +00003698 if( osFstat(pFile->h, &buf) ){
3699 return SQLITE_IOERR_FSTAT;
3700 }
dan502019c2010-07-28 14:26:17 +00003701
3702 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3703 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003704
dan502019c2010-07-28 14:26:17 +00003705#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003706 /* The code below is handling the return value of osFallocate()
3707 ** correctly. posix_fallocate() is defined to "returns zero on success,
3708 ** or an error number on failure". See the manpage for details. */
3709 int err;
drhff812312011-02-23 13:33:46 +00003710 do{
dan661d71a2011-03-30 19:08:03 +00003711 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3712 }while( err==EINTR );
3713 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003714#else
dan592bf7f2014-12-30 19:58:31 +00003715 /* If the OS does not have posix_fallocate(), fake it. Write a
3716 ** single byte to the last byte in each block that falls entirely
3717 ** within the extended region. Then, if required, a single byte
3718 ** at offset (nSize-1), to set the size of the file correctly.
3719 ** This is a similar technique to that used by glibc on systems
3720 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003721 */
3722 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003723 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003724 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003725
dan502019c2010-07-28 14:26:17 +00003726 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003727 assert( iWrite>=buf.st_size );
3728 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3729 assert( ((iWrite+1)%nBlk)==0 );
3730 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003731 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003732 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003733 }
danef3d66c2015-01-06 21:31:47 +00003734 if( nWrite==0 || (nSize%nBlk) ){
3735 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003736 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003737 }
dan502019c2010-07-28 14:26:17 +00003738#endif
3739 }
3740 }
3741
mistachkine98844f2013-08-24 00:59:24 +00003742#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003743 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003744 int rc;
3745 if( pFile->szChunk<=0 ){
3746 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003747 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003748 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3749 }
3750 }
3751
3752 rc = unixMapfile(pFile, nByte);
3753 return rc;
3754 }
mistachkine98844f2013-08-24 00:59:24 +00003755#endif
danf23da962013-03-23 21:00:41 +00003756
dan502019c2010-07-28 14:26:17 +00003757 return SQLITE_OK;
3758}
danielk1977ad94b582007-08-20 06:44:22 +00003759
danielk1977e3026632004-06-22 11:29:02 +00003760/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003761** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003762** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3763**
3764** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3765*/
3766static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3767 if( *pArg<0 ){
3768 *pArg = (pFile->ctrlFlags & mask)!=0;
3769 }else if( (*pArg)==0 ){
3770 pFile->ctrlFlags &= ~mask;
3771 }else{
3772 pFile->ctrlFlags |= mask;
3773 }
3774}
3775
drh696b33e2012-12-06 19:01:42 +00003776/* Forward declaration */
3777static int unixGetTempname(int nBuf, char *zBuf);
3778
drhf12b3f62011-12-21 14:42:29 +00003779/*
drh9e33c2c2007-08-31 18:34:59 +00003780** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003781*/
drhcc6bb3e2007-08-31 16:11:35 +00003782static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003783 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003784 switch( op ){
3785 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003786 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003787 return SQLITE_OK;
3788 }
drh4bf66fd2015-02-19 02:43:02 +00003789 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003790 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003791 return SQLITE_OK;
3792 }
dan6e09d692010-07-27 18:34:15 +00003793 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003794 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003795 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003796 }
drh9ff27ec2010-05-19 19:26:05 +00003797 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003798 int rc;
3799 SimulateIOErrorBenign(1);
3800 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3801 SimulateIOErrorBenign(0);
3802 return rc;
drhf0b190d2011-07-26 16:03:07 +00003803 }
3804 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003805 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3806 return SQLITE_OK;
3807 }
drhcb15f352011-12-23 01:04:17 +00003808 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3809 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003810 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003811 }
drhde60fc22011-12-14 17:53:36 +00003812 case SQLITE_FCNTL_VFSNAME: {
3813 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3814 return SQLITE_OK;
3815 }
drh696b33e2012-12-06 19:01:42 +00003816 case SQLITE_FCNTL_TEMPFILENAME: {
3817 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3818 if( zTFile ){
3819 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3820 *(char**)pArg = zTFile;
3821 }
3822 return SQLITE_OK;
3823 }
drhb959a012013-12-07 12:29:22 +00003824 case SQLITE_FCNTL_HAS_MOVED: {
3825 *(int*)pArg = fileHasMoved(pFile);
3826 return SQLITE_OK;
3827 }
mistachkine98844f2013-08-24 00:59:24 +00003828#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003829 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003830 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003831 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003832 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3833 newLimit = sqlite3GlobalConfig.mxMmap;
3834 }
3835 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003836 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003837 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003838 if( pFile->mmapSize>0 ){
3839 unixUnmapfile(pFile);
3840 rc = unixMapfile(pFile, -1);
3841 }
danbcb8a862013-04-08 15:30:41 +00003842 }
drh34e258c2013-05-23 01:40:53 +00003843 return rc;
danb2d3de32013-03-14 18:34:37 +00003844 }
mistachkine98844f2013-08-24 00:59:24 +00003845#endif
drhd3d8c042012-05-29 17:02:40 +00003846#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003847 /* The pager calls this method to signal that it has done
3848 ** a rollback and that the database is therefore unchanged and
3849 ** it hence it is OK for the transaction change counter to be
3850 ** unchanged.
3851 */
3852 case SQLITE_FCNTL_DB_UNCHANGED: {
3853 ((unixFile*)id)->dbUpdate = 0;
3854 return SQLITE_OK;
3855 }
3856#endif
drhd2cb50b2009-01-09 21:41:17 +00003857#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003858 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3859 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003860 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003861 }
drhd2cb50b2009-01-09 21:41:17 +00003862#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003863 }
drh0b52b7d2011-01-26 19:46:22 +00003864 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003865}
3866
3867/*
danielk1977a3d4c882007-03-23 10:08:38 +00003868** Return the sector size in bytes of the underlying block device for
3869** the specified file. This is almost always 512 bytes, but may be
3870** larger for some devices.
3871**
3872** SQLite code assumes this function cannot fail. It also assumes that
3873** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003874** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003875** same for both.
3876*/
drh537dddf2012-10-26 13:46:24 +00003877#ifndef __QNXNTO__
3878static int unixSectorSize(sqlite3_file *NotUsed){
3879 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003880 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003881}
drh537dddf2012-10-26 13:46:24 +00003882#endif
3883
3884/*
3885** The following version of unixSectorSize() is optimized for QNX.
3886*/
3887#ifdef __QNXNTO__
3888#include <sys/dcmd_blk.h>
3889#include <sys/statvfs.h>
3890static int unixSectorSize(sqlite3_file *id){
3891 unixFile *pFile = (unixFile*)id;
3892 if( pFile->sectorSize == 0 ){
3893 struct statvfs fsInfo;
3894
3895 /* Set defaults for non-supported filesystems */
3896 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3897 pFile->deviceCharacteristics = 0;
3898 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3899 return pFile->sectorSize;
3900 }
3901
3902 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3903 pFile->sectorSize = fsInfo.f_bsize;
3904 pFile->deviceCharacteristics =
3905 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3906 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3907 ** the write succeeds */
3908 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3909 ** so it is ordered */
3910 0;
3911 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3912 pFile->sectorSize = fsInfo.f_bsize;
3913 pFile->deviceCharacteristics =
3914 /* etfs cluster size writes are atomic */
3915 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3916 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3917 ** the write succeeds */
3918 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3919 ** so it is ordered */
3920 0;
3921 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3922 pFile->sectorSize = fsInfo.f_bsize;
3923 pFile->deviceCharacteristics =
3924 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3925 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3926 ** the write succeeds */
3927 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3928 ** so it is ordered */
3929 0;
3930 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3931 pFile->sectorSize = fsInfo.f_bsize;
3932 pFile->deviceCharacteristics =
3933 /* full bitset of atomics from max sector size and smaller */
3934 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3935 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3936 ** so it is ordered */
3937 0;
3938 }else if( strstr(fsInfo.f_basetype, "dos") ){
3939 pFile->sectorSize = fsInfo.f_bsize;
3940 pFile->deviceCharacteristics =
3941 /* full bitset of atomics from max sector size and smaller */
3942 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3943 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3944 ** so it is ordered */
3945 0;
3946 }else{
3947 pFile->deviceCharacteristics =
3948 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3949 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3950 ** the write succeeds */
3951 0;
3952 }
3953 }
3954 /* Last chance verification. If the sector size isn't a multiple of 512
3955 ** then it isn't valid.*/
3956 if( pFile->sectorSize % 512 != 0 ){
3957 pFile->deviceCharacteristics = 0;
3958 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3959 }
3960 return pFile->sectorSize;
3961}
3962#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003963
danielk197790949c22007-08-17 16:50:38 +00003964/*
drhf12b3f62011-12-21 14:42:29 +00003965** Return the device characteristics for the file.
3966**
drhcb15f352011-12-23 01:04:17 +00003967** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003968** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003969** file system does not always provide powersafe overwrites. (In other
3970** words, after a power-loss event, parts of the file that were never
3971** written might end up being altered.) However, non-PSOW behavior is very,
3972** very rare. And asserting PSOW makes a large reduction in the amount
3973** of required I/O for journaling, since a lot of padding is eliminated.
3974** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3975** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003976*/
drhf12b3f62011-12-21 14:42:29 +00003977static int unixDeviceCharacteristics(sqlite3_file *id){
3978 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003979 int rc = 0;
3980#ifdef __QNXNTO__
3981 if( p->sectorSize==0 ) unixSectorSize(id);
3982 rc = p->deviceCharacteristics;
3983#endif
drhcb15f352011-12-23 01:04:17 +00003984 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003985 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003986 }
drh537dddf2012-10-26 13:46:24 +00003987 return rc;
danielk197762079062007-08-15 17:08:46 +00003988}
3989
dan702eec12014-06-23 10:04:58 +00003990#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003991
dan702eec12014-06-23 10:04:58 +00003992/*
3993** Return the system page size.
3994**
3995** This function should not be called directly by other code in this file.
3996** Instead, it should be called via macro osGetpagesize().
3997*/
3998static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003999#if OS_VXWORKS
4000 return 1024;
4001#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004002 return getpagesize();
4003#else
4004 return (int)sysconf(_SC_PAGESIZE);
4005#endif
4006}
4007
4008#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4009
4010#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004011
4012/*
drhd91c68f2010-05-14 14:52:25 +00004013** Object used to represent an shared memory buffer.
4014**
4015** When multiple threads all reference the same wal-index, each thread
4016** has its own unixShm object, but they all point to a single instance
4017** of this unixShmNode object. In other words, each wal-index is opened
4018** only once per process.
4019**
4020** Each unixShmNode object is connected to a single unixInodeInfo object.
4021** We could coalesce this object into unixInodeInfo, but that would mean
4022** every open file that does not use shared memory (in other words, most
4023** open files) would have to carry around this extra information. So
4024** the unixInodeInfo object contains a pointer to this unixShmNode object
4025** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004026**
4027** unixMutexHeld() must be true when creating or destroying
4028** this object or while reading or writing the following fields:
4029**
4030** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004031**
4032** The following fields are read-only after the object is created:
4033**
4034** fid
4035** zFilename
4036**
drhd91c68f2010-05-14 14:52:25 +00004037** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004038** unixMutexHeld() is true when reading or writing any other field
4039** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004040*/
drhd91c68f2010-05-14 14:52:25 +00004041struct unixShmNode {
4042 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004043 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004044 char *zFilename; /* Name of the mmapped file */
4045 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004046 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004047 u16 nRegion; /* Size of array apRegion */
4048 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004049 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004050 int nRef; /* Number of unixShm objects pointing to this */
4051 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004052#ifdef SQLITE_DEBUG
4053 u8 exclMask; /* Mask of exclusive locks held */
4054 u8 sharedMask; /* Mask of shared locks held */
4055 u8 nextShmId; /* Next available unixShm.id value */
4056#endif
4057};
4058
4059/*
drhd9e5c4f2010-05-12 18:01:39 +00004060** Structure used internally by this VFS to record the state of an
4061** open shared memory connection.
4062**
drhd91c68f2010-05-14 14:52:25 +00004063** The following fields are initialized when this object is created and
4064** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004065**
drhd91c68f2010-05-14 14:52:25 +00004066** unixShm.pFile
4067** unixShm.id
4068**
4069** All other fields are read/write. The unixShm.pFile->mutex must be held
4070** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004071*/
4072struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004073 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4074 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004075 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004076 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004077 u16 sharedMask; /* Mask of shared locks held */
4078 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004079};
4080
4081/*
drhd9e5c4f2010-05-12 18:01:39 +00004082** Constants used for locking
4083*/
drhbd9676c2010-06-23 17:58:38 +00004084#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004085#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004086
drhd9e5c4f2010-05-12 18:01:39 +00004087/*
drh73b64e42010-05-30 19:55:15 +00004088** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004089**
4090** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4091** otherwise.
4092*/
4093static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004094 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004095 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004096 int ofst, /* First byte of the locking range */
4097 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004098){
drhbbf76ee2015-03-10 20:22:35 +00004099 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4100 struct flock f; /* The posix advisory locking structure */
4101 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004102
drhd91c68f2010-05-14 14:52:25 +00004103 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004104 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004105 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004106
drh73b64e42010-05-30 19:55:15 +00004107 /* Shared locks never span more than one byte */
4108 assert( n==1 || lockType!=F_RDLCK );
4109
4110 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004111 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004112
drh3cb93392011-03-12 18:10:44 +00004113 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004114 int lkType;
drh3cb93392011-03-12 18:10:44 +00004115 /* Initialize the locking parameters */
4116 memset(&f, 0, sizeof(f));
4117 f.l_type = lockType;
4118 f.l_whence = SEEK_SET;
4119 f.l_start = ofst;
4120 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004121
drhbbf76ee2015-03-10 20:22:35 +00004122 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4123 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004124 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004125 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004126 }
drhd9e5c4f2010-05-12 18:01:39 +00004127
4128 /* Update the global lock state and do debug tracing */
4129#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004130 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004131 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004132 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004133 if( rc==SQLITE_OK ){
4134 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004135 OSTRACE(("unlock %d ok", ofst));
4136 pShmNode->exclMask &= ~mask;
4137 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004138 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004139 OSTRACE(("read-lock %d ok", ofst));
4140 pShmNode->exclMask &= ~mask;
4141 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004142 }else{
4143 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004144 OSTRACE(("write-lock %d ok", ofst));
4145 pShmNode->exclMask |= mask;
4146 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004147 }
4148 }else{
4149 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004150 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004151 }else if( lockType==F_RDLCK ){
4152 OSTRACE(("read-lock failed"));
4153 }else{
4154 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004155 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004156 }
4157 }
drh20e1f082010-05-31 16:10:12 +00004158 OSTRACE((" - afterwards %03x,%03x\n",
4159 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004160 }
drhd9e5c4f2010-05-12 18:01:39 +00004161#endif
4162
4163 return rc;
4164}
4165
dan781e34c2014-03-20 08:59:47 +00004166/*
dan781e34c2014-03-20 08:59:47 +00004167** Return the minimum number of 32KB shm regions that should be mapped at
4168** a time, assuming that each mapping must be an integer multiple of the
4169** current system page-size.
4170**
4171** Usually, this is 1. The exception seems to be systems that are configured
4172** to use 64KB pages - in this case each mapping must cover at least two
4173** shm regions.
4174*/
4175static int unixShmRegionPerMap(void){
4176 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004177 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004178 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4179 if( pgsz<shmsz ) return 1;
4180 return pgsz/shmsz;
4181}
drhd9e5c4f2010-05-12 18:01:39 +00004182
4183/*
drhd91c68f2010-05-14 14:52:25 +00004184** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004185**
4186** This is not a VFS shared-memory method; it is a utility function called
4187** by VFS shared-memory methods.
4188*/
drhd91c68f2010-05-14 14:52:25 +00004189static void unixShmPurge(unixFile *pFd){
4190 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004191 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004192 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004193 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004194 int i;
drhd91c68f2010-05-14 14:52:25 +00004195 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004196 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004197 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004198 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004199 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004200 }else{
4201 sqlite3_free(p->apRegion[i]);
4202 }
dan13a3cb82010-06-11 19:04:21 +00004203 }
dan18801912010-06-14 14:07:50 +00004204 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004205 if( p->h>=0 ){
4206 robust_close(pFd, p->h, __LINE__);
4207 p->h = -1;
4208 }
drhd91c68f2010-05-14 14:52:25 +00004209 p->pInode->pShmNode = 0;
4210 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004211 }
4212}
4213
4214/*
danda9fe0c2010-07-13 18:44:03 +00004215** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004216** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004217**
drh7234c6d2010-06-19 15:10:09 +00004218** The file used to implement shared-memory is in the same directory
4219** as the open database file and has the same name as the open database
4220** file with the "-shm" suffix added. For example, if the database file
4221** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004222** for shared memory will be called "/home/user1/config.db-shm".
4223**
4224** Another approach to is to use files in /dev/shm or /dev/tmp or an
4225** some other tmpfs mount. But if a file in a different directory
4226** from the database file is used, then differing access permissions
4227** or a chroot() might cause two different processes on the same
4228** database to end up using different files for shared memory -
4229** meaning that their memory would not really be shared - resulting
4230** in database corruption. Nevertheless, this tmpfs file usage
4231** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4232** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4233** option results in an incompatible build of SQLite; builds of SQLite
4234** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4235** same database file at the same time, database corruption will likely
4236** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4237** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004238**
4239** When opening a new shared-memory file, if no other instances of that
4240** file are currently open, in this process or in other processes, then
4241** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004242**
4243** If the original database file (pDbFd) is using the "unix-excl" VFS
4244** that means that an exclusive lock is held on the database file and
4245** that no other processes are able to read or write the database. In
4246** that case, we do not really need shared memory. No shared memory
4247** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004248*/
danda9fe0c2010-07-13 18:44:03 +00004249static int unixOpenSharedMemory(unixFile *pDbFd){
4250 struct unixShm *p = 0; /* The connection to be opened */
4251 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4252 int rc; /* Result code */
4253 unixInodeInfo *pInode; /* The inode of fd */
4254 char *zShmFilename; /* Name of the file used for SHM */
4255 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004256
danda9fe0c2010-07-13 18:44:03 +00004257 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004258 p = sqlite3_malloc( sizeof(*p) );
4259 if( p==0 ) return SQLITE_NOMEM;
4260 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004261 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004262
danda9fe0c2010-07-13 18:44:03 +00004263 /* Check to see if a unixShmNode object already exists. Reuse an existing
4264 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004265 */
4266 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004267 pInode = pDbFd->pInode;
4268 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004269 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004270 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004271#ifndef SQLITE_SHM_DIRECTORY
4272 const char *zBasePath = pDbFd->zPath;
4273#endif
danddb0ac42010-07-14 14:48:58 +00004274
4275 /* Call fstat() to figure out the permissions on the database file. If
4276 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004277 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004278 */
drh3cb93392011-03-12 18:10:44 +00004279 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004280 rc = SQLITE_IOERR_FSTAT;
4281 goto shm_open_err;
4282 }
4283
drha4ced192010-07-15 18:32:40 +00004284#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004285 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004286#else
drh4bf66fd2015-02-19 02:43:02 +00004287 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004288#endif
drh7234c6d2010-06-19 15:10:09 +00004289 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004290 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004291 rc = SQLITE_NOMEM;
4292 goto shm_open_err;
4293 }
drh9cb5a0d2012-01-05 21:19:54 +00004294 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004295 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004296#ifdef SQLITE_SHM_DIRECTORY
4297 sqlite3_snprintf(nShmFilename, zShmFilename,
4298 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4299 (u32)sStat.st_ino, (u32)sStat.st_dev);
4300#else
drh4bf66fd2015-02-19 02:43:02 +00004301 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004302 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004303#endif
drhd91c68f2010-05-14 14:52:25 +00004304 pShmNode->h = -1;
4305 pDbFd->pInode->pShmNode = pShmNode;
4306 pShmNode->pInode = pDbFd->pInode;
4307 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4308 if( pShmNode->mutex==0 ){
4309 rc = SQLITE_NOMEM;
4310 goto shm_open_err;
4311 }
drhd9e5c4f2010-05-12 18:01:39 +00004312
drh3cb93392011-03-12 18:10:44 +00004313 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004314 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004315 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004316 openFlags = O_RDONLY;
4317 pShmNode->isReadonly = 1;
4318 }
4319 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004320 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004321 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4322 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004323 }
drhac7c3ac2012-02-11 19:23:48 +00004324
4325 /* If this process is running as root, make sure that the SHM file
4326 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004327 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004328 */
drhed466822012-05-31 13:10:49 +00004329 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004330
4331 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004332 ** If not, truncate the file to zero length.
4333 */
4334 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004335 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004336 if( robust_ftruncate(pShmNode->h, 0) ){
4337 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004338 }
4339 }
drh66dfec8b2011-06-01 20:01:49 +00004340 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004341 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004342 }
4343 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004344 }
drhd9e5c4f2010-05-12 18:01:39 +00004345 }
4346
drhd91c68f2010-05-14 14:52:25 +00004347 /* Make the new connection a child of the unixShmNode */
4348 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004349#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004350 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004351#endif
drhd91c68f2010-05-14 14:52:25 +00004352 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004353 pDbFd->pShm = p;
4354 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004355
4356 /* The reference count on pShmNode has already been incremented under
4357 ** the cover of the unixEnterMutex() mutex and the pointer from the
4358 ** new (struct unixShm) object to the pShmNode has been set. All that is
4359 ** left to do is to link the new object into the linked list starting
4360 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4361 ** mutex.
4362 */
4363 sqlite3_mutex_enter(pShmNode->mutex);
4364 p->pNext = pShmNode->pFirst;
4365 pShmNode->pFirst = p;
4366 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004367 return SQLITE_OK;
4368
4369 /* Jump here on any error */
4370shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004371 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004372 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004373 unixLeaveMutex();
4374 return rc;
4375}
4376
4377/*
danda9fe0c2010-07-13 18:44:03 +00004378** This function is called to obtain a pointer to region iRegion of the
4379** shared-memory associated with the database file fd. Shared-memory regions
4380** are numbered starting from zero. Each shared-memory region is szRegion
4381** bytes in size.
4382**
4383** If an error occurs, an error code is returned and *pp is set to NULL.
4384**
4385** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4386** region has not been allocated (by any client, including one running in a
4387** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4388** bExtend is non-zero and the requested shared-memory region has not yet
4389** been allocated, it is allocated by this function.
4390**
4391** If the shared-memory region has already been allocated or is allocated by
4392** this call as described above, then it is mapped into this processes
4393** address space (if it is not already), *pp is set to point to the mapped
4394** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004395*/
danda9fe0c2010-07-13 18:44:03 +00004396static int unixShmMap(
4397 sqlite3_file *fd, /* Handle open on database file */
4398 int iRegion, /* Region to retrieve */
4399 int szRegion, /* Size of regions */
4400 int bExtend, /* True to extend file if necessary */
4401 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004402){
danda9fe0c2010-07-13 18:44:03 +00004403 unixFile *pDbFd = (unixFile*)fd;
4404 unixShm *p;
4405 unixShmNode *pShmNode;
4406 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004407 int nShmPerMap = unixShmRegionPerMap();
4408 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004409
danda9fe0c2010-07-13 18:44:03 +00004410 /* If the shared-memory file has not yet been opened, open it now. */
4411 if( pDbFd->pShm==0 ){
4412 rc = unixOpenSharedMemory(pDbFd);
4413 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004414 }
drhd9e5c4f2010-05-12 18:01:39 +00004415
danda9fe0c2010-07-13 18:44:03 +00004416 p = pDbFd->pShm;
4417 pShmNode = p->pShmNode;
4418 sqlite3_mutex_enter(pShmNode->mutex);
4419 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004420 assert( pShmNode->pInode==pDbFd->pInode );
4421 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4422 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004423
dan781e34c2014-03-20 08:59:47 +00004424 /* Minimum number of regions required to be mapped. */
4425 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4426
4427 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004428 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004429 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004430 struct stat sStat; /* Used by fstat() */
4431
4432 pShmNode->szRegion = szRegion;
4433
drh3cb93392011-03-12 18:10:44 +00004434 if( pShmNode->h>=0 ){
4435 /* The requested region is not mapped into this processes address space.
4436 ** Check to see if it has been allocated (i.e. if the wal-index file is
4437 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004438 */
drh3cb93392011-03-12 18:10:44 +00004439 if( osFstat(pShmNode->h, &sStat) ){
4440 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004441 goto shmpage_out;
4442 }
drh3cb93392011-03-12 18:10:44 +00004443
4444 if( sStat.st_size<nByte ){
4445 /* The requested memory region does not exist. If bExtend is set to
4446 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004447 */
dan47a2b4a2013-04-26 16:09:29 +00004448 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004449 goto shmpage_out;
4450 }
dan47a2b4a2013-04-26 16:09:29 +00004451
4452 /* Alternatively, if bExtend is true, extend the file. Do this by
4453 ** writing a single byte to the end of each (OS) page being
4454 ** allocated or extended. Technically, we need only write to the
4455 ** last page in order to extend the file. But writing to all new
4456 ** pages forces the OS to allocate them immediately, which reduces
4457 ** the chances of SIGBUS while accessing the mapped region later on.
4458 */
4459 else{
4460 static const int pgsz = 4096;
4461 int iPg;
4462
4463 /* Write to the last byte of each newly allocated or extended page */
4464 assert( (nByte % pgsz)==0 );
4465 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4466 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4467 const char *zFile = pShmNode->zFilename;
4468 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4469 goto shmpage_out;
4470 }
4471 }
drh3cb93392011-03-12 18:10:44 +00004472 }
4473 }
danda9fe0c2010-07-13 18:44:03 +00004474 }
4475
4476 /* Map the requested memory region into this processes address space. */
4477 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004478 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004479 );
4480 if( !apNew ){
4481 rc = SQLITE_IOERR_NOMEM;
4482 goto shmpage_out;
4483 }
4484 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004485 while( pShmNode->nRegion<nReqRegion ){
4486 int nMap = szRegion*nShmPerMap;
4487 int i;
drh3cb93392011-03-12 18:10:44 +00004488 void *pMem;
4489 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004490 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004491 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004492 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004493 );
4494 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004495 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004496 goto shmpage_out;
4497 }
4498 }else{
4499 pMem = sqlite3_malloc(szRegion);
4500 if( pMem==0 ){
4501 rc = SQLITE_NOMEM;
4502 goto shmpage_out;
4503 }
4504 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004505 }
dan781e34c2014-03-20 08:59:47 +00004506
4507 for(i=0; i<nShmPerMap; i++){
4508 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4509 }
4510 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004511 }
4512 }
4513
4514shmpage_out:
4515 if( pShmNode->nRegion>iRegion ){
4516 *pp = pShmNode->apRegion[iRegion];
4517 }else{
4518 *pp = 0;
4519 }
drh66dfec8b2011-06-01 20:01:49 +00004520 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004521 sqlite3_mutex_leave(pShmNode->mutex);
4522 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004523}
4524
4525/*
drhd9e5c4f2010-05-12 18:01:39 +00004526** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004527**
4528** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4529** different here than in posix. In xShmLock(), one can go from unlocked
4530** to shared and back or from unlocked to exclusive and back. But one may
4531** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004532*/
4533static int unixShmLock(
4534 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004535 int ofst, /* First lock to acquire or release */
4536 int n, /* Number of locks to acquire or release */
4537 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004538){
drh73b64e42010-05-30 19:55:15 +00004539 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4540 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4541 unixShm *pX; /* For looping over all siblings */
4542 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4543 int rc = SQLITE_OK; /* Result code */
4544 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004545
drhd91c68f2010-05-14 14:52:25 +00004546 assert( pShmNode==pDbFd->pInode->pShmNode );
4547 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004548 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004549 assert( n>=1 );
4550 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4551 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4552 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4553 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4554 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004555 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4556 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004557
drhc99597c2010-05-31 01:41:15 +00004558 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004559 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004560 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004561 if( flags & SQLITE_SHM_UNLOCK ){
4562 u16 allMask = 0; /* Mask of locks held by siblings */
4563
4564 /* See if any siblings hold this same lock */
4565 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4566 if( pX==p ) continue;
4567 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4568 allMask |= pX->sharedMask;
4569 }
4570
4571 /* Unlock the system-level locks */
4572 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004573 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004574 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004575 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004576 }
drh73b64e42010-05-30 19:55:15 +00004577
4578 /* Undo the local locks */
4579 if( rc==SQLITE_OK ){
4580 p->exclMask &= ~mask;
4581 p->sharedMask &= ~mask;
4582 }
4583 }else if( flags & SQLITE_SHM_SHARED ){
4584 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4585
4586 /* Find out which shared locks are already held by sibling connections.
4587 ** If any sibling already holds an exclusive lock, go ahead and return
4588 ** SQLITE_BUSY.
4589 */
4590 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004591 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004592 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004593 break;
4594 }
4595 allShared |= pX->sharedMask;
4596 }
4597
4598 /* Get shared locks at the system level, if necessary */
4599 if( rc==SQLITE_OK ){
4600 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004601 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004602 }else{
drh73b64e42010-05-30 19:55:15 +00004603 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004604 }
drhd9e5c4f2010-05-12 18:01:39 +00004605 }
drh73b64e42010-05-30 19:55:15 +00004606
4607 /* Get the local shared locks */
4608 if( rc==SQLITE_OK ){
4609 p->sharedMask |= mask;
4610 }
4611 }else{
4612 /* Make sure no sibling connections hold locks that will block this
4613 ** lock. If any do, return SQLITE_BUSY right away.
4614 */
4615 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004616 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4617 rc = SQLITE_BUSY;
4618 break;
4619 }
4620 }
4621
4622 /* Get the exclusive locks at the system level. Then if successful
4623 ** also mark the local connection as being locked.
4624 */
4625 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004626 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004627 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004628 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004629 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004630 }
drhd9e5c4f2010-05-12 18:01:39 +00004631 }
4632 }
drhd91c68f2010-05-14 14:52:25 +00004633 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004634 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh91eb93c2015-03-03 19:56:20 +00004635 p->id, osGetpid(), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004636 return rc;
4637}
4638
drh286a2882010-05-20 23:51:06 +00004639/*
4640** Implement a memory barrier or memory fence on shared memory.
4641**
4642** All loads and stores begun before the barrier must complete before
4643** any load or store begun after the barrier.
4644*/
4645static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004646 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004647){
drhff828942010-06-26 21:34:06 +00004648 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004649 unixEnterMutex();
4650 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004651}
4652
dan18801912010-06-14 14:07:50 +00004653/*
danda9fe0c2010-07-13 18:44:03 +00004654** Close a connection to shared-memory. Delete the underlying
4655** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004656**
4657** If there is no shared memory associated with the connection then this
4658** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004659*/
danda9fe0c2010-07-13 18:44:03 +00004660static int unixShmUnmap(
4661 sqlite3_file *fd, /* The underlying database file */
4662 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004663){
danda9fe0c2010-07-13 18:44:03 +00004664 unixShm *p; /* The connection to be closed */
4665 unixShmNode *pShmNode; /* The underlying shared-memory file */
4666 unixShm **pp; /* For looping over sibling connections */
4667 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004668
danda9fe0c2010-07-13 18:44:03 +00004669 pDbFd = (unixFile*)fd;
4670 p = pDbFd->pShm;
4671 if( p==0 ) return SQLITE_OK;
4672 pShmNode = p->pShmNode;
4673
4674 assert( pShmNode==pDbFd->pInode->pShmNode );
4675 assert( pShmNode->pInode==pDbFd->pInode );
4676
4677 /* Remove connection p from the set of connections associated
4678 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004679 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004680 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4681 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004682
danda9fe0c2010-07-13 18:44:03 +00004683 /* Free the connection p */
4684 sqlite3_free(p);
4685 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004686 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004687
4688 /* If pShmNode->nRef has reached 0, then close the underlying
4689 ** shared-memory file, too */
4690 unixEnterMutex();
4691 assert( pShmNode->nRef>0 );
4692 pShmNode->nRef--;
4693 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004694 if( deleteFlag && pShmNode->h>=0 ){
4695 osUnlink(pShmNode->zFilename);
4696 }
danda9fe0c2010-07-13 18:44:03 +00004697 unixShmPurge(pDbFd);
4698 }
4699 unixLeaveMutex();
4700
4701 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004702}
drh286a2882010-05-20 23:51:06 +00004703
danda9fe0c2010-07-13 18:44:03 +00004704
drhd9e5c4f2010-05-12 18:01:39 +00004705#else
drh6b017cc2010-06-14 18:01:46 +00004706# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004707# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004708# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004709# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004710#endif /* #ifndef SQLITE_OMIT_WAL */
4711
mistachkine98844f2013-08-24 00:59:24 +00004712#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004713/*
danaef49d72013-03-25 16:28:54 +00004714** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004715*/
danf23da962013-03-23 21:00:41 +00004716static void unixUnmapfile(unixFile *pFd){
4717 assert( pFd->nFetchOut==0 );
4718 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004719 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004720 pFd->pMapRegion = 0;
4721 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004722 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004723 }
4724}
dan5d8a1372013-03-19 19:28:06 +00004725
danaef49d72013-03-25 16:28:54 +00004726/*
dane6ecd662013-04-01 17:56:59 +00004727** Attempt to set the size of the memory mapping maintained by file
4728** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4729**
4730** If successful, this function sets the following variables:
4731**
4732** unixFile.pMapRegion
4733** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004734** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004735**
4736** If unsuccessful, an error message is logged via sqlite3_log() and
4737** the three variables above are zeroed. In this case SQLite should
4738** continue accessing the database using the xRead() and xWrite()
4739** methods.
4740*/
4741static void unixRemapfile(
4742 unixFile *pFd, /* File descriptor object */
4743 i64 nNew /* Required mapping size */
4744){
dan4ff7bc42013-04-02 12:04:09 +00004745 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004746 int h = pFd->h; /* File descriptor open on db file */
4747 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004748 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004749 u8 *pNew = 0; /* Location of new mapping */
4750 int flags = PROT_READ; /* Flags to pass to mmap() */
4751
4752 assert( pFd->nFetchOut==0 );
4753 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004754 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004755 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004756 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004757 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004758
4759 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4760
4761 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004762#if HAVE_MREMAP
4763 i64 nReuse = pFd->mmapSize;
4764#else
danbc760632014-03-20 09:42:09 +00004765 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004766 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004767#endif
dane6ecd662013-04-01 17:56:59 +00004768 u8 *pReq = &pOrig[nReuse];
4769
4770 /* Unmap any pages of the existing mapping that cannot be reused. */
4771 if( nReuse!=nOrig ){
4772 osMunmap(pReq, nOrig-nReuse);
4773 }
4774
4775#if HAVE_MREMAP
4776 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004777 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004778#else
4779 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4780 if( pNew!=MAP_FAILED ){
4781 if( pNew!=pReq ){
4782 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004783 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004784 }else{
4785 pNew = pOrig;
4786 }
4787 }
4788#endif
4789
dan48ccef82013-04-02 20:55:01 +00004790 /* The attempt to extend the existing mapping failed. Free it. */
4791 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004792 osMunmap(pOrig, nReuse);
4793 }
4794 }
4795
4796 /* If pNew is still NULL, try to create an entirely new mapping. */
4797 if( pNew==0 ){
4798 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004799 }
4800
dan4ff7bc42013-04-02 12:04:09 +00004801 if( pNew==MAP_FAILED ){
4802 pNew = 0;
4803 nNew = 0;
4804 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4805
4806 /* If the mmap() above failed, assume that all subsequent mmap() calls
4807 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4808 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004809 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004810 }
dane6ecd662013-04-01 17:56:59 +00004811 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004812 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004813}
4814
4815/*
danaef49d72013-03-25 16:28:54 +00004816** Memory map or remap the file opened by file-descriptor pFd (if the file
4817** is already mapped, the existing mapping is replaced by the new). Or, if
4818** there already exists a mapping for this file, and there are still
4819** outstanding xFetch() references to it, this function is a no-op.
4820**
4821** If parameter nByte is non-negative, then it is the requested size of
4822** the mapping to create. Otherwise, if nByte is less than zero, then the
4823** requested size is the size of the file on disk. The actual size of the
4824** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004825** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004826**
4827** SQLITE_OK is returned if no error occurs (even if the mapping is not
4828** recreated as a result of outstanding references) or an SQLite error
4829** code otherwise.
4830*/
danf23da962013-03-23 21:00:41 +00004831static int unixMapfile(unixFile *pFd, i64 nByte){
4832 i64 nMap = nByte;
4833 int rc;
daneb97b292013-03-20 14:26:59 +00004834
danf23da962013-03-23 21:00:41 +00004835 assert( nMap>=0 || pFd->nFetchOut==0 );
4836 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4837
4838 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004839 struct stat statbuf; /* Low-level file information */
4840 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004841 if( rc!=SQLITE_OK ){
4842 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004843 }
drh3044b512014-06-16 16:41:52 +00004844 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004845 }
drh9b4c59f2013-04-15 17:03:42 +00004846 if( nMap>pFd->mmapSizeMax ){
4847 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004848 }
4849
danf23da962013-03-23 21:00:41 +00004850 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004851 if( nMap>0 ){
4852 unixRemapfile(pFd, nMap);
4853 }else{
danb7e3a322013-03-25 20:30:13 +00004854 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004855 }
4856 }
4857
danf23da962013-03-23 21:00:41 +00004858 return SQLITE_OK;
4859}
mistachkine98844f2013-08-24 00:59:24 +00004860#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004861
danaef49d72013-03-25 16:28:54 +00004862/*
4863** If possible, return a pointer to a mapping of file fd starting at offset
4864** iOff. The mapping must be valid for at least nAmt bytes.
4865**
4866** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4867** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4868** Finally, if an error does occur, return an SQLite error code. The final
4869** value of *pp is undefined in this case.
4870**
4871** If this function does return a pointer, the caller must eventually
4872** release the reference by calling unixUnfetch().
4873*/
danf23da962013-03-23 21:00:41 +00004874static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004875#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004876 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004877#endif
danf23da962013-03-23 21:00:41 +00004878 *pp = 0;
4879
drh9b4c59f2013-04-15 17:03:42 +00004880#if SQLITE_MAX_MMAP_SIZE>0
4881 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004882 if( pFd->pMapRegion==0 ){
4883 int rc = unixMapfile(pFd, -1);
4884 if( rc!=SQLITE_OK ) return rc;
4885 }
4886 if( pFd->mmapSize >= iOff+nAmt ){
4887 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4888 pFd->nFetchOut++;
4889 }
4890 }
drh6e0b6d52013-04-09 16:19:20 +00004891#endif
danf23da962013-03-23 21:00:41 +00004892 return SQLITE_OK;
4893}
4894
danaef49d72013-03-25 16:28:54 +00004895/*
dandf737fe2013-03-25 17:00:24 +00004896** If the third argument is non-NULL, then this function releases a
4897** reference obtained by an earlier call to unixFetch(). The second
4898** argument passed to this function must be the same as the corresponding
4899** argument that was passed to the unixFetch() invocation.
4900**
4901** Or, if the third argument is NULL, then this function is being called
4902** to inform the VFS layer that, according to POSIX, any existing mapping
4903** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004904*/
dandf737fe2013-03-25 17:00:24 +00004905static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004906#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004907 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004908 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004909
danaef49d72013-03-25 16:28:54 +00004910 /* If p==0 (unmap the entire file) then there must be no outstanding
4911 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4912 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004913 assert( (p==0)==(pFd->nFetchOut==0) );
4914
dandf737fe2013-03-25 17:00:24 +00004915 /* If p!=0, it must match the iOff value. */
4916 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4917
danf23da962013-03-23 21:00:41 +00004918 if( p ){
4919 pFd->nFetchOut--;
4920 }else{
4921 unixUnmapfile(pFd);
4922 }
4923
4924 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004925#else
4926 UNUSED_PARAMETER(fd);
4927 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004928 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004929#endif
danf23da962013-03-23 21:00:41 +00004930 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004931}
4932
4933/*
drh734c9862008-11-28 15:37:20 +00004934** Here ends the implementation of all sqlite3_file methods.
4935**
4936********************** End sqlite3_file Methods *******************************
4937******************************************************************************/
4938
4939/*
drh6b9d6dd2008-12-03 19:34:47 +00004940** This division contains definitions of sqlite3_io_methods objects that
4941** implement various file locking strategies. It also contains definitions
4942** of "finder" functions. A finder-function is used to locate the appropriate
4943** sqlite3_io_methods object for a particular database file. The pAppData
4944** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4945** the correct finder-function for that VFS.
4946**
4947** Most finder functions return a pointer to a fixed sqlite3_io_methods
4948** object. The only interesting finder-function is autolockIoFinder, which
4949** looks at the filesystem type and tries to guess the best locking
4950** strategy from that.
4951**
peter.d.reid60ec9142014-09-06 16:39:46 +00004952** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004953**
4954** (1) The real finder-function named "FImpt()".
4955**
dane946c392009-08-22 11:39:46 +00004956** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004957**
4958**
4959** A pointer to the F pointer is used as the pAppData value for VFS
4960** objects. We have to do this instead of letting pAppData point
4961** directly at the finder-function since C90 rules prevent a void*
4962** from be cast into a function pointer.
4963**
drh6b9d6dd2008-12-03 19:34:47 +00004964**
drh7708e972008-11-29 00:56:52 +00004965** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004966**
drh7708e972008-11-29 00:56:52 +00004967** * A constant sqlite3_io_methods object call METHOD that has locking
4968** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4969**
4970** * An I/O method finder function called FINDER that returns a pointer
4971** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004972*/
drhe6d41732015-02-21 00:49:00 +00004973#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004974static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004975 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004976 CLOSE, /* xClose */ \
4977 unixRead, /* xRead */ \
4978 unixWrite, /* xWrite */ \
4979 unixTruncate, /* xTruncate */ \
4980 unixSync, /* xSync */ \
4981 unixFileSize, /* xFileSize */ \
4982 LOCK, /* xLock */ \
4983 UNLOCK, /* xUnlock */ \
4984 CKLOCK, /* xCheckReservedLock */ \
4985 unixFileControl, /* xFileControl */ \
4986 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004987 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004988 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004989 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004990 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004991 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004992 unixFetch, /* xFetch */ \
4993 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004994}; \
drh0c2694b2009-09-03 16:23:44 +00004995static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4996 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004997 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004998} \
drh0c2694b2009-09-03 16:23:44 +00004999static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005000 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005001
5002/*
5003** Here are all of the sqlite3_io_methods objects for each of the
5004** locking strategies. Functions that return pointers to these methods
5005** are also created.
5006*/
5007IOMETHODS(
5008 posixIoFinder, /* Finder function name */
5009 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005010 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005011 unixClose, /* xClose method */
5012 unixLock, /* xLock method */
5013 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005014 unixCheckReservedLock, /* xCheckReservedLock method */
5015 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005016)
drh7708e972008-11-29 00:56:52 +00005017IOMETHODS(
5018 nolockIoFinder, /* Finder function name */
5019 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005020 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005021 nolockClose, /* xClose method */
5022 nolockLock, /* xLock method */
5023 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005024 nolockCheckReservedLock, /* xCheckReservedLock method */
5025 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005026)
drh7708e972008-11-29 00:56:52 +00005027IOMETHODS(
5028 dotlockIoFinder, /* Finder function name */
5029 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005030 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005031 dotlockClose, /* xClose method */
5032 dotlockLock, /* xLock method */
5033 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005034 dotlockCheckReservedLock, /* xCheckReservedLock method */
5035 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005036)
drh7708e972008-11-29 00:56:52 +00005037
drhe89b2912015-03-03 20:42:01 +00005038#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005039IOMETHODS(
5040 flockIoFinder, /* Finder function name */
5041 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005042 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005043 flockClose, /* xClose method */
5044 flockLock, /* xLock method */
5045 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005046 flockCheckReservedLock, /* xCheckReservedLock method */
5047 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005048)
drh7708e972008-11-29 00:56:52 +00005049#endif
5050
drh6c7d5c52008-11-21 20:32:33 +00005051#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005052IOMETHODS(
5053 semIoFinder, /* Finder function name */
5054 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005055 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005056 semXClose, /* xClose method */
5057 semXLock, /* xLock method */
5058 semXUnlock, /* xUnlock method */
5059 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005060 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005061)
aswiftaebf4132008-11-21 00:10:35 +00005062#endif
drh7708e972008-11-29 00:56:52 +00005063
drhd2cb50b2009-01-09 21:41:17 +00005064#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005065IOMETHODS(
5066 afpIoFinder, /* Finder function name */
5067 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005068 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005069 afpClose, /* xClose method */
5070 afpLock, /* xLock method */
5071 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005072 afpCheckReservedLock, /* xCheckReservedLock method */
5073 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005074)
drh715ff302008-12-03 22:32:44 +00005075#endif
5076
5077/*
5078** The proxy locking method is a "super-method" in the sense that it
5079** opens secondary file descriptors for the conch and lock files and
5080** it uses proxy, dot-file, AFP, and flock() locking methods on those
5081** secondary files. For this reason, the division that implements
5082** proxy locking is located much further down in the file. But we need
5083** to go ahead and define the sqlite3_io_methods and finder function
5084** for proxy locking here. So we forward declare the I/O methods.
5085*/
drhd2cb50b2009-01-09 21:41:17 +00005086#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005087static int proxyClose(sqlite3_file*);
5088static int proxyLock(sqlite3_file*, int);
5089static int proxyUnlock(sqlite3_file*, int);
5090static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005091IOMETHODS(
5092 proxyIoFinder, /* Finder function name */
5093 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005094 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005095 proxyClose, /* xClose method */
5096 proxyLock, /* xLock method */
5097 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005098 proxyCheckReservedLock, /* xCheckReservedLock method */
5099 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005100)
aswiftaebf4132008-11-21 00:10:35 +00005101#endif
drh7708e972008-11-29 00:56:52 +00005102
drh7ed97b92010-01-20 13:07:21 +00005103/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5104#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5105IOMETHODS(
5106 nfsIoFinder, /* Finder function name */
5107 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005108 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005109 unixClose, /* xClose method */
5110 unixLock, /* xLock method */
5111 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005112 unixCheckReservedLock, /* xCheckReservedLock method */
5113 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005114)
5115#endif
drh7708e972008-11-29 00:56:52 +00005116
drhd2cb50b2009-01-09 21:41:17 +00005117#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005118/*
drh6b9d6dd2008-12-03 19:34:47 +00005119** This "finder" function attempts to determine the best locking strategy
5120** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005121** object that implements that strategy.
5122**
5123** This is for MacOSX only.
5124*/
drh1875f7a2008-12-08 18:19:17 +00005125static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005126 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005127 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005128){
5129 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005130 const char *zFilesystem; /* Filesystem type name */
5131 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005132 } aMap[] = {
5133 { "hfs", &posixIoMethods },
5134 { "ufs", &posixIoMethods },
5135 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005136 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005137 { "webdav", &nolockIoMethods },
5138 { 0, 0 }
5139 };
5140 int i;
5141 struct statfs fsInfo;
5142 struct flock lockInfo;
5143
5144 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005145 /* If filePath==NULL that means we are dealing with a transient file
5146 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005147 return &nolockIoMethods;
5148 }
5149 if( statfs(filePath, &fsInfo) != -1 ){
5150 if( fsInfo.f_flags & MNT_RDONLY ){
5151 return &nolockIoMethods;
5152 }
5153 for(i=0; aMap[i].zFilesystem; i++){
5154 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5155 return aMap[i].pMethods;
5156 }
5157 }
5158 }
5159
5160 /* Default case. Handles, amongst others, "nfs".
5161 ** Test byte-range lock using fcntl(). If the call succeeds,
5162 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005163 */
drh7708e972008-11-29 00:56:52 +00005164 lockInfo.l_len = 1;
5165 lockInfo.l_start = 0;
5166 lockInfo.l_whence = SEEK_SET;
5167 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005168 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005169 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5170 return &nfsIoMethods;
5171 } else {
5172 return &posixIoMethods;
5173 }
drh7708e972008-11-29 00:56:52 +00005174 }else{
5175 return &dotlockIoMethods;
5176 }
5177}
drh0c2694b2009-09-03 16:23:44 +00005178static const sqlite3_io_methods
5179 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005180
drhd2cb50b2009-01-09 21:41:17 +00005181#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005182
drhe89b2912015-03-03 20:42:01 +00005183#if OS_VXWORKS
5184/*
5185** This "finder" function for VxWorks checks to see if posix advisory
5186** locking works. If it does, then that is what is used. If it does not
5187** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005188*/
drhe89b2912015-03-03 20:42:01 +00005189static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005190 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005191 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005192){
5193 struct flock lockInfo;
5194
5195 if( !filePath ){
5196 /* If filePath==NULL that means we are dealing with a transient file
5197 ** that does not need to be locked. */
5198 return &nolockIoMethods;
5199 }
5200
5201 /* Test if fcntl() is supported and use POSIX style locks.
5202 ** Otherwise fall back to the named semaphore method.
5203 */
5204 lockInfo.l_len = 1;
5205 lockInfo.l_start = 0;
5206 lockInfo.l_whence = SEEK_SET;
5207 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005208 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005209 return &posixIoMethods;
5210 }else{
5211 return &semIoMethods;
5212 }
5213}
drh0c2694b2009-09-03 16:23:44 +00005214static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005215 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005216
drhe89b2912015-03-03 20:42:01 +00005217#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005218
drh7708e972008-11-29 00:56:52 +00005219/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005220** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005221*/
drh0c2694b2009-09-03 16:23:44 +00005222typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005223
aswiftaebf4132008-11-21 00:10:35 +00005224
drh734c9862008-11-28 15:37:20 +00005225/****************************************************************************
5226**************************** sqlite3_vfs methods ****************************
5227**
5228** This division contains the implementation of methods on the
5229** sqlite3_vfs object.
5230*/
5231
danielk1977a3d4c882007-03-23 10:08:38 +00005232/*
danielk1977e339d652008-06-28 11:23:00 +00005233** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005234*/
5235static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005236 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005237 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005238 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005239 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005240 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005241){
drh7708e972008-11-29 00:56:52 +00005242 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005243 unixFile *pNew = (unixFile *)pId;
5244 int rc = SQLITE_OK;
5245
drh8af6c222010-05-14 12:43:01 +00005246 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005247
dan00157392010-10-05 11:33:15 +00005248 /* Usually the path zFilename should not be a relative pathname. The
5249 ** exception is when opening the proxy "conch" file in builds that
5250 ** include the special Apple locking styles.
5251 */
dan00157392010-10-05 11:33:15 +00005252#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005253 assert( zFilename==0 || zFilename[0]=='/'
5254 || pVfs->pAppData==(void*)&autolockIoFinder );
5255#else
5256 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005257#endif
dan00157392010-10-05 11:33:15 +00005258
drhb07028f2011-10-14 21:49:18 +00005259 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005260 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005261
drh308c2a52010-05-14 11:30:18 +00005262 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005263 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005264 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005265 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005266 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005267#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005268 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005269#endif
drhc02a43a2012-01-10 23:18:38 +00005270 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5271 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005272 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005273 }
drh503a6862013-03-01 01:07:17 +00005274 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005275 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005276 }
drh339eb0b2008-03-07 15:34:11 +00005277
drh6c7d5c52008-11-21 20:32:33 +00005278#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005279 pNew->pId = vxworksFindFileId(zFilename);
5280 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005281 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005282 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005283 }
5284#endif
5285
drhc02a43a2012-01-10 23:18:38 +00005286 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005287 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005288 }else{
drh0c2694b2009-09-03 16:23:44 +00005289 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005290#if SQLITE_ENABLE_LOCKING_STYLE
5291 /* Cache zFilename in the locking context (AFP and dotlock override) for
5292 ** proxyLock activation is possible (remote proxy is based on db name)
5293 ** zFilename remains valid until file is closed, to support */
5294 pNew->lockingContext = (void*)zFilename;
5295#endif
drhda0e7682008-07-30 15:27:54 +00005296 }
danielk1977e339d652008-06-28 11:23:00 +00005297
drh7ed97b92010-01-20 13:07:21 +00005298 if( pLockingStyle == &posixIoMethods
5299#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5300 || pLockingStyle == &nfsIoMethods
5301#endif
5302 ){
drh7708e972008-11-29 00:56:52 +00005303 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005304 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005305 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005306 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005307 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005308 ** in two scenarios:
5309 **
5310 ** (a) A call to fstat() failed.
5311 ** (b) A malloc failed.
5312 **
5313 ** Scenario (b) may only occur if the process is holding no other
5314 ** file descriptors open on the same file. If there were other file
5315 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005316 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005317 ** handle h - as it is guaranteed that no posix locks will be released
5318 ** by doing so.
5319 **
5320 ** If scenario (a) caused the error then things are not so safe. The
5321 ** implicit assumption here is that if fstat() fails, things are in
5322 ** such bad shape that dropping a lock or two doesn't matter much.
5323 */
drh0e9365c2011-03-02 02:08:13 +00005324 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005325 h = -1;
5326 }
drh7708e972008-11-29 00:56:52 +00005327 unixLeaveMutex();
5328 }
danielk1977e339d652008-06-28 11:23:00 +00005329
drhd2cb50b2009-01-09 21:41:17 +00005330#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005331 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005332 /* AFP locking uses the file path so it needs to be included in
5333 ** the afpLockingContext.
5334 */
5335 afpLockingContext *pCtx;
5336 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5337 if( pCtx==0 ){
5338 rc = SQLITE_NOMEM;
5339 }else{
5340 /* NB: zFilename exists and remains valid until the file is closed
5341 ** according to requirement F11141. So we do not need to make a
5342 ** copy of the filename. */
5343 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005344 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005345 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005346 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005347 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005348 if( rc!=SQLITE_OK ){
5349 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005350 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005351 h = -1;
5352 }
drh7708e972008-11-29 00:56:52 +00005353 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005354 }
drh7708e972008-11-29 00:56:52 +00005355 }
5356#endif
danielk1977e339d652008-06-28 11:23:00 +00005357
drh7708e972008-11-29 00:56:52 +00005358 else if( pLockingStyle == &dotlockIoMethods ){
5359 /* Dotfile locking uses the file path so it needs to be included in
5360 ** the dotlockLockingContext
5361 */
5362 char *zLockFile;
5363 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005364 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005365 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005366 zLockFile = (char *)sqlite3_malloc(nFilename);
5367 if( zLockFile==0 ){
5368 rc = SQLITE_NOMEM;
5369 }else{
5370 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005371 }
drh7708e972008-11-29 00:56:52 +00005372 pNew->lockingContext = zLockFile;
5373 }
danielk1977e339d652008-06-28 11:23:00 +00005374
drh6c7d5c52008-11-21 20:32:33 +00005375#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005376 else if( pLockingStyle == &semIoMethods ){
5377 /* Named semaphore locking uses the file path so it needs to be
5378 ** included in the semLockingContext
5379 */
5380 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005381 rc = findInodeInfo(pNew, &pNew->pInode);
5382 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5383 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005384 int n;
drh2238dcc2009-08-27 17:56:20 +00005385 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005386 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005387 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005388 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005389 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5390 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005391 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005392 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005393 }
chw97185482008-11-17 08:05:31 +00005394 }
drh7708e972008-11-29 00:56:52 +00005395 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005396 }
drh7708e972008-11-29 00:56:52 +00005397#endif
aswift5b1a2562008-08-22 00:22:35 +00005398
drh4bf66fd2015-02-19 02:43:02 +00005399 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005400#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005401 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005402 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005403 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005404 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005405 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005406 }
chw97185482008-11-17 08:05:31 +00005407#endif
danielk1977e339d652008-06-28 11:23:00 +00005408 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005409 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005410 }else{
drh7708e972008-11-29 00:56:52 +00005411 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005412 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005413 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005414 }
danielk1977e339d652008-06-28 11:23:00 +00005415 return rc;
drh054889e2005-11-30 03:20:31 +00005416}
drh9c06c952005-11-26 00:25:00 +00005417
danielk1977ad94b582007-08-20 06:44:22 +00005418/*
drh8b3cf822010-06-01 21:02:51 +00005419** Return the name of a directory in which to put temporary files.
5420** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005421*/
drh7234c6d2010-06-19 15:10:09 +00005422static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005423 static const char *azDirs[] = {
5424 0,
aswiftaebf4132008-11-21 00:10:35 +00005425 0,
mistachkind95a3d32013-08-30 21:52:38 +00005426 0,
danielk197717b90b52008-06-06 11:11:25 +00005427 "/var/tmp",
5428 "/usr/tmp",
5429 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005430 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005431 };
drh8b3cf822010-06-01 21:02:51 +00005432 unsigned int i;
5433 struct stat buf;
5434 const char *zDir = 0;
5435
5436 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005437 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5438 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005439 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005440 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005441 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005442 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005443 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005444 break;
5445 }
5446 return zDir;
5447}
5448
5449/*
5450** Create a temporary file name in zBuf. zBuf must be allocated
5451** by the calling process and must be big enough to hold at least
5452** pVfs->mxPathname bytes.
5453*/
5454static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005455 static const unsigned char zChars[] =
5456 "abcdefghijklmnopqrstuvwxyz"
5457 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5458 "0123456789";
drh41022642008-11-21 00:24:42 +00005459 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005460 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005461
5462 /* It's odd to simulate an io-error here, but really this is just
5463 ** using the io-error infrastructure to test that SQLite handles this
5464 ** function failing.
5465 */
5466 SimulateIOError( return SQLITE_IOERR );
5467
drh7234c6d2010-06-19 15:10:09 +00005468 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005469 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005470
5471 /* Check that the output buffer is large enough for the temporary file
5472 ** name. If it is not, return SQLITE_ERROR.
5473 */
drhc02a43a2012-01-10 23:18:38 +00005474 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005475 return SQLITE_ERROR;
5476 }
5477
5478 do{
drhc02a43a2012-01-10 23:18:38 +00005479 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005480 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005481 sqlite3_randomness(15, &zBuf[j]);
5482 for(i=0; i<15; i++, j++){
5483 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5484 }
5485 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005486 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005487 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005488 return SQLITE_OK;
5489}
5490
drhd2cb50b2009-01-09 21:41:17 +00005491#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005492/*
5493** Routine to transform a unixFile into a proxy-locking unixFile.
5494** Implementation in the proxy-lock division, but used by unixOpen()
5495** if SQLITE_PREFER_PROXY_LOCKING is defined.
5496*/
5497static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005498#endif
drhc66d5b62008-12-03 22:48:32 +00005499
dan08da86a2009-08-21 17:18:03 +00005500/*
5501** Search for an unused file descriptor that was opened on the database
5502** file (not a journal or master-journal file) identified by pathname
5503** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5504** argument to this function.
5505**
5506** Such a file descriptor may exist if a database connection was closed
5507** but the associated file descriptor could not be closed because some
5508** other file descriptor open on the same file is holding a file-lock.
5509** Refer to comments in the unixClose() function and the lengthy comment
5510** describing "Posix Advisory Locking" at the start of this file for
5511** further details. Also, ticket #4018.
5512**
5513** If a suitable file descriptor is found, then it is returned. If no
5514** such file descriptor is located, -1 is returned.
5515*/
dane946c392009-08-22 11:39:46 +00005516static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5517 UnixUnusedFd *pUnused = 0;
5518
5519 /* Do not search for an unused file descriptor on vxworks. Not because
5520 ** vxworks would not benefit from the change (it might, we're not sure),
5521 ** but because no way to test it is currently available. It is better
5522 ** not to risk breaking vxworks support for the sake of such an obscure
5523 ** feature. */
5524#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005525 struct stat sStat; /* Results of stat() call */
5526
5527 /* A stat() call may fail for various reasons. If this happens, it is
5528 ** almost certain that an open() call on the same path will also fail.
5529 ** For this reason, if an error occurs in the stat() call here, it is
5530 ** ignored and -1 is returned. The caller will try to open a new file
5531 ** descriptor on the same path, fail, and return an error to SQLite.
5532 **
5533 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005534 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005535 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005536 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005537
5538 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005539 pInode = inodeList;
5540 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5541 || pInode->fileId.ino!=sStat.st_ino) ){
5542 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005543 }
drh8af6c222010-05-14 12:43:01 +00005544 if( pInode ){
dane946c392009-08-22 11:39:46 +00005545 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005546 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005547 pUnused = *pp;
5548 if( pUnused ){
5549 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005550 }
5551 }
5552 unixLeaveMutex();
5553 }
dane946c392009-08-22 11:39:46 +00005554#endif /* if !OS_VXWORKS */
5555 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005556}
danielk197717b90b52008-06-06 11:11:25 +00005557
5558/*
danddb0ac42010-07-14 14:48:58 +00005559** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005560** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005561** and a value suitable for passing as the third argument to open(2) is
5562** written to *pMode. If an IO error occurs, an SQLite error code is
5563** returned and the value of *pMode is not modified.
5564**
peter.d.reid60ec9142014-09-06 16:39:46 +00005565** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005566** an indication to robust_open() to create the file using
5567** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5568** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005569** this function queries the file-system for the permissions on the
5570** corresponding database file and sets *pMode to this value. Whenever
5571** possible, WAL and journal files are created using the same permissions
5572** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005573**
5574** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5575** original filename is unavailable. But 8_3_NAMES is only used for
5576** FAT filesystems and permissions do not matter there, so just use
5577** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005578*/
5579static int findCreateFileMode(
5580 const char *zPath, /* Path of file (possibly) being created */
5581 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005582 mode_t *pMode, /* OUT: Permissions to open file with */
5583 uid_t *pUid, /* OUT: uid to set on the file */
5584 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005585){
5586 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005587 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005588 *pUid = 0;
5589 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005590 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005591 char zDb[MAX_PATHNAME+1]; /* Database file path */
5592 int nDb; /* Number of valid bytes in zDb */
5593 struct stat sStat; /* Output of stat() on database file */
5594
dana0c989d2010-11-05 18:07:37 +00005595 /* zPath is a path to a WAL or journal file. The following block derives
5596 ** the path to the associated database file from zPath. This block handles
5597 ** the following naming conventions:
5598 **
5599 ** "<path to db>-journal"
5600 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005601 ** "<path to db>-journalNN"
5602 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005603 **
drhd337c5b2011-10-20 18:23:35 +00005604 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005605 ** used by the test_multiplex.c module.
5606 */
5607 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005608#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005609 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005610 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005611#else
5612 while( zPath[nDb]!='-' ){
5613 assert( nDb>0 );
5614 assert( zPath[nDb]!='\n' );
5615 nDb--;
5616 }
5617#endif
danddb0ac42010-07-14 14:48:58 +00005618 memcpy(zDb, zPath, nDb);
5619 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005620
drh58384f12011-07-28 00:14:45 +00005621 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005622 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005623 *pUid = sStat.st_uid;
5624 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005625 }else{
5626 rc = SQLITE_IOERR_FSTAT;
5627 }
5628 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5629 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005630 }
5631 return rc;
5632}
5633
5634/*
danielk1977ad94b582007-08-20 06:44:22 +00005635** Open the file zPath.
5636**
danielk1977b4b47412007-08-17 15:53:36 +00005637** Previously, the SQLite OS layer used three functions in place of this
5638** one:
5639**
5640** sqlite3OsOpenReadWrite();
5641** sqlite3OsOpenReadOnly();
5642** sqlite3OsOpenExclusive();
5643**
5644** These calls correspond to the following combinations of flags:
5645**
5646** ReadWrite() -> (READWRITE | CREATE)
5647** ReadOnly() -> (READONLY)
5648** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5649**
5650** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5651** true, the file was configured to be automatically deleted when the
5652** file handle closed. To achieve the same effect using this new
5653** interface, add the DELETEONCLOSE flag to those specified above for
5654** OpenExclusive().
5655*/
5656static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005657 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5658 const char *zPath, /* Pathname of file to be opened */
5659 sqlite3_file *pFile, /* The file descriptor to be filled in */
5660 int flags, /* Input flags to control the opening */
5661 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005662){
dan08da86a2009-08-21 17:18:03 +00005663 unixFile *p = (unixFile *)pFile;
5664 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005665 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005666 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005667 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005668 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005669 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005670
5671 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5672 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5673 int isCreate = (flags & SQLITE_OPEN_CREATE);
5674 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5675 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005676#if SQLITE_ENABLE_LOCKING_STYLE
5677 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5678#endif
drh3d4435b2011-08-26 20:55:50 +00005679#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5680 struct statfs fsInfo;
5681#endif
danielk1977b4b47412007-08-17 15:53:36 +00005682
danielk1977fee2d252007-08-18 10:59:19 +00005683 /* If creating a master or main-file journal, this function will open
5684 ** a file-descriptor on the directory too. The first time unixSync()
5685 ** is called the directory file descriptor will be fsync()ed and close()d.
5686 */
drh0059eae2011-08-08 23:48:40 +00005687 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005688 eType==SQLITE_OPEN_MASTER_JOURNAL
5689 || eType==SQLITE_OPEN_MAIN_JOURNAL
5690 || eType==SQLITE_OPEN_WAL
5691 ));
danielk1977fee2d252007-08-18 10:59:19 +00005692
danielk197717b90b52008-06-06 11:11:25 +00005693 /* If argument zPath is a NULL pointer, this function is required to open
5694 ** a temporary file. Use this buffer to store the file name in.
5695 */
drhc02a43a2012-01-10 23:18:38 +00005696 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005697 const char *zName = zPath;
5698
danielk1977fee2d252007-08-18 10:59:19 +00005699 /* Check the following statements are true:
5700 **
5701 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5702 ** (b) if CREATE is set, then READWRITE must also be set, and
5703 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005704 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005705 */
danielk1977b4b47412007-08-17 15:53:36 +00005706 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005707 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005708 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005709 assert(isDelete==0 || isCreate);
5710
danddb0ac42010-07-14 14:48:58 +00005711 /* The main DB, main journal, WAL file and master journal are never
5712 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005713 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5714 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5715 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005716 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005717
danielk1977fee2d252007-08-18 10:59:19 +00005718 /* Assert that the upper layer has set one of the "file-type" flags. */
5719 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5720 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5721 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005722 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005723 );
5724
drhb00d8622014-01-01 15:18:36 +00005725 /* Detect a pid change and reset the PRNG. There is a race condition
5726 ** here such that two or more threads all trying to open databases at
5727 ** the same instant might all reset the PRNG. But multiple resets
5728 ** are harmless.
5729 */
drh91eb93c2015-03-03 19:56:20 +00005730 if( randomnessPid!=osGetpid() ){
5731 randomnessPid = osGetpid();
drhb00d8622014-01-01 15:18:36 +00005732 sqlite3_randomness(0,0);
5733 }
5734
dan08da86a2009-08-21 17:18:03 +00005735 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005736
dan08da86a2009-08-21 17:18:03 +00005737 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005738 UnixUnusedFd *pUnused;
5739 pUnused = findReusableFd(zName, flags);
5740 if( pUnused ){
5741 fd = pUnused->fd;
5742 }else{
dan6aa657f2009-08-24 18:57:58 +00005743 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005744 if( !pUnused ){
5745 return SQLITE_NOMEM;
5746 }
5747 }
5748 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005749
5750 /* Database filenames are double-zero terminated if they are not
5751 ** URIs with parameters. Hence, they can always be passed into
5752 ** sqlite3_uri_parameter(). */
5753 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5754
dan08da86a2009-08-21 17:18:03 +00005755 }else if( !zName ){
5756 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005757 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005758 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005759 if( rc!=SQLITE_OK ){
5760 return rc;
5761 }
5762 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005763
5764 /* Generated temporary filenames are always double-zero terminated
5765 ** for use by sqlite3_uri_parameter(). */
5766 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005767 }
5768
dan08da86a2009-08-21 17:18:03 +00005769 /* Determine the value of the flags parameter passed to POSIX function
5770 ** open(). These must be calculated even if open() is not called, as
5771 ** they may be stored as part of the file handle and used by the
5772 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005773 if( isReadonly ) openFlags |= O_RDONLY;
5774 if( isReadWrite ) openFlags |= O_RDWR;
5775 if( isCreate ) openFlags |= O_CREAT;
5776 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5777 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005778
danielk1977b4b47412007-08-17 15:53:36 +00005779 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005780 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005781 uid_t uid; /* Userid for the file */
5782 gid_t gid; /* Groupid for the file */
5783 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005784 if( rc!=SQLITE_OK ){
5785 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005786 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005787 return rc;
5788 }
drhad4f1e52011-03-04 15:43:57 +00005789 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005790 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005791 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5792 /* Failed to open the file for read/write access. Try read-only. */
5793 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005794 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005795 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005796 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005797 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005798 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005799 }
5800 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005801 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005802 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005803 }
drhac7c3ac2012-02-11 19:23:48 +00005804
5805 /* If this process is running as root and if creating a new rollback
5806 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005807 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005808 */
5809 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005810 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005811 }
danielk1977b4b47412007-08-17 15:53:36 +00005812 }
dan08da86a2009-08-21 17:18:03 +00005813 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005814 if( pOutFlags ){
5815 *pOutFlags = flags;
5816 }
5817
dane946c392009-08-22 11:39:46 +00005818 if( p->pUnused ){
5819 p->pUnused->fd = fd;
5820 p->pUnused->flags = flags;
5821 }
5822
danielk1977b4b47412007-08-17 15:53:36 +00005823 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005824#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005825 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005826#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5827 zPath = sqlite3_mprintf("%s", zName);
5828 if( zPath==0 ){
5829 robust_close(p, fd, __LINE__);
5830 return SQLITE_NOMEM;
5831 }
chw97185482008-11-17 08:05:31 +00005832#else
drh036ac7f2011-08-08 23:18:05 +00005833 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005834#endif
danielk1977b4b47412007-08-17 15:53:36 +00005835 }
drh41022642008-11-21 00:24:42 +00005836#if SQLITE_ENABLE_LOCKING_STYLE
5837 else{
dan08da86a2009-08-21 17:18:03 +00005838 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005839 }
5840#endif
5841
drhda0e7682008-07-30 15:27:54 +00005842 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005843
drh7ed97b92010-01-20 13:07:21 +00005844
5845#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005846 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005847 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005848 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005849 return SQLITE_IOERR_ACCESS;
5850 }
5851 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5852 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5853 }
drh4bf66fd2015-02-19 02:43:02 +00005854 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5855 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5856 }
drh7ed97b92010-01-20 13:07:21 +00005857#endif
drhc02a43a2012-01-10 23:18:38 +00005858
5859 /* Set up appropriate ctrlFlags */
5860 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5861 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5862 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5863 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5864 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5865
drh7ed97b92010-01-20 13:07:21 +00005866#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005867#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005868 isAutoProxy = 1;
5869#endif
5870 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005871 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5872 int useProxy = 0;
5873
dan08da86a2009-08-21 17:18:03 +00005874 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5875 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005876 if( envforce!=NULL ){
5877 useProxy = atoi(envforce)>0;
5878 }else{
aswiftaebf4132008-11-21 00:10:35 +00005879 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5880 }
5881 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005882 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005883 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005884 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005885 if( rc!=SQLITE_OK ){
5886 /* Use unixClose to clean up the resources added in fillInUnixFile
5887 ** and clear all the structure's references. Specifically,
5888 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5889 */
5890 unixClose(pFile);
5891 return rc;
5892 }
aswiftaebf4132008-11-21 00:10:35 +00005893 }
dane946c392009-08-22 11:39:46 +00005894 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005895 }
5896 }
5897#endif
5898
drhc02a43a2012-01-10 23:18:38 +00005899 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5900
dane946c392009-08-22 11:39:46 +00005901open_finished:
5902 if( rc!=SQLITE_OK ){
5903 sqlite3_free(p->pUnused);
5904 }
5905 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005906}
5907
dane946c392009-08-22 11:39:46 +00005908
danielk1977b4b47412007-08-17 15:53:36 +00005909/*
danielk1977fee2d252007-08-18 10:59:19 +00005910** Delete the file at zPath. If the dirSync argument is true, fsync()
5911** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005912*/
drh6b9d6dd2008-12-03 19:34:47 +00005913static int unixDelete(
5914 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5915 const char *zPath, /* Name of file to be deleted */
5916 int dirSync /* If true, fsync() directory after deleting file */
5917){
danielk1977fee2d252007-08-18 10:59:19 +00005918 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005919 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005920 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005921 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005922 if( errno==ENOENT
5923#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005924 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005925#endif
5926 ){
dan9fc5b4a2012-11-09 20:17:26 +00005927 rc = SQLITE_IOERR_DELETE_NOENT;
5928 }else{
drhb4308162012-11-09 21:40:02 +00005929 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005930 }
drhb4308162012-11-09 21:40:02 +00005931 return rc;
drh5d4feff2010-07-14 01:45:22 +00005932 }
danielk1977d39fa702008-10-16 13:27:40 +00005933#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005934 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005935 int fd;
drh90315a22011-08-10 01:52:12 +00005936 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005937 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005938#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005939 if( fsync(fd)==-1 )
5940#else
5941 if( fsync(fd) )
5942#endif
5943 {
dane18d4952011-02-21 11:46:24 +00005944 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005945 }
drh0e9365c2011-03-02 02:08:13 +00005946 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005947 }else if( rc==SQLITE_CANTOPEN ){
5948 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005949 }
5950 }
danielk1977d138dd82008-10-15 16:02:48 +00005951#endif
danielk1977fee2d252007-08-18 10:59:19 +00005952 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005953}
5954
danielk197790949c22007-08-17 16:50:38 +00005955/*
mistachkin48864df2013-03-21 21:20:32 +00005956** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005957** test performed depends on the value of flags:
5958**
5959** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5960** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5961** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5962**
5963** Otherwise return 0.
5964*/
danielk1977861f7452008-06-05 11:39:11 +00005965static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005966 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5967 const char *zPath, /* Path of the file to examine */
5968 int flags, /* What do we want to learn about the zPath file? */
5969 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005970){
rse25c0d1a2007-09-20 08:38:14 +00005971 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005972 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005973 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005974 switch( flags ){
5975 case SQLITE_ACCESS_EXISTS:
5976 amode = F_OK;
5977 break;
5978 case SQLITE_ACCESS_READWRITE:
5979 amode = W_OK|R_OK;
5980 break;
drh50d3f902007-08-27 21:10:36 +00005981 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005982 amode = R_OK;
5983 break;
5984
5985 default:
5986 assert(!"Invalid flags argument");
5987 }
drh99ab3b12011-03-02 15:09:07 +00005988 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00005989 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
5990 struct stat buf;
drh58384f12011-07-28 00:14:45 +00005991 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00005992 *pResOut = 0;
5993 }
5994 }
danielk1977861f7452008-06-05 11:39:11 +00005995 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005996}
5997
danielk1977b4b47412007-08-17 15:53:36 +00005998
5999/*
6000** Turn a relative pathname into a full pathname. The relative path
6001** is stored as a nul-terminated string in the buffer pointed to by
6002** zPath.
6003**
6004** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6005** (in this case, MAX_PATHNAME bytes). The full-path is written to
6006** this buffer before returning.
6007*/
danielk1977adfb9b02007-09-17 07:02:56 +00006008static int unixFullPathname(
6009 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6010 const char *zPath, /* Possibly relative input path */
6011 int nOut, /* Size of output buffer in bytes */
6012 char *zOut /* Output buffer */
6013){
danielk1977843e65f2007-09-01 16:16:15 +00006014
6015 /* It's odd to simulate an io-error here, but really this is just
6016 ** using the io-error infrastructure to test that SQLite handles this
6017 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006018 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006019 */
6020 SimulateIOError( return SQLITE_ERROR );
6021
drh153c62c2007-08-24 03:51:33 +00006022 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006023 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006024
drh3c7f2dc2007-12-06 13:26:20 +00006025 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006026 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006027 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006028 }else{
6029 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006030 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006031 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006032 }
drhea678832008-12-10 19:26:22 +00006033 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006034 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006035 }
6036 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006037}
6038
drh0ccebe72005-06-07 22:22:50 +00006039
drh761df872006-12-21 01:29:22 +00006040#ifndef SQLITE_OMIT_LOAD_EXTENSION
6041/*
6042** Interfaces for opening a shared library, finding entry points
6043** within the shared library, and closing the shared library.
6044*/
6045#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006046static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6047 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006048 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6049}
danielk197795c8a542007-09-01 06:51:27 +00006050
6051/*
6052** SQLite calls this function immediately after a call to unixDlSym() or
6053** unixDlOpen() fails (returns a null pointer). If a more detailed error
6054** message is available, it is written to zBufOut. If no error message
6055** is available, zBufOut is left unmodified and SQLite uses a default
6056** error message.
6057*/
danielk1977397d65f2008-11-19 11:35:39 +00006058static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006059 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006060 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006061 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006062 zErr = dlerror();
6063 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006064 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006065 }
drh6c7d5c52008-11-21 20:32:33 +00006066 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006067}
drh1875f7a2008-12-08 18:19:17 +00006068static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6069 /*
6070 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6071 ** cast into a pointer to a function. And yet the library dlsym() routine
6072 ** returns a void* which is really a pointer to a function. So how do we
6073 ** use dlsym() with -pedantic-errors?
6074 **
6075 ** Variable x below is defined to be a pointer to a function taking
6076 ** parameters void* and const char* and returning a pointer to a function.
6077 ** We initialize x by assigning it a pointer to the dlsym() function.
6078 ** (That assignment requires a cast.) Then we call the function that
6079 ** x points to.
6080 **
6081 ** This work-around is unlikely to work correctly on any system where
6082 ** you really cannot cast a function pointer into void*. But then, on the
6083 ** other hand, dlsym() will not work on such a system either, so we have
6084 ** not really lost anything.
6085 */
6086 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006087 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006088 x = (void(*(*)(void*,const char*))(void))dlsym;
6089 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006090}
danielk1977397d65f2008-11-19 11:35:39 +00006091static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6092 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006093 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006094}
danielk1977b4b47412007-08-17 15:53:36 +00006095#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6096 #define unixDlOpen 0
6097 #define unixDlError 0
6098 #define unixDlSym 0
6099 #define unixDlClose 0
6100#endif
6101
6102/*
danielk197790949c22007-08-17 16:50:38 +00006103** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006104*/
danielk1977397d65f2008-11-19 11:35:39 +00006105static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6106 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006107 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006108
drhbbd42a62004-05-22 17:41:58 +00006109 /* We have to initialize zBuf to prevent valgrind from reporting
6110 ** errors. The reports issued by valgrind are incorrect - we would
6111 ** prefer that the randomness be increased by making use of the
6112 ** uninitialized space in zBuf - but valgrind errors tend to worry
6113 ** some users. Rather than argue, it seems easier just to initialize
6114 ** the whole array and silence valgrind, even if that means less randomness
6115 ** in the random seed.
6116 **
6117 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006118 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006119 ** tests repeatable.
6120 */
danielk1977b4b47412007-08-17 15:53:36 +00006121 memset(zBuf, 0, nBuf);
drh91eb93c2015-03-03 19:56:20 +00006122 randomnessPid = osGetpid();
drhbbd42a62004-05-22 17:41:58 +00006123#if !defined(SQLITE_TEST)
6124 {
drhb00d8622014-01-01 15:18:36 +00006125 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006126 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006127 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006128 time_t t;
6129 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006130 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006131 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6132 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6133 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006134 }else{
drhc18b4042012-02-10 03:10:27 +00006135 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006136 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006137 }
drhbbd42a62004-05-22 17:41:58 +00006138 }
6139#endif
drh72cbd072008-10-14 17:58:38 +00006140 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006141}
6142
danielk1977b4b47412007-08-17 15:53:36 +00006143
drhbbd42a62004-05-22 17:41:58 +00006144/*
6145** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006146** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006147** The return value is the number of microseconds of sleep actually
6148** requested from the underlying operating system, a number which
6149** might be greater than or equal to the argument, but not less
6150** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006151*/
danielk1977397d65f2008-11-19 11:35:39 +00006152static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006153#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006154 struct timespec sp;
6155
6156 sp.tv_sec = microseconds / 1000000;
6157 sp.tv_nsec = (microseconds % 1000000) * 1000;
6158 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006159 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006160 return microseconds;
6161#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006162 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006163 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006164 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006165#else
danielk1977b4b47412007-08-17 15:53:36 +00006166 int seconds = (microseconds+999999)/1000000;
6167 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006168 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006169 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006170#endif
drh88f474a2006-01-02 20:00:12 +00006171}
6172
6173/*
drh6b9d6dd2008-12-03 19:34:47 +00006174** The following variable, if set to a non-zero value, is interpreted as
6175** the number of seconds since 1970 and is used to set the result of
6176** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006177*/
6178#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006179int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006180#endif
6181
6182/*
drhb7e8ea22010-05-03 14:32:30 +00006183** Find the current time (in Universal Coordinated Time). Write into *piNow
6184** the current time and date as a Julian Day number times 86_400_000. In
6185** other words, write into *piNow the number of milliseconds since the Julian
6186** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6187** proleptic Gregorian calendar.
6188**
drh31702252011-10-12 23:13:43 +00006189** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6190** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006191*/
6192static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6193 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006194 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006195#if defined(NO_GETTOD)
6196 time_t t;
6197 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006198 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006199#elif OS_VXWORKS
6200 struct timespec sNow;
6201 clock_gettime(CLOCK_REALTIME, &sNow);
6202 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6203#else
6204 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006205 if( gettimeofday(&sNow, 0)==0 ){
6206 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6207 }else{
6208 rc = SQLITE_ERROR;
6209 }
drhb7e8ea22010-05-03 14:32:30 +00006210#endif
6211
6212#ifdef SQLITE_TEST
6213 if( sqlite3_current_time ){
6214 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6215 }
6216#endif
6217 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006218 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006219}
6220
6221/*
drhbbd42a62004-05-22 17:41:58 +00006222** Find the current time (in Universal Coordinated Time). Write the
6223** current time and date as a Julian Day number into *prNow and
6224** return 0. Return 1 if the time and date cannot be found.
6225*/
danielk1977397d65f2008-11-19 11:35:39 +00006226static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006227 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006228 int rc;
drhff828942010-06-26 21:34:06 +00006229 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006230 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006231 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006232 return rc;
drhbbd42a62004-05-22 17:41:58 +00006233}
danielk1977b4b47412007-08-17 15:53:36 +00006234
drh6b9d6dd2008-12-03 19:34:47 +00006235/*
6236** We added the xGetLastError() method with the intention of providing
6237** better low-level error messages when operating-system problems come up
6238** during SQLite operation. But so far, none of that has been implemented
6239** in the core. So this routine is never called. For now, it is merely
6240** a place-holder.
6241*/
danielk1977397d65f2008-11-19 11:35:39 +00006242static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6243 UNUSED_PARAMETER(NotUsed);
6244 UNUSED_PARAMETER(NotUsed2);
6245 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006246 return 0;
6247}
6248
drhf2424c52010-04-26 00:04:55 +00006249
6250/*
drh734c9862008-11-28 15:37:20 +00006251************************ End of sqlite3_vfs methods ***************************
6252******************************************************************************/
6253
drh715ff302008-12-03 22:32:44 +00006254/******************************************************************************
6255************************** Begin Proxy Locking ********************************
6256**
6257** Proxy locking is a "uber-locking-method" in this sense: It uses the
6258** other locking methods on secondary lock files. Proxy locking is a
6259** meta-layer over top of the primitive locking implemented above. For
6260** this reason, the division that implements of proxy locking is deferred
6261** until late in the file (here) after all of the other I/O methods have
6262** been defined - so that the primitive locking methods are available
6263** as services to help with the implementation of proxy locking.
6264**
6265****
6266**
6267** The default locking schemes in SQLite use byte-range locks on the
6268** database file to coordinate safe, concurrent access by multiple readers
6269** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6270** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6271** as POSIX read & write locks over fixed set of locations (via fsctl),
6272** on AFP and SMB only exclusive byte-range locks are available via fsctl
6273** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6274** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6275** address in the shared range is taken for a SHARED lock, the entire
6276** shared range is taken for an EXCLUSIVE lock):
6277**
drhf2f105d2012-08-20 15:53:54 +00006278** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006279** RESERVED_BYTE 0x40000001
6280** SHARED_RANGE 0x40000002 -> 0x40000200
6281**
6282** This works well on the local file system, but shows a nearly 100x
6283** slowdown in read performance on AFP because the AFP client disables
6284** the read cache when byte-range locks are present. Enabling the read
6285** cache exposes a cache coherency problem that is present on all OS X
6286** supported network file systems. NFS and AFP both observe the
6287** close-to-open semantics for ensuring cache coherency
6288** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6289** address the requirements for concurrent database access by multiple
6290** readers and writers
6291** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6292**
6293** To address the performance and cache coherency issues, proxy file locking
6294** changes the way database access is controlled by limiting access to a
6295** single host at a time and moving file locks off of the database file
6296** and onto a proxy file on the local file system.
6297**
6298**
6299** Using proxy locks
6300** -----------------
6301**
6302** C APIs
6303**
drh4bf66fd2015-02-19 02:43:02 +00006304** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006305** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006306** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6307** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006308**
6309**
6310** SQL pragmas
6311**
6312** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6313** PRAGMA [database.]lock_proxy_file
6314**
6315** Specifying ":auto:" means that if there is a conch file with a matching
6316** host ID in it, the proxy path in the conch file will be used, otherwise
6317** a proxy path based on the user's temp dir
6318** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6319** actual proxy file name is generated from the name and path of the
6320** database file. For example:
6321**
6322** For database path "/Users/me/foo.db"
6323** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6324**
6325** Once a lock proxy is configured for a database connection, it can not
6326** be removed, however it may be switched to a different proxy path via
6327** the above APIs (assuming the conch file is not being held by another
6328** connection or process).
6329**
6330**
6331** How proxy locking works
6332** -----------------------
6333**
6334** Proxy file locking relies primarily on two new supporting files:
6335**
6336** * conch file to limit access to the database file to a single host
6337** at a time
6338**
6339** * proxy file to act as a proxy for the advisory locks normally
6340** taken on the database
6341**
6342** The conch file - to use a proxy file, sqlite must first "hold the conch"
6343** by taking an sqlite-style shared lock on the conch file, reading the
6344** contents and comparing the host's unique host ID (see below) and lock
6345** proxy path against the values stored in the conch. The conch file is
6346** stored in the same directory as the database file and the file name
6347** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006348** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006349** host ID and/or proxy path, then the lock is escalated to an exclusive
6350** lock and the conch file contents is updated with the host ID and proxy
6351** path and the lock is downgraded to a shared lock again. If the conch
6352** is held by another process (with a shared lock), the exclusive lock
6353** will fail and SQLITE_BUSY is returned.
6354**
6355** The proxy file - a single-byte file used for all advisory file locks
6356** normally taken on the database file. This allows for safe sharing
6357** of the database file for multiple readers and writers on the same
6358** host (the conch ensures that they all use the same local lock file).
6359**
drh715ff302008-12-03 22:32:44 +00006360** Requesting the lock proxy does not immediately take the conch, it is
6361** only taken when the first request to lock database file is made.
6362** This matches the semantics of the traditional locking behavior, where
6363** opening a connection to a database file does not take a lock on it.
6364** The shared lock and an open file descriptor are maintained until
6365** the connection to the database is closed.
6366**
6367** The proxy file and the lock file are never deleted so they only need
6368** to be created the first time they are used.
6369**
6370** Configuration options
6371** ---------------------
6372**
6373** SQLITE_PREFER_PROXY_LOCKING
6374**
6375** Database files accessed on non-local file systems are
6376** automatically configured for proxy locking, lock files are
6377** named automatically using the same logic as
6378** PRAGMA lock_proxy_file=":auto:"
6379**
6380** SQLITE_PROXY_DEBUG
6381**
6382** Enables the logging of error messages during host id file
6383** retrieval and creation
6384**
drh715ff302008-12-03 22:32:44 +00006385** LOCKPROXYDIR
6386**
6387** Overrides the default directory used for lock proxy files that
6388** are named automatically via the ":auto:" setting
6389**
6390** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6391**
6392** Permissions to use when creating a directory for storing the
6393** lock proxy files, only used when LOCKPROXYDIR is not set.
6394**
6395**
6396** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6397** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6398** force proxy locking to be used for every database file opened, and 0
6399** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006400** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006401** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6402*/
6403
6404/*
6405** Proxy locking is only available on MacOSX
6406*/
drhd2cb50b2009-01-09 21:41:17 +00006407#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006408
drh715ff302008-12-03 22:32:44 +00006409/*
6410** The proxyLockingContext has the path and file structures for the remote
6411** and local proxy files in it
6412*/
6413typedef struct proxyLockingContext proxyLockingContext;
6414struct proxyLockingContext {
6415 unixFile *conchFile; /* Open conch file */
6416 char *conchFilePath; /* Name of the conch file */
6417 unixFile *lockProxy; /* Open proxy lock file */
6418 char *lockProxyPath; /* Name of the proxy lock file */
6419 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006420 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006421 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006422 void *oldLockingContext; /* Original lockingcontext to restore on close */
6423 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6424};
6425
drh7ed97b92010-01-20 13:07:21 +00006426/*
6427** The proxy lock file path for the database at dbPath is written into lPath,
6428** which must point to valid, writable memory large enough for a maxLen length
6429** file path.
drh715ff302008-12-03 22:32:44 +00006430*/
drh715ff302008-12-03 22:32:44 +00006431static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6432 int len;
6433 int dbLen;
6434 int i;
6435
6436#ifdef LOCKPROXYDIR
6437 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6438#else
6439# ifdef _CS_DARWIN_USER_TEMP_DIR
6440 {
drh7ed97b92010-01-20 13:07:21 +00006441 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006442 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh91eb93c2015-03-03 19:56:20 +00006443 lPath, errno, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006444 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006445 }
drh7ed97b92010-01-20 13:07:21 +00006446 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006447 }
6448# else
6449 len = strlcpy(lPath, "/tmp/", maxLen);
6450# endif
6451#endif
6452
6453 if( lPath[len-1]!='/' ){
6454 len = strlcat(lPath, "/", maxLen);
6455 }
6456
6457 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006458 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006459 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006460 char c = dbPath[i];
6461 lPath[i+len] = (c=='/')?'_':c;
6462 }
6463 lPath[i+len]='\0';
6464 strlcat(lPath, ":auto:", maxLen);
drh91eb93c2015-03-03 19:56:20 +00006465 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid()));
drh715ff302008-12-03 22:32:44 +00006466 return SQLITE_OK;
6467}
6468
drh7ed97b92010-01-20 13:07:21 +00006469/*
6470 ** Creates the lock file and any missing directories in lockPath
6471 */
6472static int proxyCreateLockPath(const char *lockPath){
6473 int i, len;
6474 char buf[MAXPATHLEN];
6475 int start = 0;
6476
6477 assert(lockPath!=NULL);
6478 /* try to create all the intermediate directories */
6479 len = (int)strlen(lockPath);
6480 buf[0] = lockPath[0];
6481 for( i=1; i<len; i++ ){
6482 if( lockPath[i] == '/' && (i - start > 0) ){
6483 /* only mkdir if leaf dir != "." or "/" or ".." */
6484 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6485 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6486 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006487 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006488 int err=errno;
6489 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006490 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006491 "'%s' proxy lock path=%s pid=%d\n",
drh91eb93c2015-03-03 19:56:20 +00006492 buf, strerror(err), lockPath, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006493 return err;
6494 }
6495 }
6496 }
6497 start=i+1;
6498 }
6499 buf[i] = lockPath[i];
6500 }
drh91eb93c2015-03-03 19:56:20 +00006501 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00006502 return 0;
6503}
6504
drh715ff302008-12-03 22:32:44 +00006505/*
6506** Create a new VFS file descriptor (stored in memory obtained from
6507** sqlite3_malloc) and open the file named "path" in the file descriptor.
6508**
6509** The caller is responsible not only for closing the file descriptor
6510** but also for freeing the memory associated with the file descriptor.
6511*/
drh7ed97b92010-01-20 13:07:21 +00006512static int proxyCreateUnixFile(
6513 const char *path, /* path for the new unixFile */
6514 unixFile **ppFile, /* unixFile created and returned by ref */
6515 int islockfile /* if non zero missing dirs will be created */
6516) {
6517 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006518 unixFile *pNew;
6519 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006520 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006521 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006522 int terrno = 0;
6523 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006524
drh7ed97b92010-01-20 13:07:21 +00006525 /* 1. first try to open/create the file
6526 ** 2. if that fails, and this is a lock file (not-conch), try creating
6527 ** the parent directories and then try again.
6528 ** 3. if that fails, try to open the file read-only
6529 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6530 */
6531 pUnused = findReusableFd(path, openFlags);
6532 if( pUnused ){
6533 fd = pUnused->fd;
6534 }else{
6535 pUnused = sqlite3_malloc(sizeof(*pUnused));
6536 if( !pUnused ){
6537 return SQLITE_NOMEM;
6538 }
6539 }
6540 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006541 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006542 terrno = errno;
6543 if( fd<0 && errno==ENOENT && islockfile ){
6544 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006545 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006546 }
6547 }
6548 }
6549 if( fd<0 ){
6550 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006551 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006552 terrno = errno;
6553 }
6554 if( fd<0 ){
6555 if( islockfile ){
6556 return SQLITE_BUSY;
6557 }
6558 switch (terrno) {
6559 case EACCES:
6560 return SQLITE_PERM;
6561 case EIO:
6562 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6563 default:
drh9978c972010-02-23 17:36:32 +00006564 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006565 }
6566 }
6567
6568 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6569 if( pNew==NULL ){
6570 rc = SQLITE_NOMEM;
6571 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006572 }
6573 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006574 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006575 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006576 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006577 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006578 pUnused->fd = fd;
6579 pUnused->flags = openFlags;
6580 pNew->pUnused = pUnused;
6581
drhc02a43a2012-01-10 23:18:38 +00006582 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006583 if( rc==SQLITE_OK ){
6584 *ppFile = pNew;
6585 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006586 }
drh7ed97b92010-01-20 13:07:21 +00006587end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006588 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006589 sqlite3_free(pNew);
6590 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006591 return rc;
6592}
6593
drh7ed97b92010-01-20 13:07:21 +00006594#ifdef SQLITE_TEST
6595/* simulate multiple hosts by creating unique hostid file paths */
6596int sqlite3_hostid_num = 0;
6597#endif
6598
6599#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6600
drh0ab216a2010-07-02 17:10:40 +00006601/* Not always defined in the headers as it ought to be */
6602extern int gethostuuid(uuid_t id, const struct timespec *wait);
6603
drh7ed97b92010-01-20 13:07:21 +00006604/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6605** bytes of writable memory.
6606*/
6607static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006608 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6609 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh4bf66fd2015-02-19 02:43:02 +00006610# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
6611 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
drh29ecd8a2010-12-21 00:16:40 +00006612 {
drh4bf66fd2015-02-19 02:43:02 +00006613 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006614 if( gethostuuid(pHostID, &timeout) ){
6615 int err = errno;
6616 if( pError ){
6617 *pError = err;
6618 }
6619 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006620 }
drh7ed97b92010-01-20 13:07:21 +00006621 }
drh3d4435b2011-08-26 20:55:50 +00006622#else
6623 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006624#endif
drh7ed97b92010-01-20 13:07:21 +00006625#ifdef SQLITE_TEST
6626 /* simulate multiple hosts by creating unique hostid file paths */
6627 if( sqlite3_hostid_num != 0){
6628 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6629 }
6630#endif
6631
6632 return SQLITE_OK;
6633}
6634
6635/* The conch file contains the header, host id and lock file path
6636 */
6637#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6638#define PROXY_HEADERLEN 1 /* conch file header length */
6639#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6640#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6641
6642/*
6643** Takes an open conch file, copies the contents to a new path and then moves
6644** it back. The newly created file's file descriptor is assigned to the
6645** conch file structure and finally the original conch file descriptor is
6646** closed. Returns zero if successful.
6647*/
6648static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6649 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6650 unixFile *conchFile = pCtx->conchFile;
6651 char tPath[MAXPATHLEN];
6652 char buf[PROXY_MAXCONCHLEN];
6653 char *cPath = pCtx->conchFilePath;
6654 size_t readLen = 0;
6655 size_t pathLen = 0;
6656 char errmsg[64] = "";
6657 int fd = -1;
6658 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006659 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006660
6661 /* create a new path by replace the trailing '-conch' with '-break' */
6662 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6663 if( pathLen>MAXPATHLEN || pathLen<6 ||
6664 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006665 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006666 goto end_breaklock;
6667 }
6668 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006669 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006670 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006671 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006672 goto end_breaklock;
6673 }
6674 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006675 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006676 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006677 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006678 goto end_breaklock;
6679 }
drhe562be52011-03-02 18:01:10 +00006680 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006681 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006682 goto end_breaklock;
6683 }
6684 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006685 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006686 goto end_breaklock;
6687 }
6688 rc = 0;
6689 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006690 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006691 conchFile->h = fd;
6692 conchFile->openFlags = O_RDWR | O_CREAT;
6693
6694end_breaklock:
6695 if( rc ){
6696 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006697 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006698 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006699 }
6700 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6701 }
6702 return rc;
6703}
6704
6705/* Take the requested lock on the conch file and break a stale lock if the
6706** host id matches.
6707*/
6708static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6709 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6710 unixFile *conchFile = pCtx->conchFile;
6711 int rc = SQLITE_OK;
6712 int nTries = 0;
6713 struct timespec conchModTime;
6714
drh3d4435b2011-08-26 20:55:50 +00006715 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006716 do {
6717 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6718 nTries ++;
6719 if( rc==SQLITE_BUSY ){
6720 /* If the lock failed (busy):
6721 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6722 * 2nd try: fail if the mod time changed or host id is different, wait
6723 * 10 sec and try again
6724 * 3rd try: break the lock unless the mod time has changed.
6725 */
6726 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006727 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006728 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006729 return SQLITE_IOERR_LOCK;
6730 }
6731
6732 if( nTries==1 ){
6733 conchModTime = buf.st_mtimespec;
6734 usleep(500000); /* wait 0.5 sec and try the lock again*/
6735 continue;
6736 }
6737
6738 assert( nTries>1 );
6739 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6740 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6741 return SQLITE_BUSY;
6742 }
6743
6744 if( nTries==2 ){
6745 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006746 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006747 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006748 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006749 return SQLITE_IOERR_LOCK;
6750 }
6751 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6752 /* don't break the lock if the host id doesn't match */
6753 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6754 return SQLITE_BUSY;
6755 }
6756 }else{
6757 /* don't break the lock on short read or a version mismatch */
6758 return SQLITE_BUSY;
6759 }
6760 usleep(10000000); /* wait 10 sec and try the lock again */
6761 continue;
6762 }
6763
6764 assert( nTries==3 );
6765 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6766 rc = SQLITE_OK;
6767 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006768 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006769 }
6770 if( !rc ){
6771 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6772 }
6773 }
6774 }
6775 } while( rc==SQLITE_BUSY && nTries<3 );
6776
6777 return rc;
6778}
6779
6780/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006781** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6782** lockPath means that the lockPath in the conch file will be used if the
6783** host IDs match, or a new lock path will be generated automatically
6784** and written to the conch file.
6785*/
6786static int proxyTakeConch(unixFile *pFile){
6787 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6788
drh7ed97b92010-01-20 13:07:21 +00006789 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006790 return SQLITE_OK;
6791 }else{
6792 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006793 uuid_t myHostID;
6794 int pError = 0;
6795 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006796 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006797 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006798 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006799 int createConch = 0;
6800 int hostIdMatch = 0;
6801 int readLen = 0;
6802 int tryOldLockPath = 0;
6803 int forceNewLockPath = 0;
6804
drh308c2a52010-05-14 11:30:18 +00006805 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006806 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
6807 osGetpid()));
drh715ff302008-12-03 22:32:44 +00006808
drh7ed97b92010-01-20 13:07:21 +00006809 rc = proxyGetHostID(myHostID, &pError);
6810 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006811 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006812 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006813 }
drh7ed97b92010-01-20 13:07:21 +00006814 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006815 if( rc!=SQLITE_OK ){
6816 goto end_takeconch;
6817 }
drh7ed97b92010-01-20 13:07:21 +00006818 /* read the existing conch file */
6819 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6820 if( readLen<0 ){
6821 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006822 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006823 rc = SQLITE_IOERR_READ;
6824 goto end_takeconch;
6825 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6826 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6827 /* a short read or version format mismatch means we need to create a new
6828 ** conch file.
6829 */
6830 createConch = 1;
6831 }
6832 /* if the host id matches and the lock path already exists in the conch
6833 ** we'll try to use the path there, if we can't open that path, we'll
6834 ** retry with a new auto-generated path
6835 */
6836 do { /* in case we need to try again for an :auto: named lock file */
6837
6838 if( !createConch && !forceNewLockPath ){
6839 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6840 PROXY_HOSTIDLEN);
6841 /* if the conch has data compare the contents */
6842 if( !pCtx->lockProxyPath ){
6843 /* for auto-named local lock file, just check the host ID and we'll
6844 ** use the local lock file path that's already in there
6845 */
6846 if( hostIdMatch ){
6847 size_t pathLen = (readLen - PROXY_PATHINDEX);
6848
6849 if( pathLen>=MAXPATHLEN ){
6850 pathLen=MAXPATHLEN-1;
6851 }
6852 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6853 lockPath[pathLen] = 0;
6854 tempLockPath = lockPath;
6855 tryOldLockPath = 1;
6856 /* create a copy of the lock path if the conch is taken */
6857 goto end_takeconch;
6858 }
6859 }else if( hostIdMatch
6860 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6861 readLen-PROXY_PATHINDEX)
6862 ){
6863 /* conch host and lock path match */
6864 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006865 }
drh7ed97b92010-01-20 13:07:21 +00006866 }
6867
6868 /* if the conch isn't writable and doesn't match, we can't take it */
6869 if( (conchFile->openFlags&O_RDWR) == 0 ){
6870 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006871 goto end_takeconch;
6872 }
drh7ed97b92010-01-20 13:07:21 +00006873
6874 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006875 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006876 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6877 tempLockPath = lockPath;
6878 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006879 }
drh7ed97b92010-01-20 13:07:21 +00006880
6881 /* update conch with host and path (this will fail if other process
6882 ** has a shared lock already), if the host id matches, use the big
6883 ** stick.
drh715ff302008-12-03 22:32:44 +00006884 */
drh7ed97b92010-01-20 13:07:21 +00006885 futimes(conchFile->h, NULL);
6886 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006887 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006888 /* We are trying for an exclusive lock but another thread in this
6889 ** same process is still holding a shared lock. */
6890 rc = SQLITE_BUSY;
6891 } else {
6892 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006893 }
drh715ff302008-12-03 22:32:44 +00006894 }else{
drh4bf66fd2015-02-19 02:43:02 +00006895 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006896 }
drh7ed97b92010-01-20 13:07:21 +00006897 if( rc==SQLITE_OK ){
6898 char writeBuffer[PROXY_MAXCONCHLEN];
6899 int writeSize = 0;
6900
6901 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6902 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6903 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006904 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6905 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006906 }else{
6907 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6908 }
6909 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006910 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006911 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6912 fsync(conchFile->h);
6913 /* If we created a new conch file (not just updated the contents of a
6914 ** valid conch file), try to match the permissions of the database
6915 */
6916 if( rc==SQLITE_OK && createConch ){
6917 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006918 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006919 if( err==0 ){
6920 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6921 S_IROTH|S_IWOTH);
6922 /* try to match the database file R/W permissions, ignore failure */
6923#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006924 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006925#else
drhff812312011-02-23 13:33:46 +00006926 do{
drhe562be52011-03-02 18:01:10 +00006927 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006928 }while( rc==(-1) && errno==EINTR );
6929 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006930 int code = errno;
6931 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6932 cmode, code, strerror(code));
6933 } else {
6934 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6935 }
6936 }else{
6937 int code = errno;
6938 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6939 err, code, strerror(code));
6940#endif
6941 }
drh715ff302008-12-03 22:32:44 +00006942 }
6943 }
drh7ed97b92010-01-20 13:07:21 +00006944 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6945
6946 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006947 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006948 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006949 int fd;
drh7ed97b92010-01-20 13:07:21 +00006950 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006951 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006952 }
6953 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006954 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006955 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006956 if( fd>=0 ){
6957 pFile->h = fd;
6958 }else{
drh9978c972010-02-23 17:36:32 +00006959 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006960 during locking */
6961 }
6962 }
6963 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6964 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6965 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6966 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6967 /* we couldn't create the proxy lock file with the old lock file path
6968 ** so try again via auto-naming
6969 */
6970 forceNewLockPath = 1;
6971 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006972 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006973 }
6974 }
6975 if( rc==SQLITE_OK ){
6976 /* Need to make a copy of path if we extracted the value
6977 ** from the conch file or the path was allocated on the stack
6978 */
6979 if( tempLockPath ){
6980 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6981 if( !pCtx->lockProxyPath ){
6982 rc = SQLITE_NOMEM;
6983 }
6984 }
6985 }
6986 if( rc==SQLITE_OK ){
6987 pCtx->conchHeld = 1;
6988
6989 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
6990 afpLockingContext *afpCtx;
6991 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
6992 afpCtx->dbPath = pCtx->lockProxyPath;
6993 }
6994 } else {
6995 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
6996 }
drh308c2a52010-05-14 11:30:18 +00006997 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
6998 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00006999 return rc;
drh308c2a52010-05-14 11:30:18 +00007000 } while (1); /* in case we need to retry the :auto: lock file -
7001 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007002 }
7003}
7004
7005/*
7006** If pFile holds a lock on a conch file, then release that lock.
7007*/
7008static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007009 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007010 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7011 unixFile *conchFile; /* Name of the conch file */
7012
7013 pCtx = (proxyLockingContext *)pFile->lockingContext;
7014 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007015 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007016 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh91eb93c2015-03-03 19:56:20 +00007017 osGetpid()));
drh7ed97b92010-01-20 13:07:21 +00007018 if( pCtx->conchHeld>0 ){
7019 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7020 }
drh715ff302008-12-03 22:32:44 +00007021 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007022 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7023 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007024 return rc;
7025}
7026
7027/*
7028** Given the name of a database file, compute the name of its conch file.
7029** Store the conch filename in memory obtained from sqlite3_malloc().
7030** Make *pConchPath point to the new name. Return SQLITE_OK on success
7031** or SQLITE_NOMEM if unable to obtain memory.
7032**
7033** The caller is responsible for ensuring that the allocated memory
7034** space is eventually freed.
7035**
7036** *pConchPath is set to NULL if a memory allocation error occurs.
7037*/
7038static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7039 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007040 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007041 char *conchPath; /* buffer in which to construct conch name */
7042
7043 /* Allocate space for the conch filename and initialize the name to
7044 ** the name of the original database file. */
7045 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7046 if( conchPath==0 ){
7047 return SQLITE_NOMEM;
7048 }
7049 memcpy(conchPath, dbPath, len+1);
7050
7051 /* now insert a "." before the last / character */
7052 for( i=(len-1); i>=0; i-- ){
7053 if( conchPath[i]=='/' ){
7054 i++;
7055 break;
7056 }
7057 }
7058 conchPath[i]='.';
7059 while ( i<len ){
7060 conchPath[i+1]=dbPath[i];
7061 i++;
7062 }
7063
7064 /* append the "-conch" suffix to the file */
7065 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007066 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007067
7068 return SQLITE_OK;
7069}
7070
7071
7072/* Takes a fully configured proxy locking-style unix file and switches
7073** the local lock file path
7074*/
7075static int switchLockProxyPath(unixFile *pFile, const char *path) {
7076 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7077 char *oldPath = pCtx->lockProxyPath;
7078 int rc = SQLITE_OK;
7079
drh308c2a52010-05-14 11:30:18 +00007080 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007081 return SQLITE_BUSY;
7082 }
7083
7084 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7085 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7086 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7087 return SQLITE_OK;
7088 }else{
7089 unixFile *lockProxy = pCtx->lockProxy;
7090 pCtx->lockProxy=NULL;
7091 pCtx->conchHeld = 0;
7092 if( lockProxy!=NULL ){
7093 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7094 if( rc ) return rc;
7095 sqlite3_free(lockProxy);
7096 }
7097 sqlite3_free(oldPath);
7098 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7099 }
7100
7101 return rc;
7102}
7103
7104/*
7105** pFile is a file that has been opened by a prior xOpen call. dbPath
7106** is a string buffer at least MAXPATHLEN+1 characters in size.
7107**
7108** This routine find the filename associated with pFile and writes it
7109** int dbPath.
7110*/
7111static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007112#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007113 if( pFile->pMethod == &afpIoMethods ){
7114 /* afp style keeps a reference to the db path in the filePath field
7115 ** of the struct */
drhea678832008-12-10 19:26:22 +00007116 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007117 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7118 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007119 } else
drh715ff302008-12-03 22:32:44 +00007120#endif
7121 if( pFile->pMethod == &dotlockIoMethods ){
7122 /* dot lock style uses the locking context to store the dot lock
7123 ** file path */
7124 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7125 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7126 }else{
7127 /* all other styles use the locking context to store the db file path */
7128 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007129 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007130 }
7131 return SQLITE_OK;
7132}
7133
7134/*
7135** Takes an already filled in unix file and alters it so all file locking
7136** will be performed on the local proxy lock file. The following fields
7137** are preserved in the locking context so that they can be restored and
7138** the unix structure properly cleaned up at close time:
7139** ->lockingContext
7140** ->pMethod
7141*/
7142static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7143 proxyLockingContext *pCtx;
7144 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7145 char *lockPath=NULL;
7146 int rc = SQLITE_OK;
7147
drh308c2a52010-05-14 11:30:18 +00007148 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007149 return SQLITE_BUSY;
7150 }
7151 proxyGetDbPathForUnixFile(pFile, dbPath);
7152 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7153 lockPath=NULL;
7154 }else{
7155 lockPath=(char *)path;
7156 }
7157
drh308c2a52010-05-14 11:30:18 +00007158 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh91eb93c2015-03-03 19:56:20 +00007159 (lockPath ? lockPath : ":auto:"), osGetpid()));
drh715ff302008-12-03 22:32:44 +00007160
7161 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7162 if( pCtx==0 ){
7163 return SQLITE_NOMEM;
7164 }
7165 memset(pCtx, 0, sizeof(*pCtx));
7166
7167 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7168 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007169 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7170 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7171 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7172 ** (c) the file system is read-only, then enable no-locking access.
7173 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7174 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7175 */
7176 struct statfs fsInfo;
7177 struct stat conchInfo;
7178 int goLockless = 0;
7179
drh99ab3b12011-03-02 15:09:07 +00007180 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007181 int err = errno;
7182 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7183 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7184 }
7185 }
7186 if( goLockless ){
7187 pCtx->conchHeld = -1; /* read only FS/ lockless */
7188 rc = SQLITE_OK;
7189 }
7190 }
drh715ff302008-12-03 22:32:44 +00007191 }
7192 if( rc==SQLITE_OK && lockPath ){
7193 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7194 }
7195
7196 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007197 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7198 if( pCtx->dbPath==NULL ){
7199 rc = SQLITE_NOMEM;
7200 }
7201 }
7202 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007203 /* all memory is allocated, proxys are created and assigned,
7204 ** switch the locking context and pMethod then return.
7205 */
drh715ff302008-12-03 22:32:44 +00007206 pCtx->oldLockingContext = pFile->lockingContext;
7207 pFile->lockingContext = pCtx;
7208 pCtx->pOldMethod = pFile->pMethod;
7209 pFile->pMethod = &proxyIoMethods;
7210 }else{
7211 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007212 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007213 sqlite3_free(pCtx->conchFile);
7214 }
drhd56b1212010-08-11 06:14:15 +00007215 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007216 sqlite3_free(pCtx->conchFilePath);
7217 sqlite3_free(pCtx);
7218 }
drh308c2a52010-05-14 11:30:18 +00007219 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7220 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007221 return rc;
7222}
7223
7224
7225/*
7226** This routine handles sqlite3_file_control() calls that are specific
7227** to proxy locking.
7228*/
7229static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7230 switch( op ){
drhbbf76ee2015-03-10 20:22:35 +00007231 case SQLITE_FCNTL_WAL_BLOCK: {
7232 id->ctrlFlags |= UNIXFILE_BLOCK;
7233 return SQLITE_OK;
7234 }
drh4bf66fd2015-02-19 02:43:02 +00007235 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007236 unixFile *pFile = (unixFile*)id;
7237 if( pFile->pMethod == &proxyIoMethods ){
7238 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7239 proxyTakeConch(pFile);
7240 if( pCtx->lockProxyPath ){
7241 *(const char **)pArg = pCtx->lockProxyPath;
7242 }else{
7243 *(const char **)pArg = ":auto: (not held)";
7244 }
7245 } else {
7246 *(const char **)pArg = NULL;
7247 }
7248 return SQLITE_OK;
7249 }
drh4bf66fd2015-02-19 02:43:02 +00007250 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007251 unixFile *pFile = (unixFile*)id;
7252 int rc = SQLITE_OK;
7253 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7254 if( pArg==NULL || (const char *)pArg==0 ){
7255 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007256 /* turn off proxy locking - not supported. If support is added for
7257 ** switching proxy locking mode off then it will need to fail if
7258 ** the journal mode is WAL mode.
7259 */
drh715ff302008-12-03 22:32:44 +00007260 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7261 }else{
7262 /* turn off proxy locking - already off - NOOP */
7263 rc = SQLITE_OK;
7264 }
7265 }else{
7266 const char *proxyPath = (const char *)pArg;
7267 if( isProxyStyle ){
7268 proxyLockingContext *pCtx =
7269 (proxyLockingContext*)pFile->lockingContext;
7270 if( !strcmp(pArg, ":auto:")
7271 || (pCtx->lockProxyPath &&
7272 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7273 ){
7274 rc = SQLITE_OK;
7275 }else{
7276 rc = switchLockProxyPath(pFile, proxyPath);
7277 }
7278 }else{
7279 /* turn on proxy file locking */
7280 rc = proxyTransformUnixFile(pFile, proxyPath);
7281 }
7282 }
7283 return rc;
7284 }
7285 default: {
7286 assert( 0 ); /* The call assures that only valid opcodes are sent */
7287 }
7288 }
7289 /*NOTREACHED*/
7290 return SQLITE_ERROR;
7291}
7292
7293/*
7294** Within this division (the proxying locking implementation) the procedures
7295** above this point are all utilities. The lock-related methods of the
7296** proxy-locking sqlite3_io_method object follow.
7297*/
7298
7299
7300/*
7301** This routine checks if there is a RESERVED lock held on the specified
7302** file by this or any other process. If such a lock is held, set *pResOut
7303** to a non-zero value otherwise *pResOut is set to zero. The return value
7304** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7305*/
7306static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7307 unixFile *pFile = (unixFile*)id;
7308 int rc = proxyTakeConch(pFile);
7309 if( rc==SQLITE_OK ){
7310 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007311 if( pCtx->conchHeld>0 ){
7312 unixFile *proxy = pCtx->lockProxy;
7313 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7314 }else{ /* conchHeld < 0 is lockless */
7315 pResOut=0;
7316 }
drh715ff302008-12-03 22:32:44 +00007317 }
7318 return rc;
7319}
7320
7321/*
drh308c2a52010-05-14 11:30:18 +00007322** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007323** of the following:
7324**
7325** (1) SHARED_LOCK
7326** (2) RESERVED_LOCK
7327** (3) PENDING_LOCK
7328** (4) EXCLUSIVE_LOCK
7329**
7330** Sometimes when requesting one lock state, additional lock states
7331** are inserted in between. The locking might fail on one of the later
7332** transitions leaving the lock state different from what it started but
7333** still short of its goal. The following chart shows the allowed
7334** transitions and the inserted intermediate states:
7335**
7336** UNLOCKED -> SHARED
7337** SHARED -> RESERVED
7338** SHARED -> (PENDING) -> EXCLUSIVE
7339** RESERVED -> (PENDING) -> EXCLUSIVE
7340** PENDING -> EXCLUSIVE
7341**
7342** This routine will only increase a lock. Use the sqlite3OsUnlock()
7343** routine to lower a locking level.
7344*/
drh308c2a52010-05-14 11:30:18 +00007345static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007346 unixFile *pFile = (unixFile*)id;
7347 int rc = proxyTakeConch(pFile);
7348 if( rc==SQLITE_OK ){
7349 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007350 if( pCtx->conchHeld>0 ){
7351 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007352 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7353 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007354 }else{
7355 /* conchHeld < 0 is lockless */
7356 }
drh715ff302008-12-03 22:32:44 +00007357 }
7358 return rc;
7359}
7360
7361
7362/*
drh308c2a52010-05-14 11:30:18 +00007363** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007364** must be either NO_LOCK or SHARED_LOCK.
7365**
7366** If the locking level of the file descriptor is already at or below
7367** the requested locking level, this routine is a no-op.
7368*/
drh308c2a52010-05-14 11:30:18 +00007369static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007370 unixFile *pFile = (unixFile*)id;
7371 int rc = proxyTakeConch(pFile);
7372 if( rc==SQLITE_OK ){
7373 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007374 if( pCtx->conchHeld>0 ){
7375 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007376 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7377 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007378 }else{
7379 /* conchHeld < 0 is lockless */
7380 }
drh715ff302008-12-03 22:32:44 +00007381 }
7382 return rc;
7383}
7384
7385/*
7386** Close a file that uses proxy locks.
7387*/
7388static int proxyClose(sqlite3_file *id) {
7389 if( id ){
7390 unixFile *pFile = (unixFile*)id;
7391 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7392 unixFile *lockProxy = pCtx->lockProxy;
7393 unixFile *conchFile = pCtx->conchFile;
7394 int rc = SQLITE_OK;
7395
7396 if( lockProxy ){
7397 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7398 if( rc ) return rc;
7399 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7400 if( rc ) return rc;
7401 sqlite3_free(lockProxy);
7402 pCtx->lockProxy = 0;
7403 }
7404 if( conchFile ){
7405 if( pCtx->conchHeld ){
7406 rc = proxyReleaseConch(pFile);
7407 if( rc ) return rc;
7408 }
7409 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7410 if( rc ) return rc;
7411 sqlite3_free(conchFile);
7412 }
drhd56b1212010-08-11 06:14:15 +00007413 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007414 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007415 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007416 /* restore the original locking context and pMethod then close it */
7417 pFile->lockingContext = pCtx->oldLockingContext;
7418 pFile->pMethod = pCtx->pOldMethod;
7419 sqlite3_free(pCtx);
7420 return pFile->pMethod->xClose(id);
7421 }
7422 return SQLITE_OK;
7423}
7424
7425
7426
drhd2cb50b2009-01-09 21:41:17 +00007427#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007428/*
7429** The proxy locking style is intended for use with AFP filesystems.
7430** And since AFP is only supported on MacOSX, the proxy locking is also
7431** restricted to MacOSX.
7432**
7433**
7434******************* End of the proxy lock implementation **********************
7435******************************************************************************/
7436
drh734c9862008-11-28 15:37:20 +00007437/*
danielk1977e339d652008-06-28 11:23:00 +00007438** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007439**
7440** This routine registers all VFS implementations for unix-like operating
7441** systems. This routine, and the sqlite3_os_end() routine that follows,
7442** should be the only routines in this file that are visible from other
7443** files.
drh6b9d6dd2008-12-03 19:34:47 +00007444**
7445** This routine is called once during SQLite initialization and by a
7446** single thread. The memory allocation and mutex subsystems have not
7447** necessarily been initialized when this routine is called, and so they
7448** should not be used.
drh153c62c2007-08-24 03:51:33 +00007449*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007450int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007451 /*
7452 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007453 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7454 ** to the "finder" function. (pAppData is a pointer to a pointer because
7455 ** silly C90 rules prohibit a void* from being cast to a function pointer
7456 ** and so we have to go through the intermediate pointer to avoid problems
7457 ** when compiling with -pedantic-errors on GCC.)
7458 **
7459 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007460 ** finder-function. The finder-function returns a pointer to the
7461 ** sqlite_io_methods object that implements the desired locking
7462 ** behaviors. See the division above that contains the IOMETHODS
7463 ** macro for addition information on finder-functions.
7464 **
7465 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7466 ** object. But the "autolockIoFinder" available on MacOSX does a little
7467 ** more than that; it looks at the filesystem type that hosts the
7468 ** database file and tries to choose an locking method appropriate for
7469 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007470 */
drh7708e972008-11-29 00:56:52 +00007471 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007472 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007473 sizeof(unixFile), /* szOsFile */ \
7474 MAX_PATHNAME, /* mxPathname */ \
7475 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007476 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007477 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007478 unixOpen, /* xOpen */ \
7479 unixDelete, /* xDelete */ \
7480 unixAccess, /* xAccess */ \
7481 unixFullPathname, /* xFullPathname */ \
7482 unixDlOpen, /* xDlOpen */ \
7483 unixDlError, /* xDlError */ \
7484 unixDlSym, /* xDlSym */ \
7485 unixDlClose, /* xDlClose */ \
7486 unixRandomness, /* xRandomness */ \
7487 unixSleep, /* xSleep */ \
7488 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007489 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007490 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007491 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007492 unixGetSystemCall, /* xGetSystemCall */ \
7493 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007494 }
7495
drh6b9d6dd2008-12-03 19:34:47 +00007496 /*
7497 ** All default VFSes for unix are contained in the following array.
7498 **
7499 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7500 ** by the SQLite core when the VFS is registered. So the following
7501 ** array cannot be const.
7502 */
danielk1977e339d652008-06-28 11:23:00 +00007503 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007504#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007505 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007506#elif OS_VXWORKS
7507 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007508#else
7509 UNIXVFS("unix", posixIoFinder ),
7510#endif
7511 UNIXVFS("unix-none", nolockIoFinder ),
7512 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007513 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007514#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007515 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007516#endif
drhe89b2912015-03-03 20:42:01 +00007517#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007518 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007519#endif
drhe89b2912015-03-03 20:42:01 +00007520#if SQLITE_ENABLE_LOCKING_STYLE
7521 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007522#endif
drhd2cb50b2009-01-09 21:41:17 +00007523#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007524 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007525 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007526 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007527#endif
drh153c62c2007-08-24 03:51:33 +00007528 };
drh6b9d6dd2008-12-03 19:34:47 +00007529 unsigned int i; /* Loop counter */
7530
drh2aa5a002011-04-13 13:42:25 +00007531 /* Double-check that the aSyscall[] array has been constructed
7532 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007533 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007534
drh6b9d6dd2008-12-03 19:34:47 +00007535 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007536 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007537 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007538 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007539 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007540}
danielk1977e339d652008-06-28 11:23:00 +00007541
7542/*
drh6b9d6dd2008-12-03 19:34:47 +00007543** Shutdown the operating system interface.
7544**
7545** Some operating systems might need to do some cleanup in this routine,
7546** to release dynamically allocated objects. But not on unix.
7547** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007548*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007549int sqlite3_os_end(void){
7550 return SQLITE_OK;
7551}
drhdce8bdb2007-08-16 13:01:44 +00007552
danielk197729bafea2008-06-26 10:41:19 +00007553#endif /* SQLITE_OS_UNIX */