blob: 4594e2d870415da16caecdbc6d7cb973dac34891 [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
drh6bca6512015-04-13 23:05:28 +000094#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
95 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
96# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
97 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
98# define HAVE_GETHOSTUUID 1
99# else
100# warning "gethostuuid() is disabled."
101# endif
102#endif
103
104
drhe89b2912015-03-03 20:42:01 +0000105#if OS_VXWORKS
106# include <sys/ioctl.h>
107# include <semaphore.h>
108# include <limits.h>
109#endif /* OS_VXWORKS */
110
111#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000112# include <sys/mount.h>
113#endif
114
drhdbe4b882011-06-20 18:00:17 +0000115#ifdef HAVE_UTIME
116# include <utime.h>
117#endif
118
drh9cbe6352005-11-29 03:13:21 +0000119/*
drh7ed97b92010-01-20 13:07:21 +0000120** Allowed values of unixFile.fsFlags
121*/
122#define SQLITE_FSFLAGS_IS_MSDOS 0x1
123
124/*
drhf1a221e2006-01-15 17:27:17 +0000125** If we are to be thread-safe, include the pthreads header and define
126** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000127*/
drhd677b3d2007-08-20 22:48:41 +0000128#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000129# include <pthread.h>
130# define SQLITE_UNIX_THREADS 1
131#endif
132
133/*
134** Default permissions when creating a new file
135*/
136#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
137# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
138#endif
139
danielk1977b4b47412007-08-17 15:53:36 +0000140/*
drh5adc60b2012-04-14 13:25:11 +0000141** Default permissions when creating auto proxy dir
142*/
aswiftaebf4132008-11-21 00:10:35 +0000143#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
144# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
145#endif
146
147/*
danielk1977b4b47412007-08-17 15:53:36 +0000148** Maximum supported path-length.
149*/
150#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000151
drh91eb93c2015-03-03 19:56:20 +0000152/* Always cast the getpid() return type for compatibility with
153** kernel modules in VxWorks. */
154#define osGetpid(X) (pid_t)getpid()
155
drh734c9862008-11-28 15:37:20 +0000156/*
drh734c9862008-11-28 15:37:20 +0000157** Only set the lastErrno if the error code is a real error and not
158** a normal expected return code of SQLITE_BUSY or SQLITE_OK
159*/
160#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
161
drhd91c68f2010-05-14 14:52:25 +0000162/* Forward references */
163typedef struct unixShm unixShm; /* Connection shared memory */
164typedef struct unixShmNode unixShmNode; /* Shared memory instance */
165typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
166typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000167
168/*
dane946c392009-08-22 11:39:46 +0000169** Sometimes, after a file handle is closed by SQLite, the file descriptor
170** cannot be closed immediately. In these cases, instances of the following
171** structure are used to store the file descriptor while waiting for an
172** opportunity to either close or reuse it.
173*/
dane946c392009-08-22 11:39:46 +0000174struct UnixUnusedFd {
175 int fd; /* File descriptor to close */
176 int flags; /* Flags this file descriptor was opened with */
177 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
178};
179
180/*
drh9b35ea62008-11-29 02:20:26 +0000181** The unixFile structure is subclass of sqlite3_file specific to the unix
182** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000183*/
drh054889e2005-11-30 03:20:31 +0000184typedef struct unixFile unixFile;
185struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000186 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000187 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000188 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000189 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000190 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000191 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000192 int lastErrno; /* The unix errno from last I/O error */
193 void *lockingContext; /* Locking style specific state */
194 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000195 const char *zPath; /* Name of the file */
196 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000197 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000198#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000199 int nFetchOut; /* Number of outstanding xFetch refs */
200 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000201 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
202 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000203 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000204#endif
drh537dddf2012-10-26 13:46:24 +0000205#ifdef __QNXNTO__
206 int sectorSize; /* Device sector size */
207 int deviceCharacteristics; /* Precomputed device characteristics */
208#endif
drh08c6d442009-02-09 17:34:07 +0000209#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000210 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000211#endif
drh7ed97b92010-01-20 13:07:21 +0000212#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000213 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000214#endif
215#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000216 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000217#endif
drhd3d8c042012-05-29 17:02:40 +0000218#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000219 /* The next group of variables are used to track whether or not the
220 ** transaction counter in bytes 24-27 of database files are updated
221 ** whenever any part of the database changes. An assertion fault will
222 ** occur if a file is updated without also updating the transaction
223 ** counter. This test is made to avoid new problems similar to the
224 ** one described by ticket #3584.
225 */
226 unsigned char transCntrChng; /* True if the transaction counter changed */
227 unsigned char dbUpdate; /* True if any part of database file changed */
228 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000229
drh8f941bc2009-01-14 23:03:40 +0000230#endif
danf23da962013-03-23 21:00:41 +0000231
danielk1977967a4a12007-08-20 14:23:44 +0000232#ifdef SQLITE_TEST
233 /* In test mode, increase the size of this structure a bit so that
234 ** it is larger than the struct CrashFile defined in test6.c.
235 */
236 char aPadding[32];
237#endif
drh9cbe6352005-11-29 03:13:21 +0000238};
239
drhb00d8622014-01-01 15:18:36 +0000240/* This variable holds the process id (pid) from when the xRandomness()
241** method was called. If xOpen() is called from a different process id,
242** indicating that a fork() has occurred, the PRNG will be reset.
243*/
drh8cd5b252015-03-02 22:06:43 +0000244static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000245
drh0ccebe72005-06-07 22:22:50 +0000246/*
drha7e61d82011-03-12 17:02:57 +0000247** Allowed values for the unixFile.ctrlFlags bitmask:
248*/
drhf0b190d2011-07-26 16:03:07 +0000249#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
250#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
251#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000252#ifndef SQLITE_DISABLE_DIRSYNC
253# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
254#else
255# define UNIXFILE_DIRSYNC 0x00
256#endif
drhcb15f352011-12-23 01:04:17 +0000257#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000258#define UNIXFILE_DELETE 0x20 /* Delete on close */
259#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
260#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drhe6d41732015-02-21 00:49:00 +0000261#define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
drhbbf76ee2015-03-10 20:22:35 +0000262#define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
drha7e61d82011-03-12 17:02:57 +0000263
264/*
drh198bf392006-01-06 21:52:49 +0000265** Include code that is common to all os_*.c files
266*/
267#include "os_common.h"
268
269/*
drh0ccebe72005-06-07 22:22:50 +0000270** Define various macros that are missing from some systems.
271*/
drhbbd42a62004-05-22 17:41:58 +0000272#ifndef O_LARGEFILE
273# define O_LARGEFILE 0
274#endif
275#ifdef SQLITE_DISABLE_LFS
276# undef O_LARGEFILE
277# define O_LARGEFILE 0
278#endif
279#ifndef O_NOFOLLOW
280# define O_NOFOLLOW 0
281#endif
282#ifndef O_BINARY
283# define O_BINARY 0
284#endif
285
286/*
drh2b4b5962005-06-15 17:47:55 +0000287** The threadid macro resolves to the thread-id or to 0. Used for
288** testing and debugging only.
289*/
drhd677b3d2007-08-20 22:48:41 +0000290#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000291#define threadid pthread_self()
292#else
293#define threadid 0
294#endif
295
drh99ab3b12011-03-02 15:09:07 +0000296/*
dane6ecd662013-04-01 17:56:59 +0000297** HAVE_MREMAP defaults to true on Linux and false everywhere else.
298*/
299#if !defined(HAVE_MREMAP)
300# if defined(__linux__) && defined(_GNU_SOURCE)
301# define HAVE_MREMAP 1
302# else
303# define HAVE_MREMAP 0
304# endif
305#endif
306
307/*
dan2ee53412014-09-06 16:49:40 +0000308** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
309** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
310*/
311#ifdef __ANDROID__
312# define lseek lseek64
313#endif
314
315/*
drh9a3baf12011-04-25 18:01:27 +0000316** Different Unix systems declare open() in different ways. Same use
317** open(const char*,int,mode_t). Others use open(const char*,int,...).
318** The difference is important when using a pointer to the function.
319**
320** The safest way to deal with the problem is to always use this wrapper
321** which always has the same well-defined interface.
322*/
323static int posixOpen(const char *zFile, int flags, int mode){
324 return open(zFile, flags, mode);
325}
326
drhed466822012-05-31 13:10:49 +0000327/*
328** On some systems, calls to fchown() will trigger a message in a security
329** log if they come from non-root processes. So avoid calling fchown() if
330** we are not running as root.
331*/
332static int posixFchown(int fd, uid_t uid, gid_t gid){
drh91be7dc2014-08-11 13:53:30 +0000333#if OS_VXWORKS
334 return 0;
335#else
drhed466822012-05-31 13:10:49 +0000336 return geteuid() ? 0 : fchown(fd,uid,gid);
drh91be7dc2014-08-11 13:53:30 +0000337#endif
drhed466822012-05-31 13:10:49 +0000338}
339
drh90315a22011-08-10 01:52:12 +0000340/* Forward reference */
341static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000342static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000343
drh9a3baf12011-04-25 18:01:27 +0000344/*
drh99ab3b12011-03-02 15:09:07 +0000345** Many system calls are accessed through pointer-to-functions so that
346** they may be overridden at runtime to facilitate fault injection during
347** testing and sandboxing. The following array holds the names and pointers
348** to all overrideable system calls.
349*/
350static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000351 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000352 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
353 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000354} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000355 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
356#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000357
drh58ad5802011-03-23 22:02:23 +0000358 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000359#define osClose ((int(*)(int))aSyscall[1].pCurrent)
360
drh58ad5802011-03-23 22:02:23 +0000361 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000362#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
369
370/*
371** The DJGPP compiler environment looks mostly like Unix, but it
372** lacks the fcntl() system call. So redefine fcntl() to be something
373** that always succeeds. This means that locking does not occur under
374** DJGPP. But it is DOS - what did you expect?
375*/
376#ifdef __DJGPP__
377 { "fstat", 0, 0 },
378#define osFstat(a,b,c) 0
379#else
drh58ad5802011-03-23 22:02:23 +0000380 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000381#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
382#endif
383
drh58ad5802011-03-23 22:02:23 +0000384 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000385#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
386
drh58ad5802011-03-23 22:02:23 +0000387 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000389
drh58ad5802011-03-23 22:02:23 +0000390 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000391#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
392
drhe89b2912015-03-03 20:42:01 +0000393#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000394 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000395#else
drh58ad5802011-03-23 22:02:23 +0000396 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000397#endif
398#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
399
400#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000401 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000402#else
drh58ad5802011-03-23 22:02:23 +0000403 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000404#endif
405#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
406
drh58ad5802011-03-23 22:02:23 +0000407 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000408#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
409
drhe89b2912015-03-03 20:42:01 +0000410#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000411 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000412#else
drh58ad5802011-03-23 22:02:23 +0000413 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000414#endif
415#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
416 aSyscall[12].pCurrent)
417
418#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000419 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000420#else
drh58ad5802011-03-23 22:02:23 +0000421 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000422#endif
423#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
424 aSyscall[13].pCurrent)
425
drh58ad5802011-03-23 22:02:23 +0000426 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000427#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000428
429#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000430 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000431#else
drh58ad5802011-03-23 22:02:23 +0000432 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000433#endif
dan0fd7d862011-03-29 10:04:23 +0000434#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000435
drh036ac7f2011-08-08 23:18:05 +0000436 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
437#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
438
drh90315a22011-08-10 01:52:12 +0000439 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
440#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
441
drh9ef6bc42011-11-04 02:24:02 +0000442 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
443#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
444
445 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
446#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
447
drhed466822012-05-31 13:10:49 +0000448 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
dand3eaebd2012-02-13 08:50:23 +0000449#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000450
dan4dd51442013-08-26 14:30:25 +0000451#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
dan893c0ff2013-03-25 19:05:07 +0000452 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
453#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
454
drhd1ab8062013-03-25 20:50:25 +0000455 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
456#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
457
dane6ecd662013-04-01 17:56:59 +0000458#if HAVE_MREMAP
drhd1ab8062013-03-25 20:50:25 +0000459 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
460#else
461 { "mremap", (sqlite3_syscall_ptr)0, 0 },
462#endif
463#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
danbc760632014-03-20 09:42:09 +0000464 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
465#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
466
dan245fdc62015-10-31 17:58:33 +0000467 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
468#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[25].pCurrent)
469
dan702eec12014-06-23 10:04:58 +0000470#endif
471
drhe562be52011-03-02 18:01:10 +0000472}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000473
474/*
475** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000476** "unix" VFSes. Return SQLITE_OK opon successfully updating the
477** system call pointer, or SQLITE_NOTFOUND if there is no configurable
478** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000479*/
480static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000481 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
482 const char *zName, /* Name of system call to override */
483 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000484){
drh58ad5802011-03-23 22:02:23 +0000485 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000486 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000487
488 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000489 if( zName==0 ){
490 /* If no zName is given, restore all system calls to their default
491 ** settings and return NULL
492 */
dan51438a72011-04-02 17:00:47 +0000493 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000494 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
495 if( aSyscall[i].pDefault ){
496 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000497 }
498 }
499 }else{
500 /* If zName is specified, operate on only the one system call
501 ** specified.
502 */
503 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
504 if( strcmp(zName, aSyscall[i].zName)==0 ){
505 if( aSyscall[i].pDefault==0 ){
506 aSyscall[i].pDefault = aSyscall[i].pCurrent;
507 }
drh1df30962011-03-02 19:06:42 +0000508 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000509 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
510 aSyscall[i].pCurrent = pNewFunc;
511 break;
512 }
513 }
514 }
515 return rc;
516}
517
drh1df30962011-03-02 19:06:42 +0000518/*
519** Return the value of a system call. Return NULL if zName is not a
520** recognized system call name. NULL is also returned if the system call
521** is currently undefined.
522*/
drh58ad5802011-03-23 22:02:23 +0000523static sqlite3_syscall_ptr unixGetSystemCall(
524 sqlite3_vfs *pNotUsed,
525 const char *zName
526){
527 unsigned int i;
528
529 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000530 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
531 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
532 }
533 return 0;
534}
535
536/*
537** Return the name of the first system call after zName. If zName==NULL
538** then return the name of the first system call. Return NULL if zName
539** is the last system call or if zName is not the name of a valid
540** system call.
541*/
542static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000543 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000544
545 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000546 if( zName ){
547 for(i=0; i<ArraySize(aSyscall)-1; i++){
548 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000549 }
550 }
dan0fd7d862011-03-29 10:04:23 +0000551 for(i++; i<ArraySize(aSyscall); i++){
552 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000553 }
554 return 0;
555}
556
drhad4f1e52011-03-04 15:43:57 +0000557/*
drh77a3fdc2013-08-30 14:24:12 +0000558** Do not accept any file descriptor less than this value, in order to avoid
559** opening database file using file descriptors that are commonly used for
560** standard input, output, and error.
561*/
562#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
563# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
564#endif
565
566/*
drh8c815d12012-02-13 20:16:37 +0000567** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000568** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000569**
570** If the file creation mode "m" is 0 then set it to the default for
571** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
572** 0644) as modified by the system umask. If m is not 0, then
573** make the file creation mode be exactly m ignoring the umask.
574**
575** The m parameter will be non-zero only when creating -wal, -journal,
576** and -shm files. We want those files to have *exactly* the same
577** permissions as their original database, unadulterated by the umask.
578** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
579** transaction crashes and leaves behind hot journals, then any
580** process that is able to write to the database will also be able to
581** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000582*/
drh8c815d12012-02-13 20:16:37 +0000583static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000584 int fd;
drhe1186ab2013-01-04 20:45:13 +0000585 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000586 while(1){
drh5adc60b2012-04-14 13:25:11 +0000587#if defined(O_CLOEXEC)
588 fd = osOpen(z,f|O_CLOEXEC,m2);
589#else
590 fd = osOpen(z,f,m2);
591#endif
drh5128d002013-08-30 06:20:23 +0000592 if( fd<0 ){
593 if( errno==EINTR ) continue;
594 break;
595 }
drh77a3fdc2013-08-30 14:24:12 +0000596 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000597 osClose(fd);
598 sqlite3_log(SQLITE_WARNING,
599 "attempt to open \"%s\" as file descriptor %d", z, fd);
600 fd = -1;
601 if( osOpen("/dev/null", f, m)<0 ) break;
602 }
drhe1186ab2013-01-04 20:45:13 +0000603 if( fd>=0 ){
604 if( m!=0 ){
605 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000606 if( osFstat(fd, &statbuf)==0
607 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000608 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000609 ){
drhe1186ab2013-01-04 20:45:13 +0000610 osFchmod(fd, m);
611 }
612 }
drh5adc60b2012-04-14 13:25:11 +0000613#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000614 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000615#endif
drhe1186ab2013-01-04 20:45:13 +0000616 }
drh5adc60b2012-04-14 13:25:11 +0000617 return fd;
drhad4f1e52011-03-04 15:43:57 +0000618}
danielk197713adf8a2004-06-03 16:08:41 +0000619
drh107886a2008-11-21 22:21:50 +0000620/*
dan9359c7b2009-08-21 08:29:10 +0000621** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000622** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000623** vxworksFileId objects used by this file, all of which may be
624** shared by multiple threads.
625**
626** Function unixMutexHeld() is used to assert() that the global mutex
627** is held when required. This function is only used as part of assert()
628** statements. e.g.
629**
630** unixEnterMutex()
631** assert( unixMutexHeld() );
632** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000633*/
634static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000635 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000636}
637static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000638 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000639}
dan9359c7b2009-08-21 08:29:10 +0000640#ifdef SQLITE_DEBUG
641static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000642 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000643}
644#endif
drh107886a2008-11-21 22:21:50 +0000645
drh734c9862008-11-28 15:37:20 +0000646
mistachkinfb383e92015-04-16 03:24:38 +0000647#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000648/*
649** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000650** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000651** integer lock-type.
652*/
drh308c2a52010-05-14 11:30:18 +0000653static const char *azFileLock(int eFileLock){
654 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000655 case NO_LOCK: return "NONE";
656 case SHARED_LOCK: return "SHARED";
657 case RESERVED_LOCK: return "RESERVED";
658 case PENDING_LOCK: return "PENDING";
659 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000660 }
661 return "ERROR";
662}
663#endif
664
665#ifdef SQLITE_LOCK_TRACE
666/*
667** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000668**
drh734c9862008-11-28 15:37:20 +0000669** This routine is used for troubleshooting locks on multithreaded
670** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
671** command-line option on the compiler. This code is normally
672** turned off.
673*/
674static int lockTrace(int fd, int op, struct flock *p){
675 char *zOpName, *zType;
676 int s;
677 int savedErrno;
678 if( op==F_GETLK ){
679 zOpName = "GETLK";
680 }else if( op==F_SETLK ){
681 zOpName = "SETLK";
682 }else{
drh99ab3b12011-03-02 15:09:07 +0000683 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000684 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
685 return s;
686 }
687 if( p->l_type==F_RDLCK ){
688 zType = "RDLCK";
689 }else if( p->l_type==F_WRLCK ){
690 zType = "WRLCK";
691 }else if( p->l_type==F_UNLCK ){
692 zType = "UNLCK";
693 }else{
694 assert( 0 );
695 }
696 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000697 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000698 savedErrno = errno;
699 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
700 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
701 (int)p->l_pid, s);
702 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
703 struct flock l2;
704 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000705 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000706 if( l2.l_type==F_RDLCK ){
707 zType = "RDLCK";
708 }else if( l2.l_type==F_WRLCK ){
709 zType = "WRLCK";
710 }else if( l2.l_type==F_UNLCK ){
711 zType = "UNLCK";
712 }else{
713 assert( 0 );
714 }
715 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
716 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
717 }
718 errno = savedErrno;
719 return s;
720}
drh99ab3b12011-03-02 15:09:07 +0000721#undef osFcntl
722#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000723#endif /* SQLITE_LOCK_TRACE */
724
drhff812312011-02-23 13:33:46 +0000725/*
726** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000727**
drhe6d41732015-02-21 00:49:00 +0000728** All calls to ftruncate() within this file should be made through
729** this wrapper. On the Android platform, bypassing the logic below
730** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000731*/
drhff812312011-02-23 13:33:46 +0000732static int robust_ftruncate(int h, sqlite3_int64 sz){
733 int rc;
dan2ee53412014-09-06 16:49:40 +0000734#ifdef __ANDROID__
735 /* On Android, ftruncate() always uses 32-bit offsets, even if
736 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000737 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000738 ** such attempts. */
739 if( sz>(sqlite3_int64)0x7FFFFFFF ){
740 rc = SQLITE_OK;
741 }else
742#endif
drh99ab3b12011-03-02 15:09:07 +0000743 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000744 return rc;
745}
drh734c9862008-11-28 15:37:20 +0000746
747/*
748** This routine translates a standard POSIX errno code into something
749** useful to the clients of the sqlite3 functions. Specifically, it is
750** intended to translate a variety of "try again" errors into SQLITE_BUSY
751** and a variety of "please close the file descriptor NOW" errors into
752** SQLITE_IOERR
753**
754** Errors during initialization of locks, or file system support for locks,
755** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
756*/
757static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
758 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000759#if 0
760 /* At one point this code was not commented out. In theory, this branch
761 ** should never be hit, as this function should only be called after
762 ** a locking-related function (i.e. fcntl()) has returned non-zero with
763 ** the value of errno as the first argument. Since a system call has failed,
764 ** errno should be non-zero.
765 **
766 ** Despite this, if errno really is zero, we still don't want to return
767 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
768 ** propagated back to the caller. Commenting this branch out means errno==0
769 ** will be handled by the "default:" case below.
770 */
drh734c9862008-11-28 15:37:20 +0000771 case 0:
772 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000773#endif
774
drh734c9862008-11-28 15:37:20 +0000775 case EAGAIN:
776 case ETIMEDOUT:
777 case EBUSY:
778 case EINTR:
779 case ENOLCK:
780 /* random NFS retry error, unless during file system support
781 * introspection, in which it actually means what it says */
782 return SQLITE_BUSY;
783
784 case EACCES:
785 /* EACCES is like EAGAIN during locking operations, but not any other time*/
786 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000787 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
788 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
789 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000790 return SQLITE_BUSY;
791 }
792 /* else fall through */
793 case EPERM:
794 return SQLITE_PERM;
795
drh734c9862008-11-28 15:37:20 +0000796#if EOPNOTSUPP!=ENOTSUP
797 case EOPNOTSUPP:
798 /* something went terribly awry, unless during file system support
799 * introspection, in which it actually means what it says */
800#endif
801#ifdef ENOTSUP
802 case ENOTSUP:
803 /* invalid fd, unless during file system support introspection, in which
804 * it actually means what it says */
805#endif
806 case EIO:
807 case EBADF:
808 case EINVAL:
809 case ENOTCONN:
810 case ENODEV:
811 case ENXIO:
812 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000813#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000814 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000815#endif
drh734c9862008-11-28 15:37:20 +0000816 case ENOSYS:
817 /* these should force the client to close the file and reconnect */
818
819 default:
820 return sqliteIOErr;
821 }
822}
823
824
drh734c9862008-11-28 15:37:20 +0000825/******************************************************************************
826****************** Begin Unique File ID Utility Used By VxWorks ***************
827**
828** On most versions of unix, we can get a unique ID for a file by concatenating
829** the device number and the inode number. But this does not work on VxWorks.
830** On VxWorks, a unique file id must be based on the canonical filename.
831**
832** A pointer to an instance of the following structure can be used as a
833** unique file ID in VxWorks. Each instance of this structure contains
834** a copy of the canonical filename. There is also a reference count.
835** The structure is reclaimed when the number of pointers to it drops to
836** zero.
837**
838** There are never very many files open at one time and lookups are not
839** a performance-critical path, so it is sufficient to put these
840** structures on a linked list.
841*/
842struct vxworksFileId {
843 struct vxworksFileId *pNext; /* Next in a list of them all */
844 int nRef; /* Number of references to this one */
845 int nName; /* Length of the zCanonicalName[] string */
846 char *zCanonicalName; /* Canonical filename */
847};
848
849#if OS_VXWORKS
850/*
drh9b35ea62008-11-29 02:20:26 +0000851** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000852** variable:
853*/
854static struct vxworksFileId *vxworksFileList = 0;
855
856/*
857** Simplify a filename into its canonical form
858** by making the following changes:
859**
860** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000861** * convert /./ into just /
862** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000863**
864** Changes are made in-place. Return the new name length.
865**
866** The original filename is in z[0..n-1]. Return the number of
867** characters in the simplified name.
868*/
869static int vxworksSimplifyName(char *z, int n){
870 int i, j;
871 while( n>1 && z[n-1]=='/' ){ n--; }
872 for(i=j=0; i<n; i++){
873 if( z[i]=='/' ){
874 if( z[i+1]=='/' ) continue;
875 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
876 i += 1;
877 continue;
878 }
879 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
880 while( j>0 && z[j-1]!='/' ){ j--; }
881 if( j>0 ){ j--; }
882 i += 2;
883 continue;
884 }
885 }
886 z[j++] = z[i];
887 }
888 z[j] = 0;
889 return j;
890}
891
892/*
893** Find a unique file ID for the given absolute pathname. Return
894** a pointer to the vxworksFileId object. This pointer is the unique
895** file ID.
896**
897** The nRef field of the vxworksFileId object is incremented before
898** the object is returned. A new vxworksFileId object is created
899** and added to the global list if necessary.
900**
901** If a memory allocation error occurs, return NULL.
902*/
903static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
904 struct vxworksFileId *pNew; /* search key and new file ID */
905 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
906 int n; /* Length of zAbsoluteName string */
907
908 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000909 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000910 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000911 if( pNew==0 ) return 0;
912 pNew->zCanonicalName = (char*)&pNew[1];
913 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
914 n = vxworksSimplifyName(pNew->zCanonicalName, n);
915
916 /* Search for an existing entry that matching the canonical name.
917 ** If found, increment the reference count and return a pointer to
918 ** the existing file ID.
919 */
920 unixEnterMutex();
921 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
922 if( pCandidate->nName==n
923 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
924 ){
925 sqlite3_free(pNew);
926 pCandidate->nRef++;
927 unixLeaveMutex();
928 return pCandidate;
929 }
930 }
931
932 /* No match was found. We will make a new file ID */
933 pNew->nRef = 1;
934 pNew->nName = n;
935 pNew->pNext = vxworksFileList;
936 vxworksFileList = pNew;
937 unixLeaveMutex();
938 return pNew;
939}
940
941/*
942** Decrement the reference count on a vxworksFileId object. Free
943** the object when the reference count reaches zero.
944*/
945static void vxworksReleaseFileId(struct vxworksFileId *pId){
946 unixEnterMutex();
947 assert( pId->nRef>0 );
948 pId->nRef--;
949 if( pId->nRef==0 ){
950 struct vxworksFileId **pp;
951 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
952 assert( *pp==pId );
953 *pp = pId->pNext;
954 sqlite3_free(pId);
955 }
956 unixLeaveMutex();
957}
958#endif /* OS_VXWORKS */
959/*************** End of Unique File ID Utility Used By VxWorks ****************
960******************************************************************************/
961
962
963/******************************************************************************
964*************************** Posix Advisory Locking ****************************
965**
drh9b35ea62008-11-29 02:20:26 +0000966** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000967** section 6.5.2.2 lines 483 through 490 specify that when a process
968** sets or clears a lock, that operation overrides any prior locks set
969** by the same process. It does not explicitly say so, but this implies
970** that it overrides locks set by the same process using a different
971** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000972**
973** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000974** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
975**
976** Suppose ./file1 and ./file2 are really the same file (because
977** one is a hard or symbolic link to the other) then if you set
978** an exclusive lock on fd1, then try to get an exclusive lock
979** on fd2, it works. I would have expected the second lock to
980** fail since there was already a lock on the file due to fd1.
981** But not so. Since both locks came from the same process, the
982** second overrides the first, even though they were on different
983** file descriptors opened on different file names.
984**
drh734c9862008-11-28 15:37:20 +0000985** This means that we cannot use POSIX locks to synchronize file access
986** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000987** to synchronize access for threads in separate processes, but not
988** threads within the same process.
989**
990** To work around the problem, SQLite has to manage file locks internally
991** on its own. Whenever a new database is opened, we have to find the
992** specific inode of the database file (the inode is determined by the
993** st_dev and st_ino fields of the stat structure that fstat() fills in)
994** and check for locks already existing on that inode. When locks are
995** created or removed, we have to look at our own internal record of the
996** locks to see if another thread has previously set a lock on that same
997** inode.
998**
drh9b35ea62008-11-29 02:20:26 +0000999** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1000** For VxWorks, we have to use the alternative unique ID system based on
1001** canonical filename and implemented in the previous division.)
1002**
danielk1977ad94b582007-08-20 06:44:22 +00001003** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001004** descriptor. It is now a structure that holds the integer file
1005** descriptor and a pointer to a structure that describes the internal
1006** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001007** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001008** point to the same locking structure. The locking structure keeps
1009** a reference count (so we will know when to delete it) and a "cnt"
1010** field that tells us its internal lock status. cnt==0 means the
1011** file is unlocked. cnt==-1 means the file has an exclusive lock.
1012** cnt>0 means there are cnt shared locks on the file.
1013**
1014** Any attempt to lock or unlock a file first checks the locking
1015** structure. The fcntl() system call is only invoked to set a
1016** POSIX lock if the internal lock structure transitions between
1017** a locked and an unlocked state.
1018**
drh734c9862008-11-28 15:37:20 +00001019** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001020**
1021** If you close a file descriptor that points to a file that has locks,
1022** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001023** released. To work around this problem, each unixInodeInfo object
1024** maintains a count of the number of pending locks on tha inode.
1025** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001026** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001027** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001028** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001029** be closed and that list is walked (and cleared) when the last lock
1030** clears.
1031**
drh9b35ea62008-11-29 02:20:26 +00001032** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001033**
drh9b35ea62008-11-29 02:20:26 +00001034** Many older versions of linux use the LinuxThreads library which is
1035** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001036** A cannot be modified or overridden by a different thread B.
1037** Only thread A can modify the lock. Locking behavior is correct
1038** if the appliation uses the newer Native Posix Thread Library (NPTL)
1039** on linux - with NPTL a lock created by thread A can override locks
1040** in thread B. But there is no way to know at compile-time which
1041** threading library is being used. So there is no way to know at
1042** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001043** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001044** current process.
drh5fdae772004-06-29 03:29:00 +00001045**
drh8af6c222010-05-14 12:43:01 +00001046** SQLite used to support LinuxThreads. But support for LinuxThreads
1047** was dropped beginning with version 3.7.0. SQLite will still work with
1048** LinuxThreads provided that (1) there is no more than one connection
1049** per database file in the same process and (2) database connections
1050** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001051*/
1052
1053/*
1054** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001055** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001056*/
1057struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001058 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001059#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001060 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001061#else
drh107886a2008-11-21 22:21:50 +00001062 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001063#endif
1064};
1065
1066/*
drhbbd42a62004-05-22 17:41:58 +00001067** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001068** inode. Or, on LinuxThreads, there is one of these structures for
1069** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001070**
danielk1977ad94b582007-08-20 06:44:22 +00001071** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001072** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001073** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001074*/
drh8af6c222010-05-14 12:43:01 +00001075struct unixInodeInfo {
1076 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001077 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001078 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1079 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001080 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001081 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1082 int nLock; /* Number of outstanding file locks */
1083 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1084 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1085 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001086#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001087 unsigned long long sharedByte; /* for AFP simulated shared lock */
1088#endif
drh6c7d5c52008-11-21 20:32:33 +00001089#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001090 sem_t *pSem; /* Named POSIX semaphore */
1091 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001092#endif
drhbbd42a62004-05-22 17:41:58 +00001093};
1094
drhda0e7682008-07-30 15:27:54 +00001095/*
drh8af6c222010-05-14 12:43:01 +00001096** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001097*/
drhd91c68f2010-05-14 14:52:25 +00001098static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001099
drh5fdae772004-06-29 03:29:00 +00001100/*
dane18d4952011-02-21 11:46:24 +00001101**
1102** This function - unixLogError_x(), is only ever called via the macro
1103** unixLogError().
1104**
1105** It is invoked after an error occurs in an OS function and errno has been
1106** set. It logs a message using sqlite3_log() containing the current value of
1107** errno and, if possible, the human-readable equivalent from strerror() or
1108** strerror_r().
1109**
1110** The first argument passed to the macro should be the error code that
1111** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1112** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001113** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001114** if any.
1115*/
drh0e9365c2011-03-02 02:08:13 +00001116#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1117static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001118 int errcode, /* SQLite error code */
1119 const char *zFunc, /* Name of OS function that failed */
1120 const char *zPath, /* File path associated with error */
1121 int iLine /* Source line number where error occurred */
1122){
1123 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001124 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001125
1126 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1127 ** the strerror() function to obtain the human-readable error message
1128 ** equivalent to errno. Otherwise, use strerror_r().
1129 */
1130#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1131 char aErr[80];
1132 memset(aErr, 0, sizeof(aErr));
1133 zErr = aErr;
1134
1135 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001136 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001137 ** returns a pointer to a buffer containing the error message. That pointer
1138 ** may point to aErr[], or it may point to some static storage somewhere.
1139 ** Otherwise, assume that the system provides the POSIX version of
1140 ** strerror_r(), which always writes an error message into aErr[].
1141 **
1142 ** If the code incorrectly assumes that it is the POSIX version that is
1143 ** available, the error message will often be an empty string. Not a
1144 ** huge problem. Incorrectly concluding that the GNU version is available
1145 ** could lead to a segfault though.
1146 */
1147#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1148 zErr =
1149# endif
drh0e9365c2011-03-02 02:08:13 +00001150 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001151
1152#elif SQLITE_THREADSAFE
1153 /* This is a threadsafe build, but strerror_r() is not available. */
1154 zErr = "";
1155#else
1156 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001157 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001158#endif
1159
drh0e9365c2011-03-02 02:08:13 +00001160 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001161 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001162 "os_unix.c:%d: (%d) %s(%s) - %s",
1163 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001164 );
1165
1166 return errcode;
1167}
1168
drh0e9365c2011-03-02 02:08:13 +00001169/*
1170** Close a file descriptor.
1171**
1172** We assume that close() almost always works, since it is only in a
1173** very sick application or on a very sick platform that it might fail.
1174** If it does fail, simply leak the file descriptor, but do log the
1175** error.
1176**
1177** Note that it is not safe to retry close() after EINTR since the
1178** file descriptor might have already been reused by another thread.
1179** So we don't even try to recover from an EINTR. Just log the error
1180** and move on.
1181*/
1182static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001183 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001184 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1185 pFile ? pFile->zPath : 0, lineno);
1186 }
1187}
dane18d4952011-02-21 11:46:24 +00001188
1189/*
drhe6d41732015-02-21 00:49:00 +00001190** Set the pFile->lastErrno. Do this in a subroutine as that provides
1191** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001192*/
1193static void storeLastErrno(unixFile *pFile, int error){
1194 pFile->lastErrno = error;
1195}
1196
1197/*
danb0ac3e32010-06-16 10:55:42 +00001198** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001199*/
drh0e9365c2011-03-02 02:08:13 +00001200static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001201 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001202 UnixUnusedFd *p;
1203 UnixUnusedFd *pNext;
1204 for(p=pInode->pUnused; p; p=pNext){
1205 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001206 robust_close(pFile, p->fd, __LINE__);
1207 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001208 }
drh0e9365c2011-03-02 02:08:13 +00001209 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001210}
1211
1212/*
drh8af6c222010-05-14 12:43:01 +00001213** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001214**
1215** The mutex entered using the unixEnterMutex() function must be held
1216** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001217*/
danb0ac3e32010-06-16 10:55:42 +00001218static void releaseInodeInfo(unixFile *pFile){
1219 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001220 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001221 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001222 pInode->nRef--;
1223 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001224 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001225 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001226 if( pInode->pPrev ){
1227 assert( pInode->pPrev->pNext==pInode );
1228 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001229 }else{
drh8af6c222010-05-14 12:43:01 +00001230 assert( inodeList==pInode );
1231 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001232 }
drh8af6c222010-05-14 12:43:01 +00001233 if( pInode->pNext ){
1234 assert( pInode->pNext->pPrev==pInode );
1235 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001236 }
drh8af6c222010-05-14 12:43:01 +00001237 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001238 }
drhbbd42a62004-05-22 17:41:58 +00001239 }
1240}
1241
1242/*
drh8af6c222010-05-14 12:43:01 +00001243** Given a file descriptor, locate the unixInodeInfo object that
1244** describes that file descriptor. Create a new one if necessary. The
1245** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001246**
dan9359c7b2009-08-21 08:29:10 +00001247** The mutex entered using the unixEnterMutex() function must be held
1248** when this function is called.
1249**
drh6c7d5c52008-11-21 20:32:33 +00001250** Return an appropriate error code.
1251*/
drh8af6c222010-05-14 12:43:01 +00001252static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001253 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001254 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001255){
1256 int rc; /* System call return code */
1257 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001258 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1259 struct stat statbuf; /* Low-level file information */
1260 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001261
dan9359c7b2009-08-21 08:29:10 +00001262 assert( unixMutexHeld() );
1263
drh6c7d5c52008-11-21 20:32:33 +00001264 /* Get low-level information about the file that we can used to
1265 ** create a unique name for the file.
1266 */
1267 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001268 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001269 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001270 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001271#ifdef EOVERFLOW
1272 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1273#endif
1274 return SQLITE_IOERR;
1275 }
1276
drheb0d74f2009-02-03 15:27:02 +00001277#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001278 /* On OS X on an msdos filesystem, the inode number is reported
1279 ** incorrectly for zero-size files. See ticket #3260. To work
1280 ** around this problem (we consider it a bug in OS X, not SQLite)
1281 ** we always increase the file size to 1 by writing a single byte
1282 ** prior to accessing the inode number. The one byte written is
1283 ** an ASCII 'S' character which also happens to be the first byte
1284 ** in the header of every SQLite database. In this way, if there
1285 ** is a race condition such that another thread has already populated
1286 ** the first page of the database, no damage is done.
1287 */
drh7ed97b92010-01-20 13:07:21 +00001288 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001289 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001290 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001291 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001292 return SQLITE_IOERR;
1293 }
drh99ab3b12011-03-02 15:09:07 +00001294 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001295 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001296 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001297 return SQLITE_IOERR;
1298 }
1299 }
drheb0d74f2009-02-03 15:27:02 +00001300#endif
drh6c7d5c52008-11-21 20:32:33 +00001301
drh8af6c222010-05-14 12:43:01 +00001302 memset(&fileId, 0, sizeof(fileId));
1303 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001304#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001305 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001306#else
drh8af6c222010-05-14 12:43:01 +00001307 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001308#endif
drh8af6c222010-05-14 12:43:01 +00001309 pInode = inodeList;
1310 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1311 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001312 }
drh8af6c222010-05-14 12:43:01 +00001313 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001314 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001315 if( pInode==0 ){
1316 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001317 }
drh8af6c222010-05-14 12:43:01 +00001318 memset(pInode, 0, sizeof(*pInode));
1319 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1320 pInode->nRef = 1;
1321 pInode->pNext = inodeList;
1322 pInode->pPrev = 0;
1323 if( inodeList ) inodeList->pPrev = pInode;
1324 inodeList = pInode;
1325 }else{
1326 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001327 }
drh8af6c222010-05-14 12:43:01 +00001328 *ppInode = pInode;
1329 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001330}
drh6c7d5c52008-11-21 20:32:33 +00001331
drhb959a012013-12-07 12:29:22 +00001332/*
1333** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1334*/
1335static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001336#if OS_VXWORKS
1337 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1338#else
drhb959a012013-12-07 12:29:22 +00001339 struct stat buf;
1340 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001341 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001342#endif
drhb959a012013-12-07 12:29:22 +00001343}
1344
aswift5b1a2562008-08-22 00:22:35 +00001345
1346/*
drhfbc7e882013-04-11 01:16:15 +00001347** Check a unixFile that is a database. Verify the following:
1348**
1349** (1) There is exactly one hard link on the file
1350** (2) The file is not a symbolic link
1351** (3) The file has not been renamed or unlinked
1352**
1353** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1354*/
1355static void verifyDbFile(unixFile *pFile){
1356 struct stat buf;
1357 int rc;
drh3044b512014-06-16 16:41:52 +00001358 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1359 /* One or more of the following warnings have already been issued. Do not
1360 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001361 return;
1362 }
1363 rc = osFstat(pFile->h, &buf);
1364 if( rc!=0 ){
1365 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1366 pFile->ctrlFlags |= UNIXFILE_WARNED;
1367 return;
1368 }
drh3044b512014-06-16 16:41:52 +00001369 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001370 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1371 pFile->ctrlFlags |= UNIXFILE_WARNED;
1372 return;
1373 }
1374 if( buf.st_nlink>1 ){
1375 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1376 pFile->ctrlFlags |= UNIXFILE_WARNED;
1377 return;
1378 }
drhb959a012013-12-07 12:29:22 +00001379 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001380 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1381 pFile->ctrlFlags |= UNIXFILE_WARNED;
1382 return;
1383 }
1384}
1385
1386
1387/*
danielk197713adf8a2004-06-03 16:08:41 +00001388** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001389** file by this or any other process. If such a lock is held, set *pResOut
1390** to a non-zero value otherwise *pResOut is set to zero. The return value
1391** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001392*/
danielk1977861f7452008-06-05 11:39:11 +00001393static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001394 int rc = SQLITE_OK;
1395 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001396 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001397
danielk1977861f7452008-06-05 11:39:11 +00001398 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1399
drh054889e2005-11-30 03:20:31 +00001400 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001401 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001402
1403 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001404 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001405 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001406 }
1407
drh2ac3ee92004-06-07 16:27:46 +00001408 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001409 */
danielk197709480a92009-02-09 05:32:32 +00001410#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001411 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001412 struct flock lock;
1413 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001414 lock.l_start = RESERVED_BYTE;
1415 lock.l_len = 1;
1416 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001417 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1418 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001419 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001420 } else if( lock.l_type!=F_UNLCK ){
1421 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001422 }
1423 }
danielk197709480a92009-02-09 05:32:32 +00001424#endif
danielk197713adf8a2004-06-03 16:08:41 +00001425
drh6c7d5c52008-11-21 20:32:33 +00001426 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001427 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001428
aswift5b1a2562008-08-22 00:22:35 +00001429 *pResOut = reserved;
1430 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001431}
1432
1433/*
drha7e61d82011-03-12 17:02:57 +00001434** Attempt to set a system-lock on the file pFile. The lock is
1435** described by pLock.
1436**
drh77197112011-03-15 19:08:48 +00001437** If the pFile was opened read/write from unix-excl, then the only lock
1438** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001439** the first time any lock is attempted. All subsequent system locking
1440** operations become no-ops. Locking operations still happen internally,
1441** in order to coordinate access between separate database connections
1442** within this process, but all of that is handled in memory and the
1443** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001444**
1445** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1446** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1447** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001448**
1449** Zero is returned if the call completes successfully, or -1 if a call
1450** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001451*/
1452static int unixFileLock(unixFile *pFile, struct flock *pLock){
1453 int rc;
drh3cb93392011-03-12 18:10:44 +00001454 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001455 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001456 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001457 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1458 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1459 ){
drh3cb93392011-03-12 18:10:44 +00001460 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001461 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001462 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001463 lock.l_whence = SEEK_SET;
1464 lock.l_start = SHARED_FIRST;
1465 lock.l_len = SHARED_SIZE;
1466 lock.l_type = F_WRLCK;
1467 rc = osFcntl(pFile->h, F_SETLK, &lock);
1468 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001469 pInode->bProcessLock = 1;
1470 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001471 }else{
1472 rc = 0;
1473 }
1474 }else{
1475 rc = osFcntl(pFile->h, F_SETLK, pLock);
1476 }
1477 return rc;
1478}
1479
1480/*
drh308c2a52010-05-14 11:30:18 +00001481** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001482** of the following:
1483**
drh2ac3ee92004-06-07 16:27:46 +00001484** (1) SHARED_LOCK
1485** (2) RESERVED_LOCK
1486** (3) PENDING_LOCK
1487** (4) EXCLUSIVE_LOCK
1488**
drhb3e04342004-06-08 00:47:47 +00001489** Sometimes when requesting one lock state, additional lock states
1490** are inserted in between. The locking might fail on one of the later
1491** transitions leaving the lock state different from what it started but
1492** still short of its goal. The following chart shows the allowed
1493** transitions and the inserted intermediate states:
1494**
1495** UNLOCKED -> SHARED
1496** SHARED -> RESERVED
1497** SHARED -> (PENDING) -> EXCLUSIVE
1498** RESERVED -> (PENDING) -> EXCLUSIVE
1499** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001500**
drha6abd042004-06-09 17:37:22 +00001501** This routine will only increase a lock. Use the sqlite3OsUnlock()
1502** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001503*/
drh308c2a52010-05-14 11:30:18 +00001504static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001505 /* The following describes the implementation of the various locks and
1506 ** lock transitions in terms of the POSIX advisory shared and exclusive
1507 ** lock primitives (called read-locks and write-locks below, to avoid
1508 ** confusion with SQLite lock names). The algorithms are complicated
1509 ** slightly in order to be compatible with windows systems simultaneously
1510 ** accessing the same database file, in case that is ever required.
1511 **
1512 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1513 ** byte', each single bytes at well known offsets, and the 'shared byte
1514 ** range', a range of 510 bytes at a well known offset.
1515 **
1516 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1517 ** byte'. If this is successful, a random byte from the 'shared byte
1518 ** range' is read-locked and the lock on the 'pending byte' released.
1519 **
danielk197790ba3bd2004-06-25 08:32:25 +00001520 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1521 ** A RESERVED lock is implemented by grabbing a write-lock on the
1522 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001523 **
1524 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001525 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1526 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1527 ** obtained, but existing SHARED locks are allowed to persist. A process
1528 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1529 ** This property is used by the algorithm for rolling back a journal file
1530 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001531 **
danielk197790ba3bd2004-06-25 08:32:25 +00001532 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1533 ** implemented by obtaining a write-lock on the entire 'shared byte
1534 ** range'. Since all other locks require a read-lock on one of the bytes
1535 ** within this range, this ensures that no other locks are held on the
1536 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001537 **
1538 ** The reason a single byte cannot be used instead of the 'shared byte
1539 ** range' is that some versions of windows do not support read-locks. By
1540 ** locking a random byte from a range, concurrent SHARED locks may exist
1541 ** even if the locking primitive used is always a write-lock.
1542 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001543 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001544 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001545 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001546 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001547 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001548
drh054889e2005-11-30 03:20:31 +00001549 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001550 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1551 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001552 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001553 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001554
1555 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001556 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001557 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001558 */
drh308c2a52010-05-14 11:30:18 +00001559 if( pFile->eFileLock>=eFileLock ){
1560 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1561 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001562 return SQLITE_OK;
1563 }
1564
drh0c2694b2009-09-03 16:23:44 +00001565 /* Make sure the locking sequence is correct.
1566 ** (1) We never move from unlocked to anything higher than shared lock.
1567 ** (2) SQLite never explicitly requests a pendig lock.
1568 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001569 */
drh308c2a52010-05-14 11:30:18 +00001570 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1571 assert( eFileLock!=PENDING_LOCK );
1572 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001573
drh8af6c222010-05-14 12:43:01 +00001574 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001575 */
drh6c7d5c52008-11-21 20:32:33 +00001576 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001577 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001578
danielk1977ad94b582007-08-20 06:44:22 +00001579 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001580 ** handle that precludes the requested lock, return BUSY.
1581 */
drh8af6c222010-05-14 12:43:01 +00001582 if( (pFile->eFileLock!=pInode->eFileLock &&
1583 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001584 ){
1585 rc = SQLITE_BUSY;
1586 goto end_lock;
1587 }
1588
1589 /* If a SHARED lock is requested, and some thread using this PID already
1590 ** has a SHARED or RESERVED lock, then increment reference counts and
1591 ** return SQLITE_OK.
1592 */
drh308c2a52010-05-14 11:30:18 +00001593 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001594 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001595 assert( eFileLock==SHARED_LOCK );
1596 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001597 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001598 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001599 pInode->nShared++;
1600 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001601 goto end_lock;
1602 }
1603
danielk19779a1d0ab2004-06-01 14:09:28 +00001604
drh3cde3bb2004-06-12 02:17:14 +00001605 /* A PENDING lock is needed before acquiring a SHARED lock and before
1606 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1607 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001608 */
drh0c2694b2009-09-03 16:23:44 +00001609 lock.l_len = 1L;
1610 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001611 if( eFileLock==SHARED_LOCK
1612 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001613 ){
drh308c2a52010-05-14 11:30:18 +00001614 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001615 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001616 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001617 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001618 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001619 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001620 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001621 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001622 goto end_lock;
1623 }
drh3cde3bb2004-06-12 02:17:14 +00001624 }
1625
1626
1627 /* If control gets to this point, then actually go ahead and make
1628 ** operating system calls for the specified lock.
1629 */
drh308c2a52010-05-14 11:30:18 +00001630 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001631 assert( pInode->nShared==0 );
1632 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001633 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001634
drh2ac3ee92004-06-07 16:27:46 +00001635 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001636 lock.l_start = SHARED_FIRST;
1637 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001638 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001639 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001640 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001641 }
dan661d71a2011-03-30 19:08:03 +00001642
drh2ac3ee92004-06-07 16:27:46 +00001643 /* Drop the temporary PENDING lock */
1644 lock.l_start = PENDING_BYTE;
1645 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001646 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001647 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1648 /* This could happen with a network mount */
1649 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001650 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001651 }
dan661d71a2011-03-30 19:08:03 +00001652
1653 if( rc ){
1654 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001655 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001656 }
dan661d71a2011-03-30 19:08:03 +00001657 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001658 }else{
drh308c2a52010-05-14 11:30:18 +00001659 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001660 pInode->nLock++;
1661 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001662 }
drh8af6c222010-05-14 12:43:01 +00001663 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001664 /* We are trying for an exclusive lock but another thread in this
1665 ** same process is still holding a shared lock. */
1666 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001667 }else{
drh3cde3bb2004-06-12 02:17:14 +00001668 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001669 ** assumed that there is a SHARED or greater lock on the file
1670 ** already.
1671 */
drh308c2a52010-05-14 11:30:18 +00001672 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001673 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001674
1675 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1676 if( eFileLock==RESERVED_LOCK ){
1677 lock.l_start = RESERVED_BYTE;
1678 lock.l_len = 1L;
1679 }else{
1680 lock.l_start = SHARED_FIRST;
1681 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001682 }
dan661d71a2011-03-30 19:08:03 +00001683
1684 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001685 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001686 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001687 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001688 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001689 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001690 }
drhbbd42a62004-05-22 17:41:58 +00001691 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001692
drh8f941bc2009-01-14 23:03:40 +00001693
drhd3d8c042012-05-29 17:02:40 +00001694#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001695 /* Set up the transaction-counter change checking flags when
1696 ** transitioning from a SHARED to a RESERVED lock. The change
1697 ** from SHARED to RESERVED marks the beginning of a normal
1698 ** write operation (not a hot journal rollback).
1699 */
1700 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001701 && pFile->eFileLock<=SHARED_LOCK
1702 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001703 ){
1704 pFile->transCntrChng = 0;
1705 pFile->dbUpdate = 0;
1706 pFile->inNormalWrite = 1;
1707 }
1708#endif
1709
1710
danielk1977ecb2a962004-06-02 06:30:16 +00001711 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001712 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001713 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001714 }else if( eFileLock==EXCLUSIVE_LOCK ){
1715 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001716 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001717 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001718
1719end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001720 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001721 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1722 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001723 return rc;
1724}
1725
1726/*
dan08da86a2009-08-21 17:18:03 +00001727** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001728** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001729*/
1730static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001731 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001732 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001733 p->pNext = pInode->pUnused;
1734 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001735 pFile->h = -1;
1736 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001737}
1738
1739/*
drh308c2a52010-05-14 11:30:18 +00001740** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001741** must be either NO_LOCK or SHARED_LOCK.
1742**
1743** If the locking level of the file descriptor is already at or below
1744** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001745**
1746** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1747** the byte range is divided into 2 parts and the first part is unlocked then
1748** set to a read lock, then the other part is simply unlocked. This works
1749** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1750** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001751*/
drha7e61d82011-03-12 17:02:57 +00001752static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001753 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001754 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001755 struct flock lock;
1756 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001757
drh054889e2005-11-30 03:20:31 +00001758 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001759 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001760 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001761 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001762
drh308c2a52010-05-14 11:30:18 +00001763 assert( eFileLock<=SHARED_LOCK );
1764 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001765 return SQLITE_OK;
1766 }
drh6c7d5c52008-11-21 20:32:33 +00001767 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001768 pInode = pFile->pInode;
1769 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001770 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001771 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001772
drhd3d8c042012-05-29 17:02:40 +00001773#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001774 /* When reducing a lock such that other processes can start
1775 ** reading the database file again, make sure that the
1776 ** transaction counter was updated if any part of the database
1777 ** file changed. If the transaction counter is not updated,
1778 ** other connections to the same file might not realize that
1779 ** the file has changed and hence might not know to flush their
1780 ** cache. The use of a stale cache can lead to database corruption.
1781 */
drh8f941bc2009-01-14 23:03:40 +00001782 pFile->inNormalWrite = 0;
1783#endif
1784
drh7ed97b92010-01-20 13:07:21 +00001785 /* downgrading to a shared lock on NFS involves clearing the write lock
1786 ** before establishing the readlock - to avoid a race condition we downgrade
1787 ** the lock in 2 blocks, so that part of the range will be covered by a
1788 ** write lock until the rest is covered by a read lock:
1789 ** 1: [WWWWW]
1790 ** 2: [....W]
1791 ** 3: [RRRRW]
1792 ** 4: [RRRR.]
1793 */
drh308c2a52010-05-14 11:30:18 +00001794 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001795#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001796 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001797 assert( handleNFSUnlock==0 );
1798#endif
1799#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001800 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001801 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001802 off_t divSize = SHARED_SIZE - 1;
1803
1804 lock.l_type = F_UNLCK;
1805 lock.l_whence = SEEK_SET;
1806 lock.l_start = SHARED_FIRST;
1807 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001808 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001809 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001810 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001811 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001812 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001813 }
1814 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001815 }
drh7ed97b92010-01-20 13:07:21 +00001816 lock.l_type = F_RDLCK;
1817 lock.l_whence = SEEK_SET;
1818 lock.l_start = SHARED_FIRST;
1819 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001820 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001821 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001822 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1823 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001824 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001825 }
1826 goto end_unlock;
1827 }
1828 lock.l_type = F_UNLCK;
1829 lock.l_whence = SEEK_SET;
1830 lock.l_start = SHARED_FIRST+divSize;
1831 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001832 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001833 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001834 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001835 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001836 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001837 }
1838 goto end_unlock;
1839 }
drh30f776f2011-02-25 03:25:07 +00001840 }else
1841#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1842 {
drh7ed97b92010-01-20 13:07:21 +00001843 lock.l_type = F_RDLCK;
1844 lock.l_whence = SEEK_SET;
1845 lock.l_start = SHARED_FIRST;
1846 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001847 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001848 /* In theory, the call to unixFileLock() cannot fail because another
1849 ** process is holding an incompatible lock. If it does, this
1850 ** indicates that the other process is not following the locking
1851 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1852 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1853 ** an assert to fail). */
1854 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001855 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001856 goto end_unlock;
1857 }
drh9c105bb2004-10-02 20:38:28 +00001858 }
1859 }
drhbbd42a62004-05-22 17:41:58 +00001860 lock.l_type = F_UNLCK;
1861 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001862 lock.l_start = PENDING_BYTE;
1863 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001864 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001865 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001866 }else{
danea83bc62011-04-01 11:56:32 +00001867 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001868 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001869 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001870 }
drhbbd42a62004-05-22 17:41:58 +00001871 }
drh308c2a52010-05-14 11:30:18 +00001872 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001873 /* Decrement the shared lock counter. Release the lock using an
1874 ** OS call only when all threads in this same process have released
1875 ** the lock.
1876 */
drh8af6c222010-05-14 12:43:01 +00001877 pInode->nShared--;
1878 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001879 lock.l_type = F_UNLCK;
1880 lock.l_whence = SEEK_SET;
1881 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001882 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001883 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001884 }else{
danea83bc62011-04-01 11:56:32 +00001885 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001886 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001887 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001888 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001889 }
drha6abd042004-06-09 17:37:22 +00001890 }
1891
drhbbd42a62004-05-22 17:41:58 +00001892 /* Decrement the count of locks against this same file. When the
1893 ** count reaches zero, close any other file descriptors whose close
1894 ** was deferred because of outstanding locks.
1895 */
drh8af6c222010-05-14 12:43:01 +00001896 pInode->nLock--;
1897 assert( pInode->nLock>=0 );
1898 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001899 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001900 }
1901 }
drhf2f105d2012-08-20 15:53:54 +00001902
aswift5b1a2562008-08-22 00:22:35 +00001903end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001904 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001905 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001906 return rc;
drhbbd42a62004-05-22 17:41:58 +00001907}
1908
1909/*
drh308c2a52010-05-14 11:30:18 +00001910** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001911** must be either NO_LOCK or SHARED_LOCK.
1912**
1913** If the locking level of the file descriptor is already at or below
1914** the requested locking level, this routine is a no-op.
1915*/
drh308c2a52010-05-14 11:30:18 +00001916static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001917#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001918 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001919#endif
drha7e61d82011-03-12 17:02:57 +00001920 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001921}
1922
mistachkine98844f2013-08-24 00:59:24 +00001923#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001924static int unixMapfile(unixFile *pFd, i64 nByte);
1925static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001926#endif
danf23da962013-03-23 21:00:41 +00001927
drh7ed97b92010-01-20 13:07:21 +00001928/*
danielk1977e339d652008-06-28 11:23:00 +00001929** This function performs the parts of the "close file" operation
1930** common to all locking schemes. It closes the directory and file
1931** handles, if they are valid, and sets all fields of the unixFile
1932** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001933**
1934** It is *not* necessary to hold the mutex when this routine is called,
1935** even on VxWorks. A mutex will be acquired on VxWorks by the
1936** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001937*/
1938static int closeUnixFile(sqlite3_file *id){
1939 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001940#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001941 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001942#endif
dan661d71a2011-03-30 19:08:03 +00001943 if( pFile->h>=0 ){
1944 robust_close(pFile, pFile->h, __LINE__);
1945 pFile->h = -1;
1946 }
1947#if OS_VXWORKS
1948 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001949 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001950 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001951 }
1952 vxworksReleaseFileId(pFile->pId);
1953 pFile->pId = 0;
1954 }
1955#endif
drh0bdbc902014-06-16 18:35:06 +00001956#ifdef SQLITE_UNLINK_AFTER_CLOSE
1957 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1958 osUnlink(pFile->zPath);
1959 sqlite3_free(*(char**)&pFile->zPath);
1960 pFile->zPath = 0;
1961 }
1962#endif
dan661d71a2011-03-30 19:08:03 +00001963 OSTRACE(("CLOSE %-3d\n", pFile->h));
1964 OpenCounter(-1);
1965 sqlite3_free(pFile->pUnused);
1966 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001967 return SQLITE_OK;
1968}
1969
1970/*
danielk1977e3026632004-06-22 11:29:02 +00001971** Close a file.
1972*/
danielk197762079062007-08-15 17:08:46 +00001973static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001974 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001975 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001976 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001977 unixUnlock(id, NO_LOCK);
1978 unixEnterMutex();
1979
1980 /* unixFile.pInode is always valid here. Otherwise, a different close
1981 ** routine (e.g. nolockClose()) would be called instead.
1982 */
1983 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1984 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1985 /* If there are outstanding locks, do not actually close the file just
1986 ** yet because that would clear those locks. Instead, add the file
1987 ** descriptor to pInode->pUnused list. It will be automatically closed
1988 ** when the last lock is cleared.
1989 */
1990 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001991 }
dan661d71a2011-03-30 19:08:03 +00001992 releaseInodeInfo(pFile);
1993 rc = closeUnixFile(id);
1994 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001995 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001996}
1997
drh734c9862008-11-28 15:37:20 +00001998/************** End of the posix advisory lock implementation *****************
1999******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002000
drh734c9862008-11-28 15:37:20 +00002001/******************************************************************************
2002****************************** No-op Locking **********************************
2003**
2004** Of the various locking implementations available, this is by far the
2005** simplest: locking is ignored. No attempt is made to lock the database
2006** file for reading or writing.
2007**
2008** This locking mode is appropriate for use on read-only databases
2009** (ex: databases that are burned into CD-ROM, for example.) It can
2010** also be used if the application employs some external mechanism to
2011** prevent simultaneous access of the same database by two or more
2012** database connections. But there is a serious risk of database
2013** corruption if this locking mode is used in situations where multiple
2014** database connections are accessing the same database file at the same
2015** time and one or more of those connections are writing.
2016*/
drhbfe66312006-10-03 17:40:40 +00002017
drh734c9862008-11-28 15:37:20 +00002018static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2019 UNUSED_PARAMETER(NotUsed);
2020 *pResOut = 0;
2021 return SQLITE_OK;
2022}
drh734c9862008-11-28 15:37:20 +00002023static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2024 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2025 return SQLITE_OK;
2026}
drh734c9862008-11-28 15:37:20 +00002027static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2028 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2029 return SQLITE_OK;
2030}
2031
2032/*
drh9b35ea62008-11-29 02:20:26 +00002033** Close the file.
drh734c9862008-11-28 15:37:20 +00002034*/
2035static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002036 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002037}
2038
2039/******************* End of the no-op lock implementation *********************
2040******************************************************************************/
2041
2042/******************************************************************************
2043************************* Begin dot-file Locking ******************************
2044**
mistachkin48864df2013-03-21 21:20:32 +00002045** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002046** files (really a directory) to control access to the database. This works
2047** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002048**
2049** (1) There is zero concurrency. A single reader blocks all other
2050** connections from reading or writing the database.
2051**
2052** (2) An application crash or power loss can leave stale lock files
2053** sitting around that need to be cleared manually.
2054**
2055** Nevertheless, a dotlock is an appropriate locking mode for use if no
2056** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002057**
drh9ef6bc42011-11-04 02:24:02 +00002058** Dotfile locking works by creating a subdirectory in the same directory as
2059** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002060** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002061** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002062*/
2063
2064/*
2065** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002066** lock directory.
drh734c9862008-11-28 15:37:20 +00002067*/
2068#define DOTLOCK_SUFFIX ".lock"
2069
drh7708e972008-11-29 00:56:52 +00002070/*
2071** This routine checks if there is a RESERVED lock held on the specified
2072** file by this or any other process. If such a lock is held, set *pResOut
2073** to a non-zero value otherwise *pResOut is set to zero. The return value
2074** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2075**
2076** In dotfile locking, either a lock exists or it does not. So in this
2077** variation of CheckReservedLock(), *pResOut is set to true if any lock
2078** is held on the file and false if the file is unlocked.
2079*/
drh734c9862008-11-28 15:37:20 +00002080static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2081 int rc = SQLITE_OK;
2082 int reserved = 0;
2083 unixFile *pFile = (unixFile*)id;
2084
2085 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2086
2087 assert( pFile );
2088
2089 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002090 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002091 /* Either this connection or some other connection in the same process
2092 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002093 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002094 }else{
2095 /* The lock is held if and only if the lockfile exists */
2096 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002097 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002098 }
drh308c2a52010-05-14 11:30:18 +00002099 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002100 *pResOut = reserved;
2101 return rc;
2102}
2103
drh7708e972008-11-29 00:56:52 +00002104/*
drh308c2a52010-05-14 11:30:18 +00002105** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002106** of the following:
2107**
2108** (1) SHARED_LOCK
2109** (2) RESERVED_LOCK
2110** (3) PENDING_LOCK
2111** (4) EXCLUSIVE_LOCK
2112**
2113** Sometimes when requesting one lock state, additional lock states
2114** are inserted in between. The locking might fail on one of the later
2115** transitions leaving the lock state different from what it started but
2116** still short of its goal. The following chart shows the allowed
2117** transitions and the inserted intermediate states:
2118**
2119** UNLOCKED -> SHARED
2120** SHARED -> RESERVED
2121** SHARED -> (PENDING) -> EXCLUSIVE
2122** RESERVED -> (PENDING) -> EXCLUSIVE
2123** PENDING -> EXCLUSIVE
2124**
2125** This routine will only increase a lock. Use the sqlite3OsUnlock()
2126** routine to lower a locking level.
2127**
2128** With dotfile locking, we really only support state (4): EXCLUSIVE.
2129** But we track the other locking levels internally.
2130*/
drh308c2a52010-05-14 11:30:18 +00002131static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002132 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002133 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002134 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002135
drh7708e972008-11-29 00:56:52 +00002136
2137 /* If we have any lock, then the lock file already exists. All we have
2138 ** to do is adjust our internal record of the lock level.
2139 */
drh308c2a52010-05-14 11:30:18 +00002140 if( pFile->eFileLock > NO_LOCK ){
2141 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002142 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002143#ifdef HAVE_UTIME
2144 utime(zLockFile, NULL);
2145#else
drh734c9862008-11-28 15:37:20 +00002146 utimes(zLockFile, NULL);
2147#endif
drh7708e972008-11-29 00:56:52 +00002148 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002149 }
2150
2151 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002152 rc = osMkdir(zLockFile, 0777);
2153 if( rc<0 ){
2154 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002155 int tErrno = errno;
2156 if( EEXIST == tErrno ){
2157 rc = SQLITE_BUSY;
2158 } else {
2159 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2160 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002161 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002162 }
2163 }
drh7708e972008-11-29 00:56:52 +00002164 return rc;
drh734c9862008-11-28 15:37:20 +00002165 }
drh734c9862008-11-28 15:37:20 +00002166
2167 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002168 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002169 return rc;
2170}
2171
drh7708e972008-11-29 00:56:52 +00002172/*
drh308c2a52010-05-14 11:30:18 +00002173** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002174** must be either NO_LOCK or SHARED_LOCK.
2175**
2176** If the locking level of the file descriptor is already at or below
2177** the requested locking level, this routine is a no-op.
2178**
2179** When the locking level reaches NO_LOCK, delete the lock file.
2180*/
drh308c2a52010-05-14 11:30:18 +00002181static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002182 unixFile *pFile = (unixFile*)id;
2183 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002184 int rc;
drh734c9862008-11-28 15:37:20 +00002185
2186 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002187 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002188 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002189 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002190
2191 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002192 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002193 return SQLITE_OK;
2194 }
drh7708e972008-11-29 00:56:52 +00002195
2196 /* To downgrade to shared, simply update our internal notion of the
2197 ** lock state. No need to mess with the file on disk.
2198 */
drh308c2a52010-05-14 11:30:18 +00002199 if( eFileLock==SHARED_LOCK ){
2200 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002201 return SQLITE_OK;
2202 }
2203
drh7708e972008-11-29 00:56:52 +00002204 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002205 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002206 rc = osRmdir(zLockFile);
2207 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2208 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002209 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002210 rc = 0;
drh734c9862008-11-28 15:37:20 +00002211 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002212 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002213 }
2214 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002215 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002216 }
2217 return rc;
2218 }
drh308c2a52010-05-14 11:30:18 +00002219 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002220 return SQLITE_OK;
2221}
2222
2223/*
drh9b35ea62008-11-29 02:20:26 +00002224** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002225*/
2226static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002227 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002228 if( id ){
2229 unixFile *pFile = (unixFile*)id;
2230 dotlockUnlock(id, NO_LOCK);
2231 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002232 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002233 }
drh734c9862008-11-28 15:37:20 +00002234 return rc;
2235}
2236/****************** End of the dot-file lock implementation *******************
2237******************************************************************************/
2238
2239/******************************************************************************
2240************************** Begin flock Locking ********************************
2241**
2242** Use the flock() system call to do file locking.
2243**
drh6b9d6dd2008-12-03 19:34:47 +00002244** flock() locking is like dot-file locking in that the various
2245** fine-grain locking levels supported by SQLite are collapsed into
2246** a single exclusive lock. In other words, SHARED, RESERVED, and
2247** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2248** still works when you do this, but concurrency is reduced since
2249** only a single process can be reading the database at a time.
2250**
drhe89b2912015-03-03 20:42:01 +00002251** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002252*/
drhe89b2912015-03-03 20:42:01 +00002253#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002254
drh6b9d6dd2008-12-03 19:34:47 +00002255/*
drhff812312011-02-23 13:33:46 +00002256** Retry flock() calls that fail with EINTR
2257*/
2258#ifdef EINTR
2259static int robust_flock(int fd, int op){
2260 int rc;
2261 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2262 return rc;
2263}
2264#else
drh5c819272011-02-23 14:00:12 +00002265# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002266#endif
2267
2268
2269/*
drh6b9d6dd2008-12-03 19:34:47 +00002270** This routine checks if there is a RESERVED lock held on the specified
2271** file by this or any other process. If such a lock is held, set *pResOut
2272** to a non-zero value otherwise *pResOut is set to zero. The return value
2273** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2274*/
drh734c9862008-11-28 15:37:20 +00002275static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2276 int rc = SQLITE_OK;
2277 int reserved = 0;
2278 unixFile *pFile = (unixFile*)id;
2279
2280 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2281
2282 assert( pFile );
2283
2284 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002285 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002286 reserved = 1;
2287 }
2288
2289 /* Otherwise see if some other process holds it. */
2290 if( !reserved ){
2291 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002292 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002293 if( !lrc ){
2294 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002295 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002296 if ( lrc ) {
2297 int tErrno = errno;
2298 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002299 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002300 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002301 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002302 rc = lrc;
2303 }
2304 }
2305 } else {
2306 int tErrno = errno;
2307 reserved = 1;
2308 /* someone else might have it reserved */
2309 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2310 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002311 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002312 rc = lrc;
2313 }
2314 }
2315 }
drh308c2a52010-05-14 11:30:18 +00002316 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002317
2318#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2319 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2320 rc = SQLITE_OK;
2321 reserved=1;
2322 }
2323#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2324 *pResOut = reserved;
2325 return rc;
2326}
2327
drh6b9d6dd2008-12-03 19:34:47 +00002328/*
drh308c2a52010-05-14 11:30:18 +00002329** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002330** of the following:
2331**
2332** (1) SHARED_LOCK
2333** (2) RESERVED_LOCK
2334** (3) PENDING_LOCK
2335** (4) EXCLUSIVE_LOCK
2336**
2337** Sometimes when requesting one lock state, additional lock states
2338** are inserted in between. The locking might fail on one of the later
2339** transitions leaving the lock state different from what it started but
2340** still short of its goal. The following chart shows the allowed
2341** transitions and the inserted intermediate states:
2342**
2343** UNLOCKED -> SHARED
2344** SHARED -> RESERVED
2345** SHARED -> (PENDING) -> EXCLUSIVE
2346** RESERVED -> (PENDING) -> EXCLUSIVE
2347** PENDING -> EXCLUSIVE
2348**
2349** flock() only really support EXCLUSIVE locks. We track intermediate
2350** lock states in the sqlite3_file structure, but all locks SHARED or
2351** above are really EXCLUSIVE locks and exclude all other processes from
2352** access the file.
2353**
2354** This routine will only increase a lock. Use the sqlite3OsUnlock()
2355** routine to lower a locking level.
2356*/
drh308c2a52010-05-14 11:30:18 +00002357static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002358 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002359 unixFile *pFile = (unixFile*)id;
2360
2361 assert( pFile );
2362
2363 /* if we already have a lock, it is exclusive.
2364 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002365 if (pFile->eFileLock > NO_LOCK) {
2366 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002367 return SQLITE_OK;
2368 }
2369
2370 /* grab an exclusive lock */
2371
drhff812312011-02-23 13:33:46 +00002372 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002373 int tErrno = errno;
2374 /* didn't get, must be busy */
2375 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2376 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002377 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002378 }
2379 } else {
2380 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002381 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002382 }
drh308c2a52010-05-14 11:30:18 +00002383 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2384 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002385#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2386 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2387 rc = SQLITE_BUSY;
2388 }
2389#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2390 return rc;
2391}
2392
drh6b9d6dd2008-12-03 19:34:47 +00002393
2394/*
drh308c2a52010-05-14 11:30:18 +00002395** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002396** must be either NO_LOCK or SHARED_LOCK.
2397**
2398** If the locking level of the file descriptor is already at or below
2399** the requested locking level, this routine is a no-op.
2400*/
drh308c2a52010-05-14 11:30:18 +00002401static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002402 unixFile *pFile = (unixFile*)id;
2403
2404 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002405 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002406 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002407 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002408
2409 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002410 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002411 return SQLITE_OK;
2412 }
2413
2414 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002415 if (eFileLock==SHARED_LOCK) {
2416 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002417 return SQLITE_OK;
2418 }
2419
2420 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002421 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002422#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002423 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002424#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002425 return SQLITE_IOERR_UNLOCK;
2426 }else{
drh308c2a52010-05-14 11:30:18 +00002427 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002428 return SQLITE_OK;
2429 }
2430}
2431
2432/*
2433** Close a file.
2434*/
2435static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002436 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002437 if( id ){
2438 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002439 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002440 }
drh5a05be12012-10-09 18:51:44 +00002441 return rc;
drh734c9862008-11-28 15:37:20 +00002442}
2443
2444#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2445
2446/******************* End of the flock lock implementation *********************
2447******************************************************************************/
2448
2449/******************************************************************************
2450************************ Begin Named Semaphore Locking ************************
2451**
2452** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002453**
2454** Semaphore locking is like dot-lock and flock in that it really only
2455** supports EXCLUSIVE locking. Only a single process can read or write
2456** the database file at a time. This reduces potential concurrency, but
2457** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002458*/
2459#if OS_VXWORKS
2460
drh6b9d6dd2008-12-03 19:34:47 +00002461/*
2462** This routine checks if there is a RESERVED lock held on the specified
2463** file by this or any other process. If such a lock is held, set *pResOut
2464** to a non-zero value otherwise *pResOut is set to zero. The return value
2465** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2466*/
drh8cd5b252015-03-02 22:06:43 +00002467static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002468 int rc = SQLITE_OK;
2469 int reserved = 0;
2470 unixFile *pFile = (unixFile*)id;
2471
2472 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2473
2474 assert( pFile );
2475
2476 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002477 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002478 reserved = 1;
2479 }
2480
2481 /* Otherwise see if some other process holds it. */
2482 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002483 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002484
2485 if( sem_trywait(pSem)==-1 ){
2486 int tErrno = errno;
2487 if( EAGAIN != tErrno ){
2488 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002489 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002490 } else {
2491 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002492 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002493 }
2494 }else{
2495 /* we could have it if we want it */
2496 sem_post(pSem);
2497 }
2498 }
drh308c2a52010-05-14 11:30:18 +00002499 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002500
2501 *pResOut = reserved;
2502 return rc;
2503}
2504
drh6b9d6dd2008-12-03 19:34:47 +00002505/*
drh308c2a52010-05-14 11:30:18 +00002506** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002507** of the following:
2508**
2509** (1) SHARED_LOCK
2510** (2) RESERVED_LOCK
2511** (3) PENDING_LOCK
2512** (4) EXCLUSIVE_LOCK
2513**
2514** Sometimes when requesting one lock state, additional lock states
2515** are inserted in between. The locking might fail on one of the later
2516** transitions leaving the lock state different from what it started but
2517** still short of its goal. The following chart shows the allowed
2518** transitions and the inserted intermediate states:
2519**
2520** UNLOCKED -> SHARED
2521** SHARED -> RESERVED
2522** SHARED -> (PENDING) -> EXCLUSIVE
2523** RESERVED -> (PENDING) -> EXCLUSIVE
2524** PENDING -> EXCLUSIVE
2525**
2526** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2527** lock states in the sqlite3_file structure, but all locks SHARED or
2528** above are really EXCLUSIVE locks and exclude all other processes from
2529** access the file.
2530**
2531** This routine will only increase a lock. Use the sqlite3OsUnlock()
2532** routine to lower a locking level.
2533*/
drh8cd5b252015-03-02 22:06:43 +00002534static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002535 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002536 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002537 int rc = SQLITE_OK;
2538
2539 /* if we already have a lock, it is exclusive.
2540 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002541 if (pFile->eFileLock > NO_LOCK) {
2542 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002543 rc = SQLITE_OK;
2544 goto sem_end_lock;
2545 }
2546
2547 /* lock semaphore now but bail out when already locked. */
2548 if( sem_trywait(pSem)==-1 ){
2549 rc = SQLITE_BUSY;
2550 goto sem_end_lock;
2551 }
2552
2553 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002554 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002555
2556 sem_end_lock:
2557 return rc;
2558}
2559
drh6b9d6dd2008-12-03 19:34:47 +00002560/*
drh308c2a52010-05-14 11:30:18 +00002561** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002562** must be either NO_LOCK or SHARED_LOCK.
2563**
2564** If the locking level of the file descriptor is already at or below
2565** the requested locking level, this routine is a no-op.
2566*/
drh8cd5b252015-03-02 22:06:43 +00002567static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002568 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002569 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002570
2571 assert( pFile );
2572 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002573 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002574 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002575 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002576
2577 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002578 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002579 return SQLITE_OK;
2580 }
2581
2582 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002583 if (eFileLock==SHARED_LOCK) {
2584 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002585 return SQLITE_OK;
2586 }
2587
2588 /* no, really unlock. */
2589 if ( sem_post(pSem)==-1 ) {
2590 int rc, tErrno = errno;
2591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2592 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002593 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002594 }
2595 return rc;
2596 }
drh308c2a52010-05-14 11:30:18 +00002597 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002598 return SQLITE_OK;
2599}
2600
2601/*
2602 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002603 */
drh8cd5b252015-03-02 22:06:43 +00002604static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002605 if( id ){
2606 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002607 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002608 assert( pFile );
2609 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002610 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002611 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002612 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002613 }
2614 return SQLITE_OK;
2615}
2616
2617#endif /* OS_VXWORKS */
2618/*
2619** Named semaphore locking is only available on VxWorks.
2620**
2621*************** End of the named semaphore lock implementation ****************
2622******************************************************************************/
2623
2624
2625/******************************************************************************
2626*************************** Begin AFP Locking *********************************
2627**
2628** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2629** on Apple Macintosh computers - both OS9 and OSX.
2630**
2631** Third-party implementations of AFP are available. But this code here
2632** only works on OSX.
2633*/
2634
drhd2cb50b2009-01-09 21:41:17 +00002635#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002636/*
2637** The afpLockingContext structure contains all afp lock specific state
2638*/
drhbfe66312006-10-03 17:40:40 +00002639typedef struct afpLockingContext afpLockingContext;
2640struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002641 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002642 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002643};
2644
2645struct ByteRangeLockPB2
2646{
2647 unsigned long long offset; /* offset to first byte to lock */
2648 unsigned long long length; /* nbr of bytes to lock */
2649 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2650 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2651 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2652 int fd; /* file desc to assoc this lock with */
2653};
2654
drhfd131da2007-08-07 17:13:03 +00002655#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002656
drh6b9d6dd2008-12-03 19:34:47 +00002657/*
2658** This is a utility for setting or clearing a bit-range lock on an
2659** AFP filesystem.
2660**
2661** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2662*/
2663static int afpSetLock(
2664 const char *path, /* Name of the file to be locked or unlocked */
2665 unixFile *pFile, /* Open file descriptor on path */
2666 unsigned long long offset, /* First byte to be locked */
2667 unsigned long long length, /* Number of bytes to lock */
2668 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002669){
drh6b9d6dd2008-12-03 19:34:47 +00002670 struct ByteRangeLockPB2 pb;
2671 int err;
drhbfe66312006-10-03 17:40:40 +00002672
2673 pb.unLockFlag = setLockFlag ? 0 : 1;
2674 pb.startEndFlag = 0;
2675 pb.offset = offset;
2676 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002677 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002678
drh308c2a52010-05-14 11:30:18 +00002679 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002680 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002681 offset, length));
drhbfe66312006-10-03 17:40:40 +00002682 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2683 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002684 int rc;
2685 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002686 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2687 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002688#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2689 rc = SQLITE_BUSY;
2690#else
drh734c9862008-11-28 15:37:20 +00002691 rc = sqliteErrorFromPosixError(tErrno,
2692 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002693#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002694 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002695 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002696 }
2697 return rc;
drhbfe66312006-10-03 17:40:40 +00002698 } else {
aswift5b1a2562008-08-22 00:22:35 +00002699 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002700 }
2701}
2702
drh6b9d6dd2008-12-03 19:34:47 +00002703/*
2704** This routine checks if there is a RESERVED lock held on the specified
2705** file by this or any other process. If such a lock is held, set *pResOut
2706** to a non-zero value otherwise *pResOut is set to zero. The return value
2707** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2708*/
danielk1977e339d652008-06-28 11:23:00 +00002709static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002710 int rc = SQLITE_OK;
2711 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002712 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002713 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002714
aswift5b1a2562008-08-22 00:22:35 +00002715 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2716
2717 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002718 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002719 if( context->reserved ){
2720 *pResOut = 1;
2721 return SQLITE_OK;
2722 }
drh8af6c222010-05-14 12:43:01 +00002723 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002724
2725 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002726 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002727 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002728 }
2729
2730 /* Otherwise see if some other process holds it.
2731 */
aswift5b1a2562008-08-22 00:22:35 +00002732 if( !reserved ){
2733 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002734 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002735 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002736 /* if we succeeded in taking the reserved lock, unlock it to restore
2737 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002738 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002739 } else {
2740 /* if we failed to get the lock then someone else must have it */
2741 reserved = 1;
2742 }
2743 if( IS_LOCK_ERROR(lrc) ){
2744 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002745 }
2746 }
drhbfe66312006-10-03 17:40:40 +00002747
drh7ed97b92010-01-20 13:07:21 +00002748 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002749 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002750
2751 *pResOut = reserved;
2752 return rc;
drhbfe66312006-10-03 17:40:40 +00002753}
2754
drh6b9d6dd2008-12-03 19:34:47 +00002755/*
drh308c2a52010-05-14 11:30:18 +00002756** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002757** of the following:
2758**
2759** (1) SHARED_LOCK
2760** (2) RESERVED_LOCK
2761** (3) PENDING_LOCK
2762** (4) EXCLUSIVE_LOCK
2763**
2764** Sometimes when requesting one lock state, additional lock states
2765** are inserted in between. The locking might fail on one of the later
2766** transitions leaving the lock state different from what it started but
2767** still short of its goal. The following chart shows the allowed
2768** transitions and the inserted intermediate states:
2769**
2770** UNLOCKED -> SHARED
2771** SHARED -> RESERVED
2772** SHARED -> (PENDING) -> EXCLUSIVE
2773** RESERVED -> (PENDING) -> EXCLUSIVE
2774** PENDING -> EXCLUSIVE
2775**
2776** This routine will only increase a lock. Use the sqlite3OsUnlock()
2777** routine to lower a locking level.
2778*/
drh308c2a52010-05-14 11:30:18 +00002779static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002780 int rc = SQLITE_OK;
2781 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002782 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002783 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002784
2785 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002786 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2787 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002788 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002789
drhbfe66312006-10-03 17:40:40 +00002790 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002791 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002792 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002793 */
drh308c2a52010-05-14 11:30:18 +00002794 if( pFile->eFileLock>=eFileLock ){
2795 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2796 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002797 return SQLITE_OK;
2798 }
2799
2800 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002801 ** (1) We never move from unlocked to anything higher than shared lock.
2802 ** (2) SQLite never explicitly requests a pendig lock.
2803 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002804 */
drh308c2a52010-05-14 11:30:18 +00002805 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2806 assert( eFileLock!=PENDING_LOCK );
2807 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002808
drh8af6c222010-05-14 12:43:01 +00002809 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002810 */
drh6c7d5c52008-11-21 20:32:33 +00002811 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002812 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002813
2814 /* If some thread using this PID has a lock via a different unixFile*
2815 ** handle that precludes the requested lock, return BUSY.
2816 */
drh8af6c222010-05-14 12:43:01 +00002817 if( (pFile->eFileLock!=pInode->eFileLock &&
2818 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002819 ){
2820 rc = SQLITE_BUSY;
2821 goto afp_end_lock;
2822 }
2823
2824 /* If a SHARED lock is requested, and some thread using this PID already
2825 ** has a SHARED or RESERVED lock, then increment reference counts and
2826 ** return SQLITE_OK.
2827 */
drh308c2a52010-05-14 11:30:18 +00002828 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002829 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002830 assert( eFileLock==SHARED_LOCK );
2831 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002832 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002833 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002834 pInode->nShared++;
2835 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002836 goto afp_end_lock;
2837 }
drhbfe66312006-10-03 17:40:40 +00002838
2839 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002840 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2841 ** be released.
2842 */
drh308c2a52010-05-14 11:30:18 +00002843 if( eFileLock==SHARED_LOCK
2844 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002845 ){
2846 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002847 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002848 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002849 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002850 goto afp_end_lock;
2851 }
2852 }
2853
2854 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002855 ** operating system calls for the specified lock.
2856 */
drh308c2a52010-05-14 11:30:18 +00002857 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002858 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002859 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002860
drh8af6c222010-05-14 12:43:01 +00002861 assert( pInode->nShared==0 );
2862 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002863
2864 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002865 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002866 /* note that the quality of the randomness doesn't matter that much */
2867 lk = random();
drh8af6c222010-05-14 12:43:01 +00002868 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002869 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002870 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002871 if( IS_LOCK_ERROR(lrc1) ){
2872 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002873 }
aswift5b1a2562008-08-22 00:22:35 +00002874 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002875 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002876
aswift5b1a2562008-08-22 00:22:35 +00002877 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002878 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002879 rc = lrc1;
2880 goto afp_end_lock;
2881 } else if( IS_LOCK_ERROR(lrc2) ){
2882 rc = lrc2;
2883 goto afp_end_lock;
2884 } else if( lrc1 != SQLITE_OK ) {
2885 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002886 } else {
drh308c2a52010-05-14 11:30:18 +00002887 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002888 pInode->nLock++;
2889 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002890 }
drh8af6c222010-05-14 12:43:01 +00002891 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002892 /* We are trying for an exclusive lock but another thread in this
2893 ** same process is still holding a shared lock. */
2894 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002895 }else{
2896 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2897 ** assumed that there is a SHARED or greater lock on the file
2898 ** already.
2899 */
2900 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002901 assert( 0!=pFile->eFileLock );
2902 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002903 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002904 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002905 if( !failed ){
2906 context->reserved = 1;
2907 }
drhbfe66312006-10-03 17:40:40 +00002908 }
drh308c2a52010-05-14 11:30:18 +00002909 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002910 /* Acquire an EXCLUSIVE lock */
2911
2912 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002913 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002914 */
drh6b9d6dd2008-12-03 19:34:47 +00002915 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002916 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002917 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002918 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002919 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002920 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002921 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002922 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002923 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2924 ** a critical I/O error
2925 */
2926 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2927 SQLITE_IOERR_LOCK;
2928 goto afp_end_lock;
2929 }
2930 }else{
aswift5b1a2562008-08-22 00:22:35 +00002931 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002932 }
2933 }
aswift5b1a2562008-08-22 00:22:35 +00002934 if( failed ){
2935 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002936 }
2937 }
2938
2939 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002940 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002941 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002942 }else if( eFileLock==EXCLUSIVE_LOCK ){
2943 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002944 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002945 }
2946
2947afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002948 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002949 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2950 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002951 return rc;
2952}
2953
2954/*
drh308c2a52010-05-14 11:30:18 +00002955** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002956** must be either NO_LOCK or SHARED_LOCK.
2957**
2958** If the locking level of the file descriptor is already at or below
2959** the requested locking level, this routine is a no-op.
2960*/
drh308c2a52010-05-14 11:30:18 +00002961static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002962 int rc = SQLITE_OK;
2963 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002964 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002965 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2966 int skipShared = 0;
2967#ifdef SQLITE_TEST
2968 int h = pFile->h;
2969#endif
drhbfe66312006-10-03 17:40:40 +00002970
2971 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002972 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002973 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002974 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002975
drh308c2a52010-05-14 11:30:18 +00002976 assert( eFileLock<=SHARED_LOCK );
2977 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002978 return SQLITE_OK;
2979 }
drh6c7d5c52008-11-21 20:32:33 +00002980 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002981 pInode = pFile->pInode;
2982 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002983 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002984 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002985 SimulateIOErrorBenign(1);
2986 SimulateIOError( h=(-1) )
2987 SimulateIOErrorBenign(0);
2988
drhd3d8c042012-05-29 17:02:40 +00002989#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002990 /* When reducing a lock such that other processes can start
2991 ** reading the database file again, make sure that the
2992 ** transaction counter was updated if any part of the database
2993 ** file changed. If the transaction counter is not updated,
2994 ** other connections to the same file might not realize that
2995 ** the file has changed and hence might not know to flush their
2996 ** cache. The use of a stale cache can lead to database corruption.
2997 */
2998 assert( pFile->inNormalWrite==0
2999 || pFile->dbUpdate==0
3000 || pFile->transCntrChng==1 );
3001 pFile->inNormalWrite = 0;
3002#endif
aswiftaebf4132008-11-21 00:10:35 +00003003
drh308c2a52010-05-14 11:30:18 +00003004 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003005 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003006 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003007 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003008 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003009 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3010 } else {
3011 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003012 }
3013 }
drh308c2a52010-05-14 11:30:18 +00003014 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003015 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003016 }
drh308c2a52010-05-14 11:30:18 +00003017 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003018 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3019 if( !rc ){
3020 context->reserved = 0;
3021 }
aswiftaebf4132008-11-21 00:10:35 +00003022 }
drh8af6c222010-05-14 12:43:01 +00003023 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3024 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003025 }
aswiftaebf4132008-11-21 00:10:35 +00003026 }
drh308c2a52010-05-14 11:30:18 +00003027 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003028
drh7ed97b92010-01-20 13:07:21 +00003029 /* Decrement the shared lock counter. Release the lock using an
3030 ** OS call only when all threads in this same process have released
3031 ** the lock.
3032 */
drh8af6c222010-05-14 12:43:01 +00003033 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3034 pInode->nShared--;
3035 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003036 SimulateIOErrorBenign(1);
3037 SimulateIOError( h=(-1) )
3038 SimulateIOErrorBenign(0);
3039 if( !skipShared ){
3040 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3041 }
3042 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003043 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003044 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003045 }
3046 }
3047 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003048 pInode->nLock--;
3049 assert( pInode->nLock>=0 );
3050 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003051 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003052 }
3053 }
drhbfe66312006-10-03 17:40:40 +00003054 }
drh7ed97b92010-01-20 13:07:21 +00003055
drh6c7d5c52008-11-21 20:32:33 +00003056 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003057 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003058 return rc;
3059}
3060
3061/*
drh339eb0b2008-03-07 15:34:11 +00003062** Close a file & cleanup AFP specific locking context
3063*/
danielk1977e339d652008-06-28 11:23:00 +00003064static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003065 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003066 if( id ){
3067 unixFile *pFile = (unixFile*)id;
3068 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003069 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003070 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003071 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003072 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003073 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003074 ** the last lock is cleared.
3075 */
dan08da86a2009-08-21 17:18:03 +00003076 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003077 }
danb0ac3e32010-06-16 10:55:42 +00003078 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003079 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003080 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003081 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003082 }
drh7ed97b92010-01-20 13:07:21 +00003083 return rc;
drhbfe66312006-10-03 17:40:40 +00003084}
3085
drhd2cb50b2009-01-09 21:41:17 +00003086#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003087/*
3088** The code above is the AFP lock implementation. The code is specific
3089** to MacOSX and does not work on other unix platforms. No alternative
3090** is available. If you don't compile for a mac, then the "unix-afp"
3091** VFS is not available.
3092**
3093********************* End of the AFP lock implementation **********************
3094******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003095
drh7ed97b92010-01-20 13:07:21 +00003096/******************************************************************************
3097*************************** Begin NFS Locking ********************************/
3098
3099#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3100/*
drh308c2a52010-05-14 11:30:18 +00003101 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003102 ** must be either NO_LOCK or SHARED_LOCK.
3103 **
3104 ** If the locking level of the file descriptor is already at or below
3105 ** the requested locking level, this routine is a no-op.
3106 */
drh308c2a52010-05-14 11:30:18 +00003107static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003108 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003109}
3110
3111#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3112/*
3113** The code above is the NFS lock implementation. The code is specific
3114** to MacOSX and does not work on other unix platforms. No alternative
3115** is available.
3116**
3117********************* End of the NFS lock implementation **********************
3118******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003119
3120/******************************************************************************
3121**************** Non-locking sqlite3_file methods *****************************
3122**
3123** The next division contains implementations for all methods of the
3124** sqlite3_file object other than the locking methods. The locking
3125** methods were defined in divisions above (one locking method per
3126** division). Those methods that are common to all locking modes
3127** are gather together into this division.
3128*/
drhbfe66312006-10-03 17:40:40 +00003129
3130/*
drh734c9862008-11-28 15:37:20 +00003131** Seek to the offset passed as the second argument, then read cnt
3132** bytes into pBuf. Return the number of bytes actually read.
3133**
3134** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3135** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3136** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003137** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003138** See tickets #2741 and #2681.
3139**
3140** To avoid stomping the errno value on a failed read the lastErrno value
3141** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003142*/
drh734c9862008-11-28 15:37:20 +00003143static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3144 int got;
drh58024642011-11-07 18:16:00 +00003145 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003146#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003147 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003148#endif
drh734c9862008-11-28 15:37:20 +00003149 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003150 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003151 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003152 do{
drh734c9862008-11-28 15:37:20 +00003153#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003154 got = osPread(id->h, pBuf, cnt, offset);
3155 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003156#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003157 got = osPread64(id->h, pBuf, cnt, offset);
3158 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003159#else
drh58024642011-11-07 18:16:00 +00003160 newOffset = lseek(id->h, offset, SEEK_SET);
3161 SimulateIOError( newOffset-- );
3162 if( newOffset!=offset ){
3163 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003164 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003165 }else{
drh4bf66fd2015-02-19 02:43:02 +00003166 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003167 }
3168 return -1;
drh734c9862008-11-28 15:37:20 +00003169 }
drh58024642011-11-07 18:16:00 +00003170 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003171#endif
drh58024642011-11-07 18:16:00 +00003172 if( got==cnt ) break;
3173 if( got<0 ){
3174 if( errno==EINTR ){ got = 1; continue; }
3175 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003176 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003177 break;
3178 }else if( got>0 ){
3179 cnt -= got;
3180 offset += got;
3181 prior += got;
3182 pBuf = (void*)(got + (char*)pBuf);
3183 }
3184 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003185 TIMER_END;
drh58024642011-11-07 18:16:00 +00003186 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3187 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3188 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003189}
3190
3191/*
drh734c9862008-11-28 15:37:20 +00003192** Read data from a file into a buffer. Return SQLITE_OK if all
3193** bytes were read successfully and SQLITE_IOERR if anything goes
3194** wrong.
drh339eb0b2008-03-07 15:34:11 +00003195*/
drh734c9862008-11-28 15:37:20 +00003196static int unixRead(
3197 sqlite3_file *id,
3198 void *pBuf,
3199 int amt,
3200 sqlite3_int64 offset
3201){
dan08da86a2009-08-21 17:18:03 +00003202 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003203 int got;
3204 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003205 assert( offset>=0 );
3206 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003207
dan08da86a2009-08-21 17:18:03 +00003208 /* If this is a database file (not a journal, master-journal or temp
3209 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003210#if 0
dane946c392009-08-22 11:39:46 +00003211 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003212 || offset>=PENDING_BYTE+512
3213 || offset+amt<=PENDING_BYTE
3214 );
dan7c246102010-04-12 19:00:29 +00003215#endif
drh08c6d442009-02-09 17:34:07 +00003216
drh9b4c59f2013-04-15 17:03:42 +00003217#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003218 /* Deal with as much of this read request as possible by transfering
3219 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003220 if( offset<pFile->mmapSize ){
3221 if( offset+amt <= pFile->mmapSize ){
3222 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3223 return SQLITE_OK;
3224 }else{
3225 int nCopy = pFile->mmapSize - offset;
3226 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3227 pBuf = &((u8 *)pBuf)[nCopy];
3228 amt -= nCopy;
3229 offset += nCopy;
3230 }
3231 }
drh6e0b6d52013-04-09 16:19:20 +00003232#endif
danf23da962013-03-23 21:00:41 +00003233
dan08da86a2009-08-21 17:18:03 +00003234 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003235 if( got==amt ){
3236 return SQLITE_OK;
3237 }else if( got<0 ){
3238 /* lastErrno set by seekAndRead */
3239 return SQLITE_IOERR_READ;
3240 }else{
drh4bf66fd2015-02-19 02:43:02 +00003241 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003242 /* Unread parts of the buffer must be zero-filled */
3243 memset(&((char*)pBuf)[got], 0, amt-got);
3244 return SQLITE_IOERR_SHORT_READ;
3245 }
3246}
3247
3248/*
dan47a2b4a2013-04-26 16:09:29 +00003249** Attempt to seek the file-descriptor passed as the first argument to
3250** absolute offset iOff, then attempt to write nBuf bytes of data from
3251** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3252** return the actual number of bytes written (which may be less than
3253** nBuf).
3254*/
3255static int seekAndWriteFd(
3256 int fd, /* File descriptor to write to */
3257 i64 iOff, /* File offset to begin writing at */
3258 const void *pBuf, /* Copy data from this buffer to the file */
3259 int nBuf, /* Size of buffer pBuf in bytes */
3260 int *piErrno /* OUT: Error number if error occurs */
3261){
3262 int rc = 0; /* Value returned by system call */
3263
3264 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003265 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003266 nBuf &= 0x1ffff;
3267 TIMER_START;
3268
3269#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003270 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003271#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003272 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003273#else
3274 do{
3275 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3276 SimulateIOError( iSeek-- );
3277
3278 if( iSeek!=iOff ){
3279 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3280 return -1;
3281 }
3282 rc = osWrite(fd, pBuf, nBuf);
3283 }while( rc<0 && errno==EINTR );
3284#endif
3285
3286 TIMER_END;
3287 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3288
3289 if( rc<0 && piErrno ) *piErrno = errno;
3290 return rc;
3291}
3292
3293
3294/*
drh734c9862008-11-28 15:37:20 +00003295** Seek to the offset in id->offset then read cnt bytes into pBuf.
3296** Return the number of bytes actually read. Update the offset.
3297**
3298** To avoid stomping the errno value on a failed write the lastErrno value
3299** is set before returning.
3300*/
3301static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003302 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003303}
3304
3305
3306/*
3307** Write data from a buffer into a file. Return SQLITE_OK on success
3308** or some other error code on failure.
3309*/
3310static int unixWrite(
3311 sqlite3_file *id,
3312 const void *pBuf,
3313 int amt,
3314 sqlite3_int64 offset
3315){
dan08da86a2009-08-21 17:18:03 +00003316 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003317 int wrote = 0;
3318 assert( id );
3319 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003320
dan08da86a2009-08-21 17:18:03 +00003321 /* If this is a database file (not a journal, master-journal or temp
3322 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003323#if 0
dane946c392009-08-22 11:39:46 +00003324 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003325 || offset>=PENDING_BYTE+512
3326 || offset+amt<=PENDING_BYTE
3327 );
dan7c246102010-04-12 19:00:29 +00003328#endif
drh08c6d442009-02-09 17:34:07 +00003329
drhd3d8c042012-05-29 17:02:40 +00003330#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003331 /* If we are doing a normal write to a database file (as opposed to
3332 ** doing a hot-journal rollback or a write to some file other than a
3333 ** normal database file) then record the fact that the database
3334 ** has changed. If the transaction counter is modified, record that
3335 ** fact too.
3336 */
dan08da86a2009-08-21 17:18:03 +00003337 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003338 pFile->dbUpdate = 1; /* The database has been modified */
3339 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003340 int rc;
drh8f941bc2009-01-14 23:03:40 +00003341 char oldCntr[4];
3342 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003343 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003344 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003345 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003346 pFile->transCntrChng = 1; /* The transaction counter has changed */
3347 }
3348 }
3349 }
3350#endif
3351
danfe33e392015-11-17 20:56:06 +00003352#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003353 /* Deal with as much of this write request as possible by transfering
3354 ** data from the memory mapping using memcpy(). */
3355 if( offset<pFile->mmapSize ){
3356 if( offset+amt <= pFile->mmapSize ){
3357 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3358 return SQLITE_OK;
3359 }else{
3360 int nCopy = pFile->mmapSize - offset;
3361 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3362 pBuf = &((u8 *)pBuf)[nCopy];
3363 amt -= nCopy;
3364 offset += nCopy;
3365 }
3366 }
drh6e0b6d52013-04-09 16:19:20 +00003367#endif
drh02bf8b42015-09-01 23:51:53 +00003368
3369 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003370 amt -= wrote;
3371 offset += wrote;
3372 pBuf = &((char*)pBuf)[wrote];
3373 }
3374 SimulateIOError(( wrote=(-1), amt=1 ));
3375 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003376
drh02bf8b42015-09-01 23:51:53 +00003377 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003378 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003379 /* lastErrno set by seekAndWrite */
3380 return SQLITE_IOERR_WRITE;
3381 }else{
drh4bf66fd2015-02-19 02:43:02 +00003382 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003383 return SQLITE_FULL;
3384 }
3385 }
dan6e09d692010-07-27 18:34:15 +00003386
drh734c9862008-11-28 15:37:20 +00003387 return SQLITE_OK;
3388}
3389
3390#ifdef SQLITE_TEST
3391/*
3392** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003393** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003394*/
3395int sqlite3_sync_count = 0;
3396int sqlite3_fullsync_count = 0;
3397#endif
3398
3399/*
drh89240432009-03-25 01:06:01 +00003400** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003401** Others do no. To be safe, we will stick with the (slightly slower)
3402** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003403** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003404*/
drhf7a4a1b2015-01-10 18:02:45 +00003405#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003406# define fdatasync fsync
3407#endif
3408
3409/*
3410** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3411** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3412** only available on Mac OS X. But that could change.
3413*/
3414#ifdef F_FULLFSYNC
3415# define HAVE_FULLFSYNC 1
3416#else
3417# define HAVE_FULLFSYNC 0
3418#endif
3419
3420
3421/*
3422** The fsync() system call does not work as advertised on many
3423** unix systems. The following procedure is an attempt to make
3424** it work better.
3425**
3426** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3427** for testing when we want to run through the test suite quickly.
3428** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3429** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3430** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003431**
3432** SQLite sets the dataOnly flag if the size of the file is unchanged.
3433** The idea behind dataOnly is that it should only write the file content
3434** to disk, not the inode. We only set dataOnly if the file size is
3435** unchanged since the file size is part of the inode. However,
3436** Ted Ts'o tells us that fdatasync() will also write the inode if the
3437** file size has changed. The only real difference between fdatasync()
3438** and fsync(), Ted tells us, is that fdatasync() will not flush the
3439** inode if the mtime or owner or other inode attributes have changed.
3440** We only care about the file size, not the other file attributes, so
3441** as far as SQLite is concerned, an fdatasync() is always adequate.
3442** So, we always use fdatasync() if it is available, regardless of
3443** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003444*/
3445static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003446 int rc;
drh734c9862008-11-28 15:37:20 +00003447
3448 /* The following "ifdef/elif/else/" block has the same structure as
3449 ** the one below. It is replicated here solely to avoid cluttering
3450 ** up the real code with the UNUSED_PARAMETER() macros.
3451 */
3452#ifdef SQLITE_NO_SYNC
3453 UNUSED_PARAMETER(fd);
3454 UNUSED_PARAMETER(fullSync);
3455 UNUSED_PARAMETER(dataOnly);
3456#elif HAVE_FULLFSYNC
3457 UNUSED_PARAMETER(dataOnly);
3458#else
3459 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003460 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003461#endif
3462
3463 /* Record the number of times that we do a normal fsync() and
3464 ** FULLSYNC. This is used during testing to verify that this procedure
3465 ** gets called with the correct arguments.
3466 */
3467#ifdef SQLITE_TEST
3468 if( fullSync ) sqlite3_fullsync_count++;
3469 sqlite3_sync_count++;
3470#endif
3471
3472 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3473 ** no-op
3474 */
3475#ifdef SQLITE_NO_SYNC
3476 rc = SQLITE_OK;
3477#elif HAVE_FULLFSYNC
3478 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003479 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003480 }else{
3481 rc = 1;
3482 }
3483 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003484 ** It shouldn't be possible for fullfsync to fail on the local
3485 ** file system (on OSX), so failure indicates that FULLFSYNC
3486 ** isn't supported for this file system. So, attempt an fsync
3487 ** and (for now) ignore the overhead of a superfluous fcntl call.
3488 ** It'd be better to detect fullfsync support once and avoid
3489 ** the fcntl call every time sync is called.
3490 */
drh734c9862008-11-28 15:37:20 +00003491 if( rc ) rc = fsync(fd);
3492
drh7ed97b92010-01-20 13:07:21 +00003493#elif defined(__APPLE__)
3494 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3495 ** so currently we default to the macro that redefines fdatasync to fsync
3496 */
3497 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003498#else
drh0b647ff2009-03-21 14:41:04 +00003499 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003500#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003501 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003502 rc = fsync(fd);
3503 }
drh0b647ff2009-03-21 14:41:04 +00003504#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003505#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3506
3507 if( OS_VXWORKS && rc!= -1 ){
3508 rc = 0;
3509 }
chw97185482008-11-17 08:05:31 +00003510 return rc;
drhbfe66312006-10-03 17:40:40 +00003511}
3512
drh734c9862008-11-28 15:37:20 +00003513/*
drh0059eae2011-08-08 23:48:40 +00003514** Open a file descriptor to the directory containing file zFilename.
3515** If successful, *pFd is set to the opened file descriptor and
3516** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3517** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3518** value.
3519**
drh90315a22011-08-10 01:52:12 +00003520** The directory file descriptor is used for only one thing - to
3521** fsync() a directory to make sure file creation and deletion events
3522** are flushed to disk. Such fsyncs are not needed on newer
3523** journaling filesystems, but are required on older filesystems.
3524**
3525** This routine can be overridden using the xSetSysCall interface.
3526** The ability to override this routine was added in support of the
3527** chromium sandbox. Opening a directory is a security risk (we are
3528** told) so making it overrideable allows the chromium sandbox to
3529** replace this routine with a harmless no-op. To make this routine
3530** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3531** *pFd set to a negative number.
3532**
drh0059eae2011-08-08 23:48:40 +00003533** If SQLITE_OK is returned, the caller is responsible for closing
3534** the file descriptor *pFd using close().
3535*/
3536static int openDirectory(const char *zFilename, int *pFd){
3537 int ii;
3538 int fd = -1;
3539 char zDirname[MAX_PATHNAME+1];
3540
3541 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3542 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3543 if( ii>0 ){
3544 zDirname[ii] = '\0';
3545 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3546 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003547 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3548 }
3549 }
3550 *pFd = fd;
3551 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3552}
3553
3554/*
drh734c9862008-11-28 15:37:20 +00003555** Make sure all writes to a particular file are committed to disk.
3556**
3557** If dataOnly==0 then both the file itself and its metadata (file
3558** size, access time, etc) are synced. If dataOnly!=0 then only the
3559** file data is synced.
3560**
3561** Under Unix, also make sure that the directory entry for the file
3562** has been created by fsync-ing the directory that contains the file.
3563** If we do not do this and we encounter a power failure, the directory
3564** entry for the journal might not exist after we reboot. The next
3565** SQLite to access the file will not know that the journal exists (because
3566** the directory entry for the journal was never created) and the transaction
3567** will not roll back - possibly leading to database corruption.
3568*/
3569static int unixSync(sqlite3_file *id, int flags){
3570 int rc;
3571 unixFile *pFile = (unixFile*)id;
3572
3573 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3574 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3575
3576 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3577 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3578 || (flags&0x0F)==SQLITE_SYNC_FULL
3579 );
3580
3581 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3582 ** line is to test that doing so does not cause any problems.
3583 */
3584 SimulateDiskfullError( return SQLITE_FULL );
3585
3586 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003587 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003588 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3589 SimulateIOError( rc=1 );
3590 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003591 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003592 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003593 }
drh0059eae2011-08-08 23:48:40 +00003594
3595 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003596 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003597 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003598 */
3599 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3600 int dirfd;
3601 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003602 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003603 rc = osOpenDirectory(pFile->zPath, &dirfd);
3604 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003605 full_fsync(dirfd, 0, 0);
3606 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003607 }else if( rc==SQLITE_CANTOPEN ){
3608 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003609 }
drh0059eae2011-08-08 23:48:40 +00003610 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003611 }
3612 return rc;
3613}
3614
3615/*
3616** Truncate an open file to a specified size
3617*/
3618static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003619 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003620 int rc;
dan6e09d692010-07-27 18:34:15 +00003621 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003622 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003623
3624 /* If the user has configured a chunk-size for this file, truncate the
3625 ** file so that it consists of an integer number of chunks (i.e. the
3626 ** actual file size after the operation may be larger than the requested
3627 ** size).
3628 */
drhb8af4b72012-04-05 20:04:39 +00003629 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003630 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3631 }
3632
dan2ee53412014-09-06 16:49:40 +00003633 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003634 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003635 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003636 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003637 }else{
drhd3d8c042012-05-29 17:02:40 +00003638#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003639 /* If we are doing a normal write to a database file (as opposed to
3640 ** doing a hot-journal rollback or a write to some file other than a
3641 ** normal database file) and we truncate the file to zero length,
3642 ** that effectively updates the change counter. This might happen
3643 ** when restoring a database using the backup API from a zero-length
3644 ** source.
3645 */
dan6e09d692010-07-27 18:34:15 +00003646 if( pFile->inNormalWrite && nByte==0 ){
3647 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003648 }
danf23da962013-03-23 21:00:41 +00003649#endif
danc0003312013-03-22 17:46:11 +00003650
mistachkine98844f2013-08-24 00:59:24 +00003651#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003652 /* If the file was just truncated to a size smaller than the currently
3653 ** mapped region, reduce the effective mapping size as well. SQLite will
3654 ** use read() and write() to access data beyond this point from now on.
3655 */
3656 if( nByte<pFile->mmapSize ){
3657 pFile->mmapSize = nByte;
3658 }
mistachkine98844f2013-08-24 00:59:24 +00003659#endif
drh3313b142009-11-06 04:13:18 +00003660
drh734c9862008-11-28 15:37:20 +00003661 return SQLITE_OK;
3662 }
3663}
3664
3665/*
3666** Determine the current size of a file in bytes
3667*/
3668static int unixFileSize(sqlite3_file *id, i64 *pSize){
3669 int rc;
3670 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003671 assert( id );
3672 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003673 SimulateIOError( rc=1 );
3674 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003675 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003676 return SQLITE_IOERR_FSTAT;
3677 }
3678 *pSize = buf.st_size;
3679
drh8af6c222010-05-14 12:43:01 +00003680 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003681 ** writes a single byte into that file in order to work around a bug
3682 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3683 ** layers, we need to report this file size as zero even though it is
3684 ** really 1. Ticket #3260.
3685 */
3686 if( *pSize==1 ) *pSize = 0;
3687
3688
3689 return SQLITE_OK;
3690}
3691
drhd2cb50b2009-01-09 21:41:17 +00003692#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003693/*
3694** Handler for proxy-locking file-control verbs. Defined below in the
3695** proxying locking division.
3696*/
3697static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003698#endif
drh715ff302008-12-03 22:32:44 +00003699
dan502019c2010-07-28 14:26:17 +00003700/*
3701** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003702** file-control operation. Enlarge the database to nBytes in size
3703** (rounded up to the next chunk-size). If the database is already
3704** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003705*/
3706static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003707 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003708 i64 nSize; /* Required file size */
3709 struct stat buf; /* Used to hold return values of fstat() */
3710
drh4bf66fd2015-02-19 02:43:02 +00003711 if( osFstat(pFile->h, &buf) ){
3712 return SQLITE_IOERR_FSTAT;
3713 }
dan502019c2010-07-28 14:26:17 +00003714
3715 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3716 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003717
dan502019c2010-07-28 14:26:17 +00003718#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003719 /* The code below is handling the return value of osFallocate()
3720 ** correctly. posix_fallocate() is defined to "returns zero on success,
3721 ** or an error number on failure". See the manpage for details. */
3722 int err;
drhff812312011-02-23 13:33:46 +00003723 do{
dan661d71a2011-03-30 19:08:03 +00003724 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3725 }while( err==EINTR );
3726 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003727#else
dan592bf7f2014-12-30 19:58:31 +00003728 /* If the OS does not have posix_fallocate(), fake it. Write a
3729 ** single byte to the last byte in each block that falls entirely
3730 ** within the extended region. Then, if required, a single byte
3731 ** at offset (nSize-1), to set the size of the file correctly.
3732 ** This is a similar technique to that used by glibc on systems
3733 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003734 */
3735 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003736 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003737 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003738
dan502019c2010-07-28 14:26:17 +00003739 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003740 assert( iWrite>=buf.st_size );
3741 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3742 assert( ((iWrite+1)%nBlk)==0 );
3743 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003744 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003745 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003746 }
danef3d66c2015-01-06 21:31:47 +00003747 if( nWrite==0 || (nSize%nBlk) ){
3748 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003749 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003750 }
dan502019c2010-07-28 14:26:17 +00003751#endif
3752 }
3753 }
3754
mistachkine98844f2013-08-24 00:59:24 +00003755#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003756 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003757 int rc;
3758 if( pFile->szChunk<=0 ){
3759 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003760 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003761 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3762 }
3763 }
3764
3765 rc = unixMapfile(pFile, nByte);
3766 return rc;
3767 }
mistachkine98844f2013-08-24 00:59:24 +00003768#endif
danf23da962013-03-23 21:00:41 +00003769
dan502019c2010-07-28 14:26:17 +00003770 return SQLITE_OK;
3771}
danielk1977ad94b582007-08-20 06:44:22 +00003772
danielk1977e3026632004-06-22 11:29:02 +00003773/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003774** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003775** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3776**
3777** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3778*/
3779static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3780 if( *pArg<0 ){
3781 *pArg = (pFile->ctrlFlags & mask)!=0;
3782 }else if( (*pArg)==0 ){
3783 pFile->ctrlFlags &= ~mask;
3784 }else{
3785 pFile->ctrlFlags |= mask;
3786 }
3787}
3788
drh696b33e2012-12-06 19:01:42 +00003789/* Forward declaration */
3790static int unixGetTempname(int nBuf, char *zBuf);
3791
drhf12b3f62011-12-21 14:42:29 +00003792/*
drh9e33c2c2007-08-31 18:34:59 +00003793** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003794*/
drhcc6bb3e2007-08-31 16:11:35 +00003795static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003796 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003797 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003798 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003799 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003800 return SQLITE_OK;
3801 }
drh9e33c2c2007-08-31 18:34:59 +00003802 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003803 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003804 return SQLITE_OK;
3805 }
drh4bf66fd2015-02-19 02:43:02 +00003806 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003807 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003808 return SQLITE_OK;
3809 }
dan6e09d692010-07-27 18:34:15 +00003810 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003811 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003812 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003813 }
drh9ff27ec2010-05-19 19:26:05 +00003814 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003815 int rc;
3816 SimulateIOErrorBenign(1);
3817 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3818 SimulateIOErrorBenign(0);
3819 return rc;
drhf0b190d2011-07-26 16:03:07 +00003820 }
3821 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003822 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3823 return SQLITE_OK;
3824 }
drhcb15f352011-12-23 01:04:17 +00003825 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3826 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003827 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003828 }
drhde60fc22011-12-14 17:53:36 +00003829 case SQLITE_FCNTL_VFSNAME: {
3830 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3831 return SQLITE_OK;
3832 }
drh696b33e2012-12-06 19:01:42 +00003833 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003834 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003835 if( zTFile ){
3836 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3837 *(char**)pArg = zTFile;
3838 }
3839 return SQLITE_OK;
3840 }
drhb959a012013-12-07 12:29:22 +00003841 case SQLITE_FCNTL_HAS_MOVED: {
3842 *(int*)pArg = fileHasMoved(pFile);
3843 return SQLITE_OK;
3844 }
mistachkine98844f2013-08-24 00:59:24 +00003845#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003846 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003847 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003848 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003849 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3850 newLimit = sqlite3GlobalConfig.mxMmap;
3851 }
3852 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003853 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003854 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003855 if( pFile->mmapSize>0 ){
3856 unixUnmapfile(pFile);
3857 rc = unixMapfile(pFile, -1);
3858 }
danbcb8a862013-04-08 15:30:41 +00003859 }
drh34e258c2013-05-23 01:40:53 +00003860 return rc;
danb2d3de32013-03-14 18:34:37 +00003861 }
mistachkine98844f2013-08-24 00:59:24 +00003862#endif
drhd3d8c042012-05-29 17:02:40 +00003863#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003864 /* The pager calls this method to signal that it has done
3865 ** a rollback and that the database is therefore unchanged and
3866 ** it hence it is OK for the transaction change counter to be
3867 ** unchanged.
3868 */
3869 case SQLITE_FCNTL_DB_UNCHANGED: {
3870 ((unixFile*)id)->dbUpdate = 0;
3871 return SQLITE_OK;
3872 }
3873#endif
drhd2cb50b2009-01-09 21:41:17 +00003874#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003875 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3876 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003877 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003878 }
drhd2cb50b2009-01-09 21:41:17 +00003879#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003880 }
drh0b52b7d2011-01-26 19:46:22 +00003881 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003882}
3883
3884/*
danielk1977a3d4c882007-03-23 10:08:38 +00003885** Return the sector size in bytes of the underlying block device for
3886** the specified file. This is almost always 512 bytes, but may be
3887** larger for some devices.
3888**
3889** SQLite code assumes this function cannot fail. It also assumes that
3890** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003891** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003892** same for both.
3893*/
drh537dddf2012-10-26 13:46:24 +00003894#ifndef __QNXNTO__
3895static int unixSectorSize(sqlite3_file *NotUsed){
3896 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003897 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003898}
drh537dddf2012-10-26 13:46:24 +00003899#endif
3900
3901/*
3902** The following version of unixSectorSize() is optimized for QNX.
3903*/
3904#ifdef __QNXNTO__
3905#include <sys/dcmd_blk.h>
3906#include <sys/statvfs.h>
3907static int unixSectorSize(sqlite3_file *id){
3908 unixFile *pFile = (unixFile*)id;
3909 if( pFile->sectorSize == 0 ){
3910 struct statvfs fsInfo;
3911
3912 /* Set defaults for non-supported filesystems */
3913 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3914 pFile->deviceCharacteristics = 0;
3915 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3916 return pFile->sectorSize;
3917 }
3918
3919 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3920 pFile->sectorSize = fsInfo.f_bsize;
3921 pFile->deviceCharacteristics =
3922 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3923 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3924 ** the write succeeds */
3925 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3926 ** so it is ordered */
3927 0;
3928 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3929 pFile->sectorSize = fsInfo.f_bsize;
3930 pFile->deviceCharacteristics =
3931 /* etfs cluster size writes are atomic */
3932 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3933 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3934 ** the write succeeds */
3935 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3936 ** so it is ordered */
3937 0;
3938 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3939 pFile->sectorSize = fsInfo.f_bsize;
3940 pFile->deviceCharacteristics =
3941 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3942 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3943 ** the write succeeds */
3944 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3945 ** so it is ordered */
3946 0;
3947 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3948 pFile->sectorSize = fsInfo.f_bsize;
3949 pFile->deviceCharacteristics =
3950 /* full bitset of atomics from max sector size and smaller */
3951 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3952 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3953 ** so it is ordered */
3954 0;
3955 }else if( strstr(fsInfo.f_basetype, "dos") ){
3956 pFile->sectorSize = fsInfo.f_bsize;
3957 pFile->deviceCharacteristics =
3958 /* full bitset of atomics from max sector size and smaller */
3959 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3960 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3961 ** so it is ordered */
3962 0;
3963 }else{
3964 pFile->deviceCharacteristics =
3965 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3966 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3967 ** the write succeeds */
3968 0;
3969 }
3970 }
3971 /* Last chance verification. If the sector size isn't a multiple of 512
3972 ** then it isn't valid.*/
3973 if( pFile->sectorSize % 512 != 0 ){
3974 pFile->deviceCharacteristics = 0;
3975 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3976 }
3977 return pFile->sectorSize;
3978}
3979#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003980
danielk197790949c22007-08-17 16:50:38 +00003981/*
drhf12b3f62011-12-21 14:42:29 +00003982** Return the device characteristics for the file.
3983**
drhcb15f352011-12-23 01:04:17 +00003984** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003985** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003986** file system does not always provide powersafe overwrites. (In other
3987** words, after a power-loss event, parts of the file that were never
3988** written might end up being altered.) However, non-PSOW behavior is very,
3989** very rare. And asserting PSOW makes a large reduction in the amount
3990** of required I/O for journaling, since a lot of padding is eliminated.
3991** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3992** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003993*/
drhf12b3f62011-12-21 14:42:29 +00003994static int unixDeviceCharacteristics(sqlite3_file *id){
3995 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003996 int rc = 0;
3997#ifdef __QNXNTO__
3998 if( p->sectorSize==0 ) unixSectorSize(id);
3999 rc = p->deviceCharacteristics;
4000#endif
drhcb15f352011-12-23 01:04:17 +00004001 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00004002 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00004003 }
drh537dddf2012-10-26 13:46:24 +00004004 return rc;
danielk197762079062007-08-15 17:08:46 +00004005}
4006
dan702eec12014-06-23 10:04:58 +00004007#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004008
dan702eec12014-06-23 10:04:58 +00004009/*
4010** Return the system page size.
4011**
4012** This function should not be called directly by other code in this file.
4013** Instead, it should be called via macro osGetpagesize().
4014*/
4015static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004016#if OS_VXWORKS
4017 return 1024;
4018#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004019 return getpagesize();
4020#else
4021 return (int)sysconf(_SC_PAGESIZE);
4022#endif
4023}
4024
4025#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4026
4027#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004028
4029/*
drhd91c68f2010-05-14 14:52:25 +00004030** Object used to represent an shared memory buffer.
4031**
4032** When multiple threads all reference the same wal-index, each thread
4033** has its own unixShm object, but they all point to a single instance
4034** of this unixShmNode object. In other words, each wal-index is opened
4035** only once per process.
4036**
4037** Each unixShmNode object is connected to a single unixInodeInfo object.
4038** We could coalesce this object into unixInodeInfo, but that would mean
4039** every open file that does not use shared memory (in other words, most
4040** open files) would have to carry around this extra information. So
4041** the unixInodeInfo object contains a pointer to this unixShmNode object
4042** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004043**
4044** unixMutexHeld() must be true when creating or destroying
4045** this object or while reading or writing the following fields:
4046**
4047** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004048**
4049** The following fields are read-only after the object is created:
4050**
4051** fid
4052** zFilename
4053**
drhd91c68f2010-05-14 14:52:25 +00004054** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004055** unixMutexHeld() is true when reading or writing any other field
4056** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004057*/
drhd91c68f2010-05-14 14:52:25 +00004058struct unixShmNode {
4059 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004060 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004061 char *zFilename; /* Name of the mmapped file */
4062 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004063 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004064 u16 nRegion; /* Size of array apRegion */
4065 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004066 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004067 int nRef; /* Number of unixShm objects pointing to this */
4068 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004069#ifdef SQLITE_DEBUG
4070 u8 exclMask; /* Mask of exclusive locks held */
4071 u8 sharedMask; /* Mask of shared locks held */
4072 u8 nextShmId; /* Next available unixShm.id value */
4073#endif
4074};
4075
4076/*
drhd9e5c4f2010-05-12 18:01:39 +00004077** Structure used internally by this VFS to record the state of an
4078** open shared memory connection.
4079**
drhd91c68f2010-05-14 14:52:25 +00004080** The following fields are initialized when this object is created and
4081** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004082**
drhd91c68f2010-05-14 14:52:25 +00004083** unixShm.pFile
4084** unixShm.id
4085**
4086** All other fields are read/write. The unixShm.pFile->mutex must be held
4087** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004088*/
4089struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004090 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4091 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004092 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004093 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004094 u16 sharedMask; /* Mask of shared locks held */
4095 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004096};
4097
4098/*
drhd9e5c4f2010-05-12 18:01:39 +00004099** Constants used for locking
4100*/
drhbd9676c2010-06-23 17:58:38 +00004101#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004102#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004103
drhd9e5c4f2010-05-12 18:01:39 +00004104/*
drh73b64e42010-05-30 19:55:15 +00004105** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004106**
4107** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4108** otherwise.
4109*/
4110static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004111 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004112 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004113 int ofst, /* First byte of the locking range */
4114 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004115){
drhbbf76ee2015-03-10 20:22:35 +00004116 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4117 struct flock f; /* The posix advisory locking structure */
4118 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004119
drhd91c68f2010-05-14 14:52:25 +00004120 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004121 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004122 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004123
drh73b64e42010-05-30 19:55:15 +00004124 /* Shared locks never span more than one byte */
4125 assert( n==1 || lockType!=F_RDLCK );
4126
4127 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004128 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004129
drh3cb93392011-03-12 18:10:44 +00004130 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004131 int lkType;
drh3cb93392011-03-12 18:10:44 +00004132 /* Initialize the locking parameters */
4133 memset(&f, 0, sizeof(f));
4134 f.l_type = lockType;
4135 f.l_whence = SEEK_SET;
4136 f.l_start = ofst;
4137 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004138
drhbbf76ee2015-03-10 20:22:35 +00004139 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4140 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004141 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004142 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004143 }
drhd9e5c4f2010-05-12 18:01:39 +00004144
4145 /* Update the global lock state and do debug tracing */
4146#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004147 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004148 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004149 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004150 if( rc==SQLITE_OK ){
4151 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004152 OSTRACE(("unlock %d ok", ofst));
4153 pShmNode->exclMask &= ~mask;
4154 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004155 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004156 OSTRACE(("read-lock %d ok", ofst));
4157 pShmNode->exclMask &= ~mask;
4158 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004159 }else{
4160 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004161 OSTRACE(("write-lock %d ok", ofst));
4162 pShmNode->exclMask |= mask;
4163 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004164 }
4165 }else{
4166 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004167 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004168 }else if( lockType==F_RDLCK ){
4169 OSTRACE(("read-lock failed"));
4170 }else{
4171 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004172 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004173 }
4174 }
drh20e1f082010-05-31 16:10:12 +00004175 OSTRACE((" - afterwards %03x,%03x\n",
4176 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004177 }
drhd9e5c4f2010-05-12 18:01:39 +00004178#endif
4179
4180 return rc;
4181}
4182
dan781e34c2014-03-20 08:59:47 +00004183/*
dan781e34c2014-03-20 08:59:47 +00004184** Return the minimum number of 32KB shm regions that should be mapped at
4185** a time, assuming that each mapping must be an integer multiple of the
4186** current system page-size.
4187**
4188** Usually, this is 1. The exception seems to be systems that are configured
4189** to use 64KB pages - in this case each mapping must cover at least two
4190** shm regions.
4191*/
4192static int unixShmRegionPerMap(void){
4193 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004194 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004195 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4196 if( pgsz<shmsz ) return 1;
4197 return pgsz/shmsz;
4198}
drhd9e5c4f2010-05-12 18:01:39 +00004199
4200/*
drhd91c68f2010-05-14 14:52:25 +00004201** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004202**
4203** This is not a VFS shared-memory method; it is a utility function called
4204** by VFS shared-memory methods.
4205*/
drhd91c68f2010-05-14 14:52:25 +00004206static void unixShmPurge(unixFile *pFd){
4207 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004208 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004209 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004210 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004211 int i;
drhd91c68f2010-05-14 14:52:25 +00004212 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004213 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004214 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004215 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004216 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004217 }else{
4218 sqlite3_free(p->apRegion[i]);
4219 }
dan13a3cb82010-06-11 19:04:21 +00004220 }
dan18801912010-06-14 14:07:50 +00004221 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004222 if( p->h>=0 ){
4223 robust_close(pFd, p->h, __LINE__);
4224 p->h = -1;
4225 }
drhd91c68f2010-05-14 14:52:25 +00004226 p->pInode->pShmNode = 0;
4227 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004228 }
4229}
4230
4231/*
danda9fe0c2010-07-13 18:44:03 +00004232** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004233** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004234**
drh7234c6d2010-06-19 15:10:09 +00004235** The file used to implement shared-memory is in the same directory
4236** as the open database file and has the same name as the open database
4237** file with the "-shm" suffix added. For example, if the database file
4238** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004239** for shared memory will be called "/home/user1/config.db-shm".
4240**
4241** Another approach to is to use files in /dev/shm or /dev/tmp or an
4242** some other tmpfs mount. But if a file in a different directory
4243** from the database file is used, then differing access permissions
4244** or a chroot() might cause two different processes on the same
4245** database to end up using different files for shared memory -
4246** meaning that their memory would not really be shared - resulting
4247** in database corruption. Nevertheless, this tmpfs file usage
4248** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4249** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4250** option results in an incompatible build of SQLite; builds of SQLite
4251** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4252** same database file at the same time, database corruption will likely
4253** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4254** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004255**
4256** When opening a new shared-memory file, if no other instances of that
4257** file are currently open, in this process or in other processes, then
4258** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004259**
4260** If the original database file (pDbFd) is using the "unix-excl" VFS
4261** that means that an exclusive lock is held on the database file and
4262** that no other processes are able to read or write the database. In
4263** that case, we do not really need shared memory. No shared memory
4264** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004265*/
danda9fe0c2010-07-13 18:44:03 +00004266static int unixOpenSharedMemory(unixFile *pDbFd){
4267 struct unixShm *p = 0; /* The connection to be opened */
4268 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4269 int rc; /* Result code */
4270 unixInodeInfo *pInode; /* The inode of fd */
4271 char *zShmFilename; /* Name of the file used for SHM */
4272 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004273
danda9fe0c2010-07-13 18:44:03 +00004274 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004275 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004276 if( p==0 ) return SQLITE_NOMEM;
4277 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004278 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004279
danda9fe0c2010-07-13 18:44:03 +00004280 /* Check to see if a unixShmNode object already exists. Reuse an existing
4281 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004282 */
4283 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004284 pInode = pDbFd->pInode;
4285 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004286 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004287 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004288#ifndef SQLITE_SHM_DIRECTORY
4289 const char *zBasePath = pDbFd->zPath;
4290#endif
danddb0ac42010-07-14 14:48:58 +00004291
4292 /* Call fstat() to figure out the permissions on the database file. If
4293 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004294 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004295 */
drh3cb93392011-03-12 18:10:44 +00004296 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004297 rc = SQLITE_IOERR_FSTAT;
4298 goto shm_open_err;
4299 }
4300
drha4ced192010-07-15 18:32:40 +00004301#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004302 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004303#else
drh4bf66fd2015-02-19 02:43:02 +00004304 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004305#endif
drhf3cdcdc2015-04-29 16:50:28 +00004306 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004307 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004308 rc = SQLITE_NOMEM;
4309 goto shm_open_err;
4310 }
drh9cb5a0d2012-01-05 21:19:54 +00004311 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004312 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004313#ifdef SQLITE_SHM_DIRECTORY
4314 sqlite3_snprintf(nShmFilename, zShmFilename,
4315 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4316 (u32)sStat.st_ino, (u32)sStat.st_dev);
4317#else
drh4bf66fd2015-02-19 02:43:02 +00004318 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004319 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004320#endif
drhd91c68f2010-05-14 14:52:25 +00004321 pShmNode->h = -1;
4322 pDbFd->pInode->pShmNode = pShmNode;
4323 pShmNode->pInode = pDbFd->pInode;
4324 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4325 if( pShmNode->mutex==0 ){
4326 rc = SQLITE_NOMEM;
4327 goto shm_open_err;
4328 }
drhd9e5c4f2010-05-12 18:01:39 +00004329
drh3cb93392011-03-12 18:10:44 +00004330 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004331 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004332 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004333 openFlags = O_RDONLY;
4334 pShmNode->isReadonly = 1;
4335 }
4336 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004337 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004338 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4339 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004340 }
drhac7c3ac2012-02-11 19:23:48 +00004341
4342 /* If this process is running as root, make sure that the SHM file
4343 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004344 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004345 */
drhed466822012-05-31 13:10:49 +00004346 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004347
4348 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004349 ** If not, truncate the file to zero length.
4350 */
4351 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004352 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004353 if( robust_ftruncate(pShmNode->h, 0) ){
4354 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004355 }
4356 }
drh66dfec8b2011-06-01 20:01:49 +00004357 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004358 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004359 }
4360 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004361 }
drhd9e5c4f2010-05-12 18:01:39 +00004362 }
4363
drhd91c68f2010-05-14 14:52:25 +00004364 /* Make the new connection a child of the unixShmNode */
4365 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004366#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004367 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004368#endif
drhd91c68f2010-05-14 14:52:25 +00004369 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004370 pDbFd->pShm = p;
4371 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004372
4373 /* The reference count on pShmNode has already been incremented under
4374 ** the cover of the unixEnterMutex() mutex and the pointer from the
4375 ** new (struct unixShm) object to the pShmNode has been set. All that is
4376 ** left to do is to link the new object into the linked list starting
4377 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4378 ** mutex.
4379 */
4380 sqlite3_mutex_enter(pShmNode->mutex);
4381 p->pNext = pShmNode->pFirst;
4382 pShmNode->pFirst = p;
4383 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004384 return SQLITE_OK;
4385
4386 /* Jump here on any error */
4387shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004388 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004389 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004390 unixLeaveMutex();
4391 return rc;
4392}
4393
4394/*
danda9fe0c2010-07-13 18:44:03 +00004395** This function is called to obtain a pointer to region iRegion of the
4396** shared-memory associated with the database file fd. Shared-memory regions
4397** are numbered starting from zero. Each shared-memory region is szRegion
4398** bytes in size.
4399**
4400** If an error occurs, an error code is returned and *pp is set to NULL.
4401**
4402** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4403** region has not been allocated (by any client, including one running in a
4404** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4405** bExtend is non-zero and the requested shared-memory region has not yet
4406** been allocated, it is allocated by this function.
4407**
4408** If the shared-memory region has already been allocated or is allocated by
4409** this call as described above, then it is mapped into this processes
4410** address space (if it is not already), *pp is set to point to the mapped
4411** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004412*/
danda9fe0c2010-07-13 18:44:03 +00004413static int unixShmMap(
4414 sqlite3_file *fd, /* Handle open on database file */
4415 int iRegion, /* Region to retrieve */
4416 int szRegion, /* Size of regions */
4417 int bExtend, /* True to extend file if necessary */
4418 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004419){
danda9fe0c2010-07-13 18:44:03 +00004420 unixFile *pDbFd = (unixFile*)fd;
4421 unixShm *p;
4422 unixShmNode *pShmNode;
4423 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004424 int nShmPerMap = unixShmRegionPerMap();
4425 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004426
danda9fe0c2010-07-13 18:44:03 +00004427 /* If the shared-memory file has not yet been opened, open it now. */
4428 if( pDbFd->pShm==0 ){
4429 rc = unixOpenSharedMemory(pDbFd);
4430 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004431 }
drhd9e5c4f2010-05-12 18:01:39 +00004432
danda9fe0c2010-07-13 18:44:03 +00004433 p = pDbFd->pShm;
4434 pShmNode = p->pShmNode;
4435 sqlite3_mutex_enter(pShmNode->mutex);
4436 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004437 assert( pShmNode->pInode==pDbFd->pInode );
4438 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4439 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004440
dan781e34c2014-03-20 08:59:47 +00004441 /* Minimum number of regions required to be mapped. */
4442 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4443
4444 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004445 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004446 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004447 struct stat sStat; /* Used by fstat() */
4448
4449 pShmNode->szRegion = szRegion;
4450
drh3cb93392011-03-12 18:10:44 +00004451 if( pShmNode->h>=0 ){
4452 /* The requested region is not mapped into this processes address space.
4453 ** Check to see if it has been allocated (i.e. if the wal-index file is
4454 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004455 */
drh3cb93392011-03-12 18:10:44 +00004456 if( osFstat(pShmNode->h, &sStat) ){
4457 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004458 goto shmpage_out;
4459 }
drh3cb93392011-03-12 18:10:44 +00004460
4461 if( sStat.st_size<nByte ){
4462 /* The requested memory region does not exist. If bExtend is set to
4463 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004464 */
dan47a2b4a2013-04-26 16:09:29 +00004465 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004466 goto shmpage_out;
4467 }
dan47a2b4a2013-04-26 16:09:29 +00004468
4469 /* Alternatively, if bExtend is true, extend the file. Do this by
4470 ** writing a single byte to the end of each (OS) page being
4471 ** allocated or extended. Technically, we need only write to the
4472 ** last page in order to extend the file. But writing to all new
4473 ** pages forces the OS to allocate them immediately, which reduces
4474 ** the chances of SIGBUS while accessing the mapped region later on.
4475 */
4476 else{
4477 static const int pgsz = 4096;
4478 int iPg;
4479
4480 /* Write to the last byte of each newly allocated or extended page */
4481 assert( (nByte % pgsz)==0 );
4482 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4483 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4484 const char *zFile = pShmNode->zFilename;
4485 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4486 goto shmpage_out;
4487 }
4488 }
drh3cb93392011-03-12 18:10:44 +00004489 }
4490 }
danda9fe0c2010-07-13 18:44:03 +00004491 }
4492
4493 /* Map the requested memory region into this processes address space. */
4494 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004495 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004496 );
4497 if( !apNew ){
4498 rc = SQLITE_IOERR_NOMEM;
4499 goto shmpage_out;
4500 }
4501 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004502 while( pShmNode->nRegion<nReqRegion ){
4503 int nMap = szRegion*nShmPerMap;
4504 int i;
drh3cb93392011-03-12 18:10:44 +00004505 void *pMem;
4506 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004507 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004508 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004509 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004510 );
4511 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004512 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004513 goto shmpage_out;
4514 }
4515 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004516 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004517 if( pMem==0 ){
4518 rc = SQLITE_NOMEM;
4519 goto shmpage_out;
4520 }
4521 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004522 }
dan781e34c2014-03-20 08:59:47 +00004523
4524 for(i=0; i<nShmPerMap; i++){
4525 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4526 }
4527 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004528 }
4529 }
4530
4531shmpage_out:
4532 if( pShmNode->nRegion>iRegion ){
4533 *pp = pShmNode->apRegion[iRegion];
4534 }else{
4535 *pp = 0;
4536 }
drh66dfec8b2011-06-01 20:01:49 +00004537 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004538 sqlite3_mutex_leave(pShmNode->mutex);
4539 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004540}
4541
4542/*
drhd9e5c4f2010-05-12 18:01:39 +00004543** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004544**
4545** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4546** different here than in posix. In xShmLock(), one can go from unlocked
4547** to shared and back or from unlocked to exclusive and back. But one may
4548** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004549*/
4550static int unixShmLock(
4551 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004552 int ofst, /* First lock to acquire or release */
4553 int n, /* Number of locks to acquire or release */
4554 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004555){
drh73b64e42010-05-30 19:55:15 +00004556 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4557 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4558 unixShm *pX; /* For looping over all siblings */
4559 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4560 int rc = SQLITE_OK; /* Result code */
4561 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004562
drhd91c68f2010-05-14 14:52:25 +00004563 assert( pShmNode==pDbFd->pInode->pShmNode );
4564 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004565 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004566 assert( n>=1 );
4567 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4568 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4569 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4570 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4571 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004572 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4573 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004574
drhc99597c2010-05-31 01:41:15 +00004575 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004576 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004577 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004578 if( flags & SQLITE_SHM_UNLOCK ){
4579 u16 allMask = 0; /* Mask of locks held by siblings */
4580
4581 /* See if any siblings hold this same lock */
4582 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4583 if( pX==p ) continue;
4584 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4585 allMask |= pX->sharedMask;
4586 }
4587
4588 /* Unlock the system-level locks */
4589 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004590 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004591 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004592 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004593 }
drh73b64e42010-05-30 19:55:15 +00004594
4595 /* Undo the local locks */
4596 if( rc==SQLITE_OK ){
4597 p->exclMask &= ~mask;
4598 p->sharedMask &= ~mask;
4599 }
4600 }else if( flags & SQLITE_SHM_SHARED ){
4601 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4602
4603 /* Find out which shared locks are already held by sibling connections.
4604 ** If any sibling already holds an exclusive lock, go ahead and return
4605 ** SQLITE_BUSY.
4606 */
4607 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004608 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004609 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004610 break;
4611 }
4612 allShared |= pX->sharedMask;
4613 }
4614
4615 /* Get shared locks at the system level, if necessary */
4616 if( rc==SQLITE_OK ){
4617 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004618 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004619 }else{
drh73b64e42010-05-30 19:55:15 +00004620 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004621 }
drhd9e5c4f2010-05-12 18:01:39 +00004622 }
drh73b64e42010-05-30 19:55:15 +00004623
4624 /* Get the local shared locks */
4625 if( rc==SQLITE_OK ){
4626 p->sharedMask |= mask;
4627 }
4628 }else{
4629 /* Make sure no sibling connections hold locks that will block this
4630 ** lock. If any do, return SQLITE_BUSY right away.
4631 */
4632 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004633 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4634 rc = SQLITE_BUSY;
4635 break;
4636 }
4637 }
4638
4639 /* Get the exclusive locks at the system level. Then if successful
4640 ** also mark the local connection as being locked.
4641 */
4642 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004643 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004644 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004645 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004646 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004647 }
drhd9e5c4f2010-05-12 18:01:39 +00004648 }
4649 }
drhd91c68f2010-05-14 14:52:25 +00004650 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004651 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004652 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004653 return rc;
4654}
4655
drh286a2882010-05-20 23:51:06 +00004656/*
4657** Implement a memory barrier or memory fence on shared memory.
4658**
4659** All loads and stores begun before the barrier must complete before
4660** any load or store begun after the barrier.
4661*/
4662static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004663 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004664){
drhff828942010-06-26 21:34:06 +00004665 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004666 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4667 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004668 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004669}
4670
dan18801912010-06-14 14:07:50 +00004671/*
danda9fe0c2010-07-13 18:44:03 +00004672** Close a connection to shared-memory. Delete the underlying
4673** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004674**
4675** If there is no shared memory associated with the connection then this
4676** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004677*/
danda9fe0c2010-07-13 18:44:03 +00004678static int unixShmUnmap(
4679 sqlite3_file *fd, /* The underlying database file */
4680 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004681){
danda9fe0c2010-07-13 18:44:03 +00004682 unixShm *p; /* The connection to be closed */
4683 unixShmNode *pShmNode; /* The underlying shared-memory file */
4684 unixShm **pp; /* For looping over sibling connections */
4685 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004686
danda9fe0c2010-07-13 18:44:03 +00004687 pDbFd = (unixFile*)fd;
4688 p = pDbFd->pShm;
4689 if( p==0 ) return SQLITE_OK;
4690 pShmNode = p->pShmNode;
4691
4692 assert( pShmNode==pDbFd->pInode->pShmNode );
4693 assert( pShmNode->pInode==pDbFd->pInode );
4694
4695 /* Remove connection p from the set of connections associated
4696 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004697 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004698 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4699 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004700
danda9fe0c2010-07-13 18:44:03 +00004701 /* Free the connection p */
4702 sqlite3_free(p);
4703 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004704 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004705
4706 /* If pShmNode->nRef has reached 0, then close the underlying
4707 ** shared-memory file, too */
4708 unixEnterMutex();
4709 assert( pShmNode->nRef>0 );
4710 pShmNode->nRef--;
4711 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004712 if( deleteFlag && pShmNode->h>=0 ){
4713 osUnlink(pShmNode->zFilename);
4714 }
danda9fe0c2010-07-13 18:44:03 +00004715 unixShmPurge(pDbFd);
4716 }
4717 unixLeaveMutex();
4718
4719 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004720}
drh286a2882010-05-20 23:51:06 +00004721
danda9fe0c2010-07-13 18:44:03 +00004722
drhd9e5c4f2010-05-12 18:01:39 +00004723#else
drh6b017cc2010-06-14 18:01:46 +00004724# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004725# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004726# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004727# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004728#endif /* #ifndef SQLITE_OMIT_WAL */
4729
mistachkine98844f2013-08-24 00:59:24 +00004730#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004731/*
danaef49d72013-03-25 16:28:54 +00004732** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004733*/
danf23da962013-03-23 21:00:41 +00004734static void unixUnmapfile(unixFile *pFd){
4735 assert( pFd->nFetchOut==0 );
4736 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004737 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004738 pFd->pMapRegion = 0;
4739 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004740 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004741 }
4742}
dan5d8a1372013-03-19 19:28:06 +00004743
danaef49d72013-03-25 16:28:54 +00004744/*
dane6ecd662013-04-01 17:56:59 +00004745** Attempt to set the size of the memory mapping maintained by file
4746** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4747**
4748** If successful, this function sets the following variables:
4749**
4750** unixFile.pMapRegion
4751** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004752** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004753**
4754** If unsuccessful, an error message is logged via sqlite3_log() and
4755** the three variables above are zeroed. In this case SQLite should
4756** continue accessing the database using the xRead() and xWrite()
4757** methods.
4758*/
4759static void unixRemapfile(
4760 unixFile *pFd, /* File descriptor object */
4761 i64 nNew /* Required mapping size */
4762){
dan4ff7bc42013-04-02 12:04:09 +00004763 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004764 int h = pFd->h; /* File descriptor open on db file */
4765 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004766 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004767 u8 *pNew = 0; /* Location of new mapping */
4768 int flags = PROT_READ; /* Flags to pass to mmap() */
4769
4770 assert( pFd->nFetchOut==0 );
4771 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004772 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004773 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004774 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004775 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004776
danfe33e392015-11-17 20:56:06 +00004777#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004778 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004779#endif
dane6ecd662013-04-01 17:56:59 +00004780
4781 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004782#if HAVE_MREMAP
4783 i64 nReuse = pFd->mmapSize;
4784#else
danbc760632014-03-20 09:42:09 +00004785 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004786 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004787#endif
dane6ecd662013-04-01 17:56:59 +00004788 u8 *pReq = &pOrig[nReuse];
4789
4790 /* Unmap any pages of the existing mapping that cannot be reused. */
4791 if( nReuse!=nOrig ){
4792 osMunmap(pReq, nOrig-nReuse);
4793 }
4794
4795#if HAVE_MREMAP
4796 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004797 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004798#else
4799 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4800 if( pNew!=MAP_FAILED ){
4801 if( pNew!=pReq ){
4802 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004803 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004804 }else{
4805 pNew = pOrig;
4806 }
4807 }
4808#endif
4809
dan48ccef82013-04-02 20:55:01 +00004810 /* The attempt to extend the existing mapping failed. Free it. */
4811 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004812 osMunmap(pOrig, nReuse);
4813 }
4814 }
4815
4816 /* If pNew is still NULL, try to create an entirely new mapping. */
4817 if( pNew==0 ){
4818 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004819 }
4820
dan4ff7bc42013-04-02 12:04:09 +00004821 if( pNew==MAP_FAILED ){
4822 pNew = 0;
4823 nNew = 0;
4824 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4825
4826 /* If the mmap() above failed, assume that all subsequent mmap() calls
4827 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4828 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004829 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004830 }
dane6ecd662013-04-01 17:56:59 +00004831 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004832 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004833}
4834
4835/*
danaef49d72013-03-25 16:28:54 +00004836** Memory map or remap the file opened by file-descriptor pFd (if the file
4837** is already mapped, the existing mapping is replaced by the new). Or, if
4838** there already exists a mapping for this file, and there are still
4839** outstanding xFetch() references to it, this function is a no-op.
4840**
4841** If parameter nByte is non-negative, then it is the requested size of
4842** the mapping to create. Otherwise, if nByte is less than zero, then the
4843** requested size is the size of the file on disk. The actual size of the
4844** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004845** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004846**
4847** SQLITE_OK is returned if no error occurs (even if the mapping is not
4848** recreated as a result of outstanding references) or an SQLite error
4849** code otherwise.
4850*/
danf23da962013-03-23 21:00:41 +00004851static int unixMapfile(unixFile *pFd, i64 nByte){
4852 i64 nMap = nByte;
4853 int rc;
daneb97b292013-03-20 14:26:59 +00004854
danf23da962013-03-23 21:00:41 +00004855 assert( nMap>=0 || pFd->nFetchOut==0 );
4856 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4857
4858 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004859 struct stat statbuf; /* Low-level file information */
4860 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004861 if( rc!=SQLITE_OK ){
4862 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004863 }
drh3044b512014-06-16 16:41:52 +00004864 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004865 }
drh9b4c59f2013-04-15 17:03:42 +00004866 if( nMap>pFd->mmapSizeMax ){
4867 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004868 }
4869
danf23da962013-03-23 21:00:41 +00004870 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004871 if( nMap>0 ){
4872 unixRemapfile(pFd, nMap);
4873 }else{
danb7e3a322013-03-25 20:30:13 +00004874 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004875 }
4876 }
4877
danf23da962013-03-23 21:00:41 +00004878 return SQLITE_OK;
4879}
mistachkine98844f2013-08-24 00:59:24 +00004880#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004881
danaef49d72013-03-25 16:28:54 +00004882/*
4883** If possible, return a pointer to a mapping of file fd starting at offset
4884** iOff. The mapping must be valid for at least nAmt bytes.
4885**
4886** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4887** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4888** Finally, if an error does occur, return an SQLite error code. The final
4889** value of *pp is undefined in this case.
4890**
4891** If this function does return a pointer, the caller must eventually
4892** release the reference by calling unixUnfetch().
4893*/
danf23da962013-03-23 21:00:41 +00004894static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004895#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004896 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004897#endif
danf23da962013-03-23 21:00:41 +00004898 *pp = 0;
4899
drh9b4c59f2013-04-15 17:03:42 +00004900#if SQLITE_MAX_MMAP_SIZE>0
4901 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004902 if( pFd->pMapRegion==0 ){
4903 int rc = unixMapfile(pFd, -1);
4904 if( rc!=SQLITE_OK ) return rc;
4905 }
4906 if( pFd->mmapSize >= iOff+nAmt ){
4907 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4908 pFd->nFetchOut++;
4909 }
4910 }
drh6e0b6d52013-04-09 16:19:20 +00004911#endif
danf23da962013-03-23 21:00:41 +00004912 return SQLITE_OK;
4913}
4914
danaef49d72013-03-25 16:28:54 +00004915/*
dandf737fe2013-03-25 17:00:24 +00004916** If the third argument is non-NULL, then this function releases a
4917** reference obtained by an earlier call to unixFetch(). The second
4918** argument passed to this function must be the same as the corresponding
4919** argument that was passed to the unixFetch() invocation.
4920**
4921** Or, if the third argument is NULL, then this function is being called
4922** to inform the VFS layer that, according to POSIX, any existing mapping
4923** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004924*/
dandf737fe2013-03-25 17:00:24 +00004925static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004926#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004927 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004928 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004929
danaef49d72013-03-25 16:28:54 +00004930 /* If p==0 (unmap the entire file) then there must be no outstanding
4931 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4932 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004933 assert( (p==0)==(pFd->nFetchOut==0) );
4934
dandf737fe2013-03-25 17:00:24 +00004935 /* If p!=0, it must match the iOff value. */
4936 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4937
danf23da962013-03-23 21:00:41 +00004938 if( p ){
4939 pFd->nFetchOut--;
4940 }else{
4941 unixUnmapfile(pFd);
4942 }
4943
4944 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004945#else
4946 UNUSED_PARAMETER(fd);
4947 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004948 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004949#endif
danf23da962013-03-23 21:00:41 +00004950 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004951}
4952
4953/*
drh734c9862008-11-28 15:37:20 +00004954** Here ends the implementation of all sqlite3_file methods.
4955**
4956********************** End sqlite3_file Methods *******************************
4957******************************************************************************/
4958
4959/*
drh6b9d6dd2008-12-03 19:34:47 +00004960** This division contains definitions of sqlite3_io_methods objects that
4961** implement various file locking strategies. It also contains definitions
4962** of "finder" functions. A finder-function is used to locate the appropriate
4963** sqlite3_io_methods object for a particular database file. The pAppData
4964** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4965** the correct finder-function for that VFS.
4966**
4967** Most finder functions return a pointer to a fixed sqlite3_io_methods
4968** object. The only interesting finder-function is autolockIoFinder, which
4969** looks at the filesystem type and tries to guess the best locking
4970** strategy from that.
4971**
peter.d.reid60ec9142014-09-06 16:39:46 +00004972** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004973**
4974** (1) The real finder-function named "FImpt()".
4975**
dane946c392009-08-22 11:39:46 +00004976** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004977**
4978**
4979** A pointer to the F pointer is used as the pAppData value for VFS
4980** objects. We have to do this instead of letting pAppData point
4981** directly at the finder-function since C90 rules prevent a void*
4982** from be cast into a function pointer.
4983**
drh6b9d6dd2008-12-03 19:34:47 +00004984**
drh7708e972008-11-29 00:56:52 +00004985** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004986**
drh7708e972008-11-29 00:56:52 +00004987** * A constant sqlite3_io_methods object call METHOD that has locking
4988** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4989**
4990** * An I/O method finder function called FINDER that returns a pointer
4991** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004992*/
drhe6d41732015-02-21 00:49:00 +00004993#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004994static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004995 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004996 CLOSE, /* xClose */ \
4997 unixRead, /* xRead */ \
4998 unixWrite, /* xWrite */ \
4999 unixTruncate, /* xTruncate */ \
5000 unixSync, /* xSync */ \
5001 unixFileSize, /* xFileSize */ \
5002 LOCK, /* xLock */ \
5003 UNLOCK, /* xUnlock */ \
5004 CKLOCK, /* xCheckReservedLock */ \
5005 unixFileControl, /* xFileControl */ \
5006 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005007 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005008 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005009 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005010 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005011 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005012 unixFetch, /* xFetch */ \
5013 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005014}; \
drh0c2694b2009-09-03 16:23:44 +00005015static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5016 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005017 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005018} \
drh0c2694b2009-09-03 16:23:44 +00005019static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005020 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005021
5022/*
5023** Here are all of the sqlite3_io_methods objects for each of the
5024** locking strategies. Functions that return pointers to these methods
5025** are also created.
5026*/
5027IOMETHODS(
5028 posixIoFinder, /* Finder function name */
5029 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005030 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005031 unixClose, /* xClose method */
5032 unixLock, /* xLock method */
5033 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005034 unixCheckReservedLock, /* xCheckReservedLock method */
5035 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005036)
drh7708e972008-11-29 00:56:52 +00005037IOMETHODS(
5038 nolockIoFinder, /* Finder function name */
5039 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005040 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005041 nolockClose, /* xClose method */
5042 nolockLock, /* xLock method */
5043 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005044 nolockCheckReservedLock, /* xCheckReservedLock method */
5045 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005046)
drh7708e972008-11-29 00:56:52 +00005047IOMETHODS(
5048 dotlockIoFinder, /* Finder function name */
5049 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005050 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005051 dotlockClose, /* xClose method */
5052 dotlockLock, /* xLock method */
5053 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005054 dotlockCheckReservedLock, /* xCheckReservedLock method */
5055 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005056)
drh7708e972008-11-29 00:56:52 +00005057
drhe89b2912015-03-03 20:42:01 +00005058#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005059IOMETHODS(
5060 flockIoFinder, /* Finder function name */
5061 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005062 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005063 flockClose, /* xClose method */
5064 flockLock, /* xLock method */
5065 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005066 flockCheckReservedLock, /* xCheckReservedLock method */
5067 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005068)
drh7708e972008-11-29 00:56:52 +00005069#endif
5070
drh6c7d5c52008-11-21 20:32:33 +00005071#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005072IOMETHODS(
5073 semIoFinder, /* Finder function name */
5074 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005075 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005076 semXClose, /* xClose method */
5077 semXLock, /* xLock method */
5078 semXUnlock, /* xUnlock method */
5079 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005080 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005081)
aswiftaebf4132008-11-21 00:10:35 +00005082#endif
drh7708e972008-11-29 00:56:52 +00005083
drhd2cb50b2009-01-09 21:41:17 +00005084#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005085IOMETHODS(
5086 afpIoFinder, /* Finder function name */
5087 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005088 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005089 afpClose, /* xClose method */
5090 afpLock, /* xLock method */
5091 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005092 afpCheckReservedLock, /* xCheckReservedLock method */
5093 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005094)
drh715ff302008-12-03 22:32:44 +00005095#endif
5096
5097/*
5098** The proxy locking method is a "super-method" in the sense that it
5099** opens secondary file descriptors for the conch and lock files and
5100** it uses proxy, dot-file, AFP, and flock() locking methods on those
5101** secondary files. For this reason, the division that implements
5102** proxy locking is located much further down in the file. But we need
5103** to go ahead and define the sqlite3_io_methods and finder function
5104** for proxy locking here. So we forward declare the I/O methods.
5105*/
drhd2cb50b2009-01-09 21:41:17 +00005106#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005107static int proxyClose(sqlite3_file*);
5108static int proxyLock(sqlite3_file*, int);
5109static int proxyUnlock(sqlite3_file*, int);
5110static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005111IOMETHODS(
5112 proxyIoFinder, /* Finder function name */
5113 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005114 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005115 proxyClose, /* xClose method */
5116 proxyLock, /* xLock method */
5117 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005118 proxyCheckReservedLock, /* xCheckReservedLock method */
5119 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005120)
aswiftaebf4132008-11-21 00:10:35 +00005121#endif
drh7708e972008-11-29 00:56:52 +00005122
drh7ed97b92010-01-20 13:07:21 +00005123/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5124#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5125IOMETHODS(
5126 nfsIoFinder, /* Finder function name */
5127 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005128 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005129 unixClose, /* xClose method */
5130 unixLock, /* xLock method */
5131 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005132 unixCheckReservedLock, /* xCheckReservedLock method */
5133 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005134)
5135#endif
drh7708e972008-11-29 00:56:52 +00005136
drhd2cb50b2009-01-09 21:41:17 +00005137#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005138/*
drh6b9d6dd2008-12-03 19:34:47 +00005139** This "finder" function attempts to determine the best locking strategy
5140** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005141** object that implements that strategy.
5142**
5143** This is for MacOSX only.
5144*/
drh1875f7a2008-12-08 18:19:17 +00005145static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005146 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005147 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005148){
5149 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005150 const char *zFilesystem; /* Filesystem type name */
5151 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005152 } aMap[] = {
5153 { "hfs", &posixIoMethods },
5154 { "ufs", &posixIoMethods },
5155 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005156 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005157 { "webdav", &nolockIoMethods },
5158 { 0, 0 }
5159 };
5160 int i;
5161 struct statfs fsInfo;
5162 struct flock lockInfo;
5163
5164 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005165 /* If filePath==NULL that means we are dealing with a transient file
5166 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005167 return &nolockIoMethods;
5168 }
5169 if( statfs(filePath, &fsInfo) != -1 ){
5170 if( fsInfo.f_flags & MNT_RDONLY ){
5171 return &nolockIoMethods;
5172 }
5173 for(i=0; aMap[i].zFilesystem; i++){
5174 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5175 return aMap[i].pMethods;
5176 }
5177 }
5178 }
5179
5180 /* Default case. Handles, amongst others, "nfs".
5181 ** Test byte-range lock using fcntl(). If the call succeeds,
5182 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005183 */
drh7708e972008-11-29 00:56:52 +00005184 lockInfo.l_len = 1;
5185 lockInfo.l_start = 0;
5186 lockInfo.l_whence = SEEK_SET;
5187 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005188 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005189 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5190 return &nfsIoMethods;
5191 } else {
5192 return &posixIoMethods;
5193 }
drh7708e972008-11-29 00:56:52 +00005194 }else{
5195 return &dotlockIoMethods;
5196 }
5197}
drh0c2694b2009-09-03 16:23:44 +00005198static const sqlite3_io_methods
5199 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005200
drhd2cb50b2009-01-09 21:41:17 +00005201#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005202
drhe89b2912015-03-03 20:42:01 +00005203#if OS_VXWORKS
5204/*
5205** This "finder" function for VxWorks checks to see if posix advisory
5206** locking works. If it does, then that is what is used. If it does not
5207** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005208*/
drhe89b2912015-03-03 20:42:01 +00005209static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005210 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005211 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005212){
5213 struct flock lockInfo;
5214
5215 if( !filePath ){
5216 /* If filePath==NULL that means we are dealing with a transient file
5217 ** that does not need to be locked. */
5218 return &nolockIoMethods;
5219 }
5220
5221 /* Test if fcntl() is supported and use POSIX style locks.
5222 ** Otherwise fall back to the named semaphore method.
5223 */
5224 lockInfo.l_len = 1;
5225 lockInfo.l_start = 0;
5226 lockInfo.l_whence = SEEK_SET;
5227 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005228 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005229 return &posixIoMethods;
5230 }else{
5231 return &semIoMethods;
5232 }
5233}
drh0c2694b2009-09-03 16:23:44 +00005234static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005235 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005236
drhe89b2912015-03-03 20:42:01 +00005237#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005238
drh7708e972008-11-29 00:56:52 +00005239/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005240** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005241*/
drh0c2694b2009-09-03 16:23:44 +00005242typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005243
aswiftaebf4132008-11-21 00:10:35 +00005244
drh734c9862008-11-28 15:37:20 +00005245/****************************************************************************
5246**************************** sqlite3_vfs methods ****************************
5247**
5248** This division contains the implementation of methods on the
5249** sqlite3_vfs object.
5250*/
5251
danielk1977a3d4c882007-03-23 10:08:38 +00005252/*
danielk1977e339d652008-06-28 11:23:00 +00005253** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005254*/
5255static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005256 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005257 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005258 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005259 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005260 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005261){
drh7708e972008-11-29 00:56:52 +00005262 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005263 unixFile *pNew = (unixFile *)pId;
5264 int rc = SQLITE_OK;
5265
drh8af6c222010-05-14 12:43:01 +00005266 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005267
dan00157392010-10-05 11:33:15 +00005268 /* Usually the path zFilename should not be a relative pathname. The
5269 ** exception is when opening the proxy "conch" file in builds that
5270 ** include the special Apple locking styles.
5271 */
dan00157392010-10-05 11:33:15 +00005272#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005273 assert( zFilename==0 || zFilename[0]=='/'
5274 || pVfs->pAppData==(void*)&autolockIoFinder );
5275#else
5276 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005277#endif
dan00157392010-10-05 11:33:15 +00005278
drhb07028f2011-10-14 21:49:18 +00005279 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005280 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005281
drh308c2a52010-05-14 11:30:18 +00005282 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005283 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005284 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005285 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005286 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005287#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005288 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005289#endif
drhc02a43a2012-01-10 23:18:38 +00005290 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5291 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005292 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005293 }
drh503a6862013-03-01 01:07:17 +00005294 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005295 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005296 }
drh339eb0b2008-03-07 15:34:11 +00005297
drh6c7d5c52008-11-21 20:32:33 +00005298#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005299 pNew->pId = vxworksFindFileId(zFilename);
5300 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005301 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005302 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005303 }
5304#endif
5305
drhc02a43a2012-01-10 23:18:38 +00005306 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005307 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005308 }else{
drh0c2694b2009-09-03 16:23:44 +00005309 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005310#if SQLITE_ENABLE_LOCKING_STYLE
5311 /* Cache zFilename in the locking context (AFP and dotlock override) for
5312 ** proxyLock activation is possible (remote proxy is based on db name)
5313 ** zFilename remains valid until file is closed, to support */
5314 pNew->lockingContext = (void*)zFilename;
5315#endif
drhda0e7682008-07-30 15:27:54 +00005316 }
danielk1977e339d652008-06-28 11:23:00 +00005317
drh7ed97b92010-01-20 13:07:21 +00005318 if( pLockingStyle == &posixIoMethods
5319#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5320 || pLockingStyle == &nfsIoMethods
5321#endif
5322 ){
drh7708e972008-11-29 00:56:52 +00005323 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005324 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005325 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005326 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005327 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005328 ** in two scenarios:
5329 **
5330 ** (a) A call to fstat() failed.
5331 ** (b) A malloc failed.
5332 **
5333 ** Scenario (b) may only occur if the process is holding no other
5334 ** file descriptors open on the same file. If there were other file
5335 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005336 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005337 ** handle h - as it is guaranteed that no posix locks will be released
5338 ** by doing so.
5339 **
5340 ** If scenario (a) caused the error then things are not so safe. The
5341 ** implicit assumption here is that if fstat() fails, things are in
5342 ** such bad shape that dropping a lock or two doesn't matter much.
5343 */
drh0e9365c2011-03-02 02:08:13 +00005344 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005345 h = -1;
5346 }
drh7708e972008-11-29 00:56:52 +00005347 unixLeaveMutex();
5348 }
danielk1977e339d652008-06-28 11:23:00 +00005349
drhd2cb50b2009-01-09 21:41:17 +00005350#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005351 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005352 /* AFP locking uses the file path so it needs to be included in
5353 ** the afpLockingContext.
5354 */
5355 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005356 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005357 if( pCtx==0 ){
5358 rc = SQLITE_NOMEM;
5359 }else{
5360 /* NB: zFilename exists and remains valid until the file is closed
5361 ** according to requirement F11141. So we do not need to make a
5362 ** copy of the filename. */
5363 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005364 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005365 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005366 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005367 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005368 if( rc!=SQLITE_OK ){
5369 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005370 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005371 h = -1;
5372 }
drh7708e972008-11-29 00:56:52 +00005373 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005374 }
drh7708e972008-11-29 00:56:52 +00005375 }
5376#endif
danielk1977e339d652008-06-28 11:23:00 +00005377
drh7708e972008-11-29 00:56:52 +00005378 else if( pLockingStyle == &dotlockIoMethods ){
5379 /* Dotfile locking uses the file path so it needs to be included in
5380 ** the dotlockLockingContext
5381 */
5382 char *zLockFile;
5383 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005384 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005385 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005386 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005387 if( zLockFile==0 ){
5388 rc = SQLITE_NOMEM;
5389 }else{
5390 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005391 }
drh7708e972008-11-29 00:56:52 +00005392 pNew->lockingContext = zLockFile;
5393 }
danielk1977e339d652008-06-28 11:23:00 +00005394
drh6c7d5c52008-11-21 20:32:33 +00005395#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005396 else if( pLockingStyle == &semIoMethods ){
5397 /* Named semaphore locking uses the file path so it needs to be
5398 ** included in the semLockingContext
5399 */
5400 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005401 rc = findInodeInfo(pNew, &pNew->pInode);
5402 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5403 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005404 int n;
drh2238dcc2009-08-27 17:56:20 +00005405 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005406 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005407 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005408 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005409 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5410 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005411 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005412 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005413 }
chw97185482008-11-17 08:05:31 +00005414 }
drh7708e972008-11-29 00:56:52 +00005415 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005416 }
drh7708e972008-11-29 00:56:52 +00005417#endif
aswift5b1a2562008-08-22 00:22:35 +00005418
drh4bf66fd2015-02-19 02:43:02 +00005419 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005420#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005421 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005422 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005423 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005424 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005425 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005426 }
chw97185482008-11-17 08:05:31 +00005427#endif
danielk1977e339d652008-06-28 11:23:00 +00005428 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005429 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005430 }else{
drh7708e972008-11-29 00:56:52 +00005431 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005432 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005433 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005434 }
danielk1977e339d652008-06-28 11:23:00 +00005435 return rc;
drh054889e2005-11-30 03:20:31 +00005436}
drh9c06c952005-11-26 00:25:00 +00005437
danielk1977ad94b582007-08-20 06:44:22 +00005438/*
drh8b3cf822010-06-01 21:02:51 +00005439** Return the name of a directory in which to put temporary files.
5440** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005441*/
drh7234c6d2010-06-19 15:10:09 +00005442static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005443 static const char *azDirs[] = {
5444 0,
aswiftaebf4132008-11-21 00:10:35 +00005445 0,
mistachkind95a3d32013-08-30 21:52:38 +00005446 0,
danielk197717b90b52008-06-06 11:11:25 +00005447 "/var/tmp",
5448 "/usr/tmp",
5449 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005450 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005451 };
drh8b3cf822010-06-01 21:02:51 +00005452 unsigned int i;
5453 struct stat buf;
5454 const char *zDir = 0;
5455
5456 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005457 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5458 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005459 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005460 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005461 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005462 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005463 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005464 break;
5465 }
5466 return zDir;
5467}
5468
5469/*
5470** Create a temporary file name in zBuf. zBuf must be allocated
5471** by the calling process and must be big enough to hold at least
5472** pVfs->mxPathname bytes.
5473*/
5474static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005475 static const unsigned char zChars[] =
5476 "abcdefghijklmnopqrstuvwxyz"
5477 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5478 "0123456789";
drh41022642008-11-21 00:24:42 +00005479 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005480 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005481
5482 /* It's odd to simulate an io-error here, but really this is just
5483 ** using the io-error infrastructure to test that SQLite handles this
5484 ** function failing.
5485 */
5486 SimulateIOError( return SQLITE_IOERR );
5487
drh7234c6d2010-06-19 15:10:09 +00005488 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005489 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005490
5491 /* Check that the output buffer is large enough for the temporary file
5492 ** name. If it is not, return SQLITE_ERROR.
5493 */
drhc02a43a2012-01-10 23:18:38 +00005494 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005495 return SQLITE_ERROR;
5496 }
5497
5498 do{
drhc02a43a2012-01-10 23:18:38 +00005499 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005500 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005501 sqlite3_randomness(15, &zBuf[j]);
5502 for(i=0; i<15; i++, j++){
5503 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5504 }
5505 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005506 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005507 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005508 return SQLITE_OK;
5509}
5510
drhd2cb50b2009-01-09 21:41:17 +00005511#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005512/*
5513** Routine to transform a unixFile into a proxy-locking unixFile.
5514** Implementation in the proxy-lock division, but used by unixOpen()
5515** if SQLITE_PREFER_PROXY_LOCKING is defined.
5516*/
5517static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005518#endif
drhc66d5b62008-12-03 22:48:32 +00005519
dan08da86a2009-08-21 17:18:03 +00005520/*
5521** Search for an unused file descriptor that was opened on the database
5522** file (not a journal or master-journal file) identified by pathname
5523** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5524** argument to this function.
5525**
5526** Such a file descriptor may exist if a database connection was closed
5527** but the associated file descriptor could not be closed because some
5528** other file descriptor open on the same file is holding a file-lock.
5529** Refer to comments in the unixClose() function and the lengthy comment
5530** describing "Posix Advisory Locking" at the start of this file for
5531** further details. Also, ticket #4018.
5532**
5533** If a suitable file descriptor is found, then it is returned. If no
5534** such file descriptor is located, -1 is returned.
5535*/
dane946c392009-08-22 11:39:46 +00005536static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5537 UnixUnusedFd *pUnused = 0;
5538
5539 /* Do not search for an unused file descriptor on vxworks. Not because
5540 ** vxworks would not benefit from the change (it might, we're not sure),
5541 ** but because no way to test it is currently available. It is better
5542 ** not to risk breaking vxworks support for the sake of such an obscure
5543 ** feature. */
5544#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005545 struct stat sStat; /* Results of stat() call */
5546
5547 /* A stat() call may fail for various reasons. If this happens, it is
5548 ** almost certain that an open() call on the same path will also fail.
5549 ** For this reason, if an error occurs in the stat() call here, it is
5550 ** ignored and -1 is returned. The caller will try to open a new file
5551 ** descriptor on the same path, fail, and return an error to SQLite.
5552 **
5553 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005554 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005555 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005556 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005557
5558 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005559 pInode = inodeList;
5560 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5561 || pInode->fileId.ino!=sStat.st_ino) ){
5562 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005563 }
drh8af6c222010-05-14 12:43:01 +00005564 if( pInode ){
dane946c392009-08-22 11:39:46 +00005565 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005566 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005567 pUnused = *pp;
5568 if( pUnused ){
5569 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005570 }
5571 }
5572 unixLeaveMutex();
5573 }
dane946c392009-08-22 11:39:46 +00005574#endif /* if !OS_VXWORKS */
5575 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005576}
danielk197717b90b52008-06-06 11:11:25 +00005577
5578/*
danddb0ac42010-07-14 14:48:58 +00005579** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005580** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005581** and a value suitable for passing as the third argument to open(2) is
5582** written to *pMode. If an IO error occurs, an SQLite error code is
5583** returned and the value of *pMode is not modified.
5584**
peter.d.reid60ec9142014-09-06 16:39:46 +00005585** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005586** an indication to robust_open() to create the file using
5587** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5588** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005589** this function queries the file-system for the permissions on the
5590** corresponding database file and sets *pMode to this value. Whenever
5591** possible, WAL and journal files are created using the same permissions
5592** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005593**
5594** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5595** original filename is unavailable. But 8_3_NAMES is only used for
5596** FAT filesystems and permissions do not matter there, so just use
5597** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005598*/
5599static int findCreateFileMode(
5600 const char *zPath, /* Path of file (possibly) being created */
5601 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005602 mode_t *pMode, /* OUT: Permissions to open file with */
5603 uid_t *pUid, /* OUT: uid to set on the file */
5604 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005605){
5606 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005607 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005608 *pUid = 0;
5609 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005610 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005611 char zDb[MAX_PATHNAME+1]; /* Database file path */
5612 int nDb; /* Number of valid bytes in zDb */
5613 struct stat sStat; /* Output of stat() on database file */
5614
dana0c989d2010-11-05 18:07:37 +00005615 /* zPath is a path to a WAL or journal file. The following block derives
5616 ** the path to the associated database file from zPath. This block handles
5617 ** the following naming conventions:
5618 **
5619 ** "<path to db>-journal"
5620 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005621 ** "<path to db>-journalNN"
5622 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005623 **
drhd337c5b2011-10-20 18:23:35 +00005624 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005625 ** used by the test_multiplex.c module.
5626 */
5627 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005628#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005629 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005630 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005631#else
5632 while( zPath[nDb]!='-' ){
5633 assert( nDb>0 );
5634 assert( zPath[nDb]!='\n' );
5635 nDb--;
5636 }
5637#endif
danddb0ac42010-07-14 14:48:58 +00005638 memcpy(zDb, zPath, nDb);
5639 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005640
drh58384f12011-07-28 00:14:45 +00005641 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005642 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005643 *pUid = sStat.st_uid;
5644 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005645 }else{
5646 rc = SQLITE_IOERR_FSTAT;
5647 }
5648 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5649 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005650 }
5651 return rc;
5652}
5653
5654/*
danielk1977ad94b582007-08-20 06:44:22 +00005655** Open the file zPath.
5656**
danielk1977b4b47412007-08-17 15:53:36 +00005657** Previously, the SQLite OS layer used three functions in place of this
5658** one:
5659**
5660** sqlite3OsOpenReadWrite();
5661** sqlite3OsOpenReadOnly();
5662** sqlite3OsOpenExclusive();
5663**
5664** These calls correspond to the following combinations of flags:
5665**
5666** ReadWrite() -> (READWRITE | CREATE)
5667** ReadOnly() -> (READONLY)
5668** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5669**
5670** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5671** true, the file was configured to be automatically deleted when the
5672** file handle closed. To achieve the same effect using this new
5673** interface, add the DELETEONCLOSE flag to those specified above for
5674** OpenExclusive().
5675*/
5676static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005677 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5678 const char *zPath, /* Pathname of file to be opened */
5679 sqlite3_file *pFile, /* The file descriptor to be filled in */
5680 int flags, /* Input flags to control the opening */
5681 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005682){
dan08da86a2009-08-21 17:18:03 +00005683 unixFile *p = (unixFile *)pFile;
5684 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005685 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005686 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005687 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005688 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005689 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005690
5691 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5692 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5693 int isCreate = (flags & SQLITE_OPEN_CREATE);
5694 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5695 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005696#if SQLITE_ENABLE_LOCKING_STYLE
5697 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5698#endif
drh3d4435b2011-08-26 20:55:50 +00005699#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5700 struct statfs fsInfo;
5701#endif
danielk1977b4b47412007-08-17 15:53:36 +00005702
danielk1977fee2d252007-08-18 10:59:19 +00005703 /* If creating a master or main-file journal, this function will open
5704 ** a file-descriptor on the directory too. The first time unixSync()
5705 ** is called the directory file descriptor will be fsync()ed and close()d.
5706 */
drh0059eae2011-08-08 23:48:40 +00005707 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005708 eType==SQLITE_OPEN_MASTER_JOURNAL
5709 || eType==SQLITE_OPEN_MAIN_JOURNAL
5710 || eType==SQLITE_OPEN_WAL
5711 ));
danielk1977fee2d252007-08-18 10:59:19 +00005712
danielk197717b90b52008-06-06 11:11:25 +00005713 /* If argument zPath is a NULL pointer, this function is required to open
5714 ** a temporary file. Use this buffer to store the file name in.
5715 */
drhc02a43a2012-01-10 23:18:38 +00005716 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005717 const char *zName = zPath;
5718
danielk1977fee2d252007-08-18 10:59:19 +00005719 /* Check the following statements are true:
5720 **
5721 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5722 ** (b) if CREATE is set, then READWRITE must also be set, and
5723 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005724 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005725 */
danielk1977b4b47412007-08-17 15:53:36 +00005726 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005727 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005728 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005729 assert(isDelete==0 || isCreate);
5730
danddb0ac42010-07-14 14:48:58 +00005731 /* The main DB, main journal, WAL file and master journal are never
5732 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005733 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5734 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5735 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005736 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005737
danielk1977fee2d252007-08-18 10:59:19 +00005738 /* Assert that the upper layer has set one of the "file-type" flags. */
5739 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5740 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5741 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005742 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005743 );
5744
drhb00d8622014-01-01 15:18:36 +00005745 /* Detect a pid change and reset the PRNG. There is a race condition
5746 ** here such that two or more threads all trying to open databases at
5747 ** the same instant might all reset the PRNG. But multiple resets
5748 ** are harmless.
5749 */
drh5ac93652015-03-21 20:59:43 +00005750 if( randomnessPid!=osGetpid(0) ){
5751 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005752 sqlite3_randomness(0,0);
5753 }
5754
dan08da86a2009-08-21 17:18:03 +00005755 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005756
dan08da86a2009-08-21 17:18:03 +00005757 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005758 UnixUnusedFd *pUnused;
5759 pUnused = findReusableFd(zName, flags);
5760 if( pUnused ){
5761 fd = pUnused->fd;
5762 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005763 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005764 if( !pUnused ){
5765 return SQLITE_NOMEM;
5766 }
5767 }
5768 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005769
5770 /* Database filenames are double-zero terminated if they are not
5771 ** URIs with parameters. Hence, they can always be passed into
5772 ** sqlite3_uri_parameter(). */
5773 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5774
dan08da86a2009-08-21 17:18:03 +00005775 }else if( !zName ){
5776 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005777 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005778 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005779 if( rc!=SQLITE_OK ){
5780 return rc;
5781 }
5782 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005783
5784 /* Generated temporary filenames are always double-zero terminated
5785 ** for use by sqlite3_uri_parameter(). */
5786 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005787 }
5788
dan08da86a2009-08-21 17:18:03 +00005789 /* Determine the value of the flags parameter passed to POSIX function
5790 ** open(). These must be calculated even if open() is not called, as
5791 ** they may be stored as part of the file handle and used by the
5792 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005793 if( isReadonly ) openFlags |= O_RDONLY;
5794 if( isReadWrite ) openFlags |= O_RDWR;
5795 if( isCreate ) openFlags |= O_CREAT;
5796 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5797 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005798
danielk1977b4b47412007-08-17 15:53:36 +00005799 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005800 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005801 uid_t uid; /* Userid for the file */
5802 gid_t gid; /* Groupid for the file */
5803 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005804 if( rc!=SQLITE_OK ){
5805 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005806 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005807 return rc;
5808 }
drhad4f1e52011-03-04 15:43:57 +00005809 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005810 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005811 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5812 /* Failed to open the file for read/write access. Try read-only. */
5813 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005814 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005815 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005816 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005817 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005818 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005819 }
5820 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005821 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005822 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005823 }
drhac7c3ac2012-02-11 19:23:48 +00005824
5825 /* If this process is running as root and if creating a new rollback
5826 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005827 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005828 */
5829 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005830 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005831 }
danielk1977b4b47412007-08-17 15:53:36 +00005832 }
dan08da86a2009-08-21 17:18:03 +00005833 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005834 if( pOutFlags ){
5835 *pOutFlags = flags;
5836 }
5837
dane946c392009-08-22 11:39:46 +00005838 if( p->pUnused ){
5839 p->pUnused->fd = fd;
5840 p->pUnused->flags = flags;
5841 }
5842
danielk1977b4b47412007-08-17 15:53:36 +00005843 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005844#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005845 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005846#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5847 zPath = sqlite3_mprintf("%s", zName);
5848 if( zPath==0 ){
5849 robust_close(p, fd, __LINE__);
5850 return SQLITE_NOMEM;
5851 }
chw97185482008-11-17 08:05:31 +00005852#else
drh036ac7f2011-08-08 23:18:05 +00005853 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005854#endif
danielk1977b4b47412007-08-17 15:53:36 +00005855 }
drh41022642008-11-21 00:24:42 +00005856#if SQLITE_ENABLE_LOCKING_STYLE
5857 else{
dan08da86a2009-08-21 17:18:03 +00005858 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005859 }
5860#endif
5861
drhda0e7682008-07-30 15:27:54 +00005862 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005863
drh7ed97b92010-01-20 13:07:21 +00005864
5865#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005866 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005867 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005868 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005869 return SQLITE_IOERR_ACCESS;
5870 }
5871 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5872 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5873 }
drh4bf66fd2015-02-19 02:43:02 +00005874 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5875 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5876 }
drh7ed97b92010-01-20 13:07:21 +00005877#endif
drhc02a43a2012-01-10 23:18:38 +00005878
5879 /* Set up appropriate ctrlFlags */
5880 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5881 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5882 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5883 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5884 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5885
drh7ed97b92010-01-20 13:07:21 +00005886#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005887#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005888 isAutoProxy = 1;
5889#endif
5890 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005891 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5892 int useProxy = 0;
5893
dan08da86a2009-08-21 17:18:03 +00005894 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5895 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005896 if( envforce!=NULL ){
5897 useProxy = atoi(envforce)>0;
5898 }else{
aswiftaebf4132008-11-21 00:10:35 +00005899 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5900 }
5901 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005902 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005903 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005904 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005905 if( rc!=SQLITE_OK ){
5906 /* Use unixClose to clean up the resources added in fillInUnixFile
5907 ** and clear all the structure's references. Specifically,
5908 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5909 */
5910 unixClose(pFile);
5911 return rc;
5912 }
aswiftaebf4132008-11-21 00:10:35 +00005913 }
dane946c392009-08-22 11:39:46 +00005914 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005915 }
5916 }
5917#endif
5918
drhc02a43a2012-01-10 23:18:38 +00005919 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5920
dane946c392009-08-22 11:39:46 +00005921open_finished:
5922 if( rc!=SQLITE_OK ){
5923 sqlite3_free(p->pUnused);
5924 }
5925 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005926}
5927
dane946c392009-08-22 11:39:46 +00005928
danielk1977b4b47412007-08-17 15:53:36 +00005929/*
danielk1977fee2d252007-08-18 10:59:19 +00005930** Delete the file at zPath. If the dirSync argument is true, fsync()
5931** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005932*/
drh6b9d6dd2008-12-03 19:34:47 +00005933static int unixDelete(
5934 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5935 const char *zPath, /* Name of file to be deleted */
5936 int dirSync /* If true, fsync() directory after deleting file */
5937){
danielk1977fee2d252007-08-18 10:59:19 +00005938 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005939 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005940 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005941 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005942 if( errno==ENOENT
5943#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005944 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005945#endif
5946 ){
dan9fc5b4a2012-11-09 20:17:26 +00005947 rc = SQLITE_IOERR_DELETE_NOENT;
5948 }else{
drhb4308162012-11-09 21:40:02 +00005949 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005950 }
drhb4308162012-11-09 21:40:02 +00005951 return rc;
drh5d4feff2010-07-14 01:45:22 +00005952 }
danielk1977d39fa702008-10-16 13:27:40 +00005953#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005954 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005955 int fd;
drh90315a22011-08-10 01:52:12 +00005956 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005957 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005958#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005959 if( fsync(fd)==-1 )
5960#else
5961 if( fsync(fd) )
5962#endif
5963 {
dane18d4952011-02-21 11:46:24 +00005964 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005965 }
drh0e9365c2011-03-02 02:08:13 +00005966 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005967 }else if( rc==SQLITE_CANTOPEN ){
5968 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005969 }
5970 }
danielk1977d138dd82008-10-15 16:02:48 +00005971#endif
danielk1977fee2d252007-08-18 10:59:19 +00005972 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005973}
5974
danielk197790949c22007-08-17 16:50:38 +00005975/*
mistachkin48864df2013-03-21 21:20:32 +00005976** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005977** test performed depends on the value of flags:
5978**
5979** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5980** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5981** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5982**
5983** Otherwise return 0.
5984*/
danielk1977861f7452008-06-05 11:39:11 +00005985static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005986 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5987 const char *zPath, /* Path of the file to examine */
5988 int flags, /* What do we want to learn about the zPath file? */
5989 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005990){
rse25c0d1a2007-09-20 08:38:14 +00005991 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005992 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005993 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005994 switch( flags ){
5995 case SQLITE_ACCESS_EXISTS:
5996 amode = F_OK;
5997 break;
5998 case SQLITE_ACCESS_READWRITE:
5999 amode = W_OK|R_OK;
6000 break;
drh50d3f902007-08-27 21:10:36 +00006001 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00006002 amode = R_OK;
6003 break;
6004
6005 default:
6006 assert(!"Invalid flags argument");
6007 }
drh99ab3b12011-03-02 15:09:07 +00006008 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00006009 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
6010 struct stat buf;
drh58384f12011-07-28 00:14:45 +00006011 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00006012 *pResOut = 0;
6013 }
6014 }
danielk1977861f7452008-06-05 11:39:11 +00006015 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006016}
6017
danielk1977b4b47412007-08-17 15:53:36 +00006018
6019/*
6020** Turn a relative pathname into a full pathname. The relative path
6021** is stored as a nul-terminated string in the buffer pointed to by
6022** zPath.
6023**
6024** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6025** (in this case, MAX_PATHNAME bytes). The full-path is written to
6026** this buffer before returning.
6027*/
danielk1977adfb9b02007-09-17 07:02:56 +00006028static int unixFullPathname(
6029 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6030 const char *zPath, /* Possibly relative input path */
6031 int nOut, /* Size of output buffer in bytes */
6032 char *zOut /* Output buffer */
6033){
dan245fdc62015-10-31 17:58:33 +00006034 int nByte;
danielk1977843e65f2007-09-01 16:16:15 +00006035
6036 /* It's odd to simulate an io-error here, but really this is just
6037 ** using the io-error infrastructure to test that SQLite handles this
6038 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006039 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006040 */
6041 SimulateIOError( return SQLITE_ERROR );
6042
drh153c62c2007-08-24 03:51:33 +00006043 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006044 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006045
dan245fdc62015-10-31 17:58:33 +00006046 /* Attempt to resolve the path as if it were a symbolic link. If it is
6047 ** a symbolic link, the resolved path is stored in buffer zOut[]. Or, if
6048 ** the identified file is not a symbolic link or does not exist, then
6049 ** zPath is copied directly into zOut. Either way, nByte is left set to
6050 ** the size of the string copied into zOut[] in bytes. */
6051 nByte = osReadlink(zPath, zOut, nOut-1);
6052 if( nByte<0 ){
6053 if( errno!=EINVAL && errno!=ENOENT ){
6054 return unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zPath);
6055 }
6056 zOut[nOut-1] = '\0';
6057 sqlite3_snprintf(nOut-1, zOut, "%s", zPath);
6058 nByte = sqlite3Strlen30(zOut);
danielk1977b4b47412007-08-17 15:53:36 +00006059 }else{
dan245fdc62015-10-31 17:58:33 +00006060 zOut[nByte] = '\0';
6061 }
6062
6063 /* If buffer zOut[] now contains an absolute path there is nothing more
6064 ** to do. If it contains a relative path, do the following:
6065 **
6066 ** * move the relative path string so that it is at the end of th
6067 ** zOut[] buffer.
6068 ** * Call getcwd() to read the path of the current working directory
6069 ** into the start of the zOut[] buffer.
6070 ** * Append a '/' character to the cwd string and move the
6071 ** relative path back within the buffer so that it immediately
6072 ** follows the '/'.
6073 **
6074 ** This code is written so that if the combination of the CWD and relative
6075 ** path are larger than the allocated size of zOut[] the CWD is silently
6076 ** truncated to make it fit. This is Ok, as SQLite refuses to open any
6077 ** file for which this function returns a full path larger than (nOut-8)
6078 ** bytes in size. */
6079 if( zOut[0]!='/' ){
danielk1977b4b47412007-08-17 15:53:36 +00006080 int nCwd;
dan245fdc62015-10-31 17:58:33 +00006081 int nRem = nOut-nByte-1;
6082 memmove(&zOut[nRem], zOut, nByte+1);
6083 zOut[nRem-1] = '\0';
6084 if( osGetcwd(zOut, nRem-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006085 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006086 }
dan245fdc62015-10-31 17:58:33 +00006087 nCwd = sqlite3Strlen30(zOut);
6088 assert( nCwd<=nRem-1 );
6089 zOut[nCwd] = '/';
6090 memmove(&zOut[nCwd+1], &zOut[nRem], nByte+1);
danielk1977b4b47412007-08-17 15:53:36 +00006091 }
dan245fdc62015-10-31 17:58:33 +00006092
danielk1977b4b47412007-08-17 15:53:36 +00006093 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006094}
6095
drh0ccebe72005-06-07 22:22:50 +00006096
drh761df872006-12-21 01:29:22 +00006097#ifndef SQLITE_OMIT_LOAD_EXTENSION
6098/*
6099** Interfaces for opening a shared library, finding entry points
6100** within the shared library, and closing the shared library.
6101*/
6102#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006103static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6104 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006105 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6106}
danielk197795c8a542007-09-01 06:51:27 +00006107
6108/*
6109** SQLite calls this function immediately after a call to unixDlSym() or
6110** unixDlOpen() fails (returns a null pointer). If a more detailed error
6111** message is available, it is written to zBufOut. If no error message
6112** is available, zBufOut is left unmodified and SQLite uses a default
6113** error message.
6114*/
danielk1977397d65f2008-11-19 11:35:39 +00006115static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006116 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006117 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006118 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006119 zErr = dlerror();
6120 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006121 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006122 }
drh6c7d5c52008-11-21 20:32:33 +00006123 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006124}
drh1875f7a2008-12-08 18:19:17 +00006125static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6126 /*
6127 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6128 ** cast into a pointer to a function. And yet the library dlsym() routine
6129 ** returns a void* which is really a pointer to a function. So how do we
6130 ** use dlsym() with -pedantic-errors?
6131 **
6132 ** Variable x below is defined to be a pointer to a function taking
6133 ** parameters void* and const char* and returning a pointer to a function.
6134 ** We initialize x by assigning it a pointer to the dlsym() function.
6135 ** (That assignment requires a cast.) Then we call the function that
6136 ** x points to.
6137 **
6138 ** This work-around is unlikely to work correctly on any system where
6139 ** you really cannot cast a function pointer into void*. But then, on the
6140 ** other hand, dlsym() will not work on such a system either, so we have
6141 ** not really lost anything.
6142 */
6143 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006144 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006145 x = (void(*(*)(void*,const char*))(void))dlsym;
6146 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006147}
danielk1977397d65f2008-11-19 11:35:39 +00006148static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6149 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006150 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006151}
danielk1977b4b47412007-08-17 15:53:36 +00006152#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6153 #define unixDlOpen 0
6154 #define unixDlError 0
6155 #define unixDlSym 0
6156 #define unixDlClose 0
6157#endif
6158
6159/*
danielk197790949c22007-08-17 16:50:38 +00006160** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006161*/
danielk1977397d65f2008-11-19 11:35:39 +00006162static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6163 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006164 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006165
drhbbd42a62004-05-22 17:41:58 +00006166 /* We have to initialize zBuf to prevent valgrind from reporting
6167 ** errors. The reports issued by valgrind are incorrect - we would
6168 ** prefer that the randomness be increased by making use of the
6169 ** uninitialized space in zBuf - but valgrind errors tend to worry
6170 ** some users. Rather than argue, it seems easier just to initialize
6171 ** the whole array and silence valgrind, even if that means less randomness
6172 ** in the random seed.
6173 **
6174 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006175 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006176 ** tests repeatable.
6177 */
danielk1977b4b47412007-08-17 15:53:36 +00006178 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006179 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006180#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006181 {
drhb00d8622014-01-01 15:18:36 +00006182 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006183 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006184 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006185 time_t t;
6186 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006187 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006188 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6189 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6190 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006191 }else{
drhc18b4042012-02-10 03:10:27 +00006192 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006193 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006194 }
drhbbd42a62004-05-22 17:41:58 +00006195 }
6196#endif
drh72cbd072008-10-14 17:58:38 +00006197 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006198}
6199
danielk1977b4b47412007-08-17 15:53:36 +00006200
drhbbd42a62004-05-22 17:41:58 +00006201/*
6202** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006203** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006204** The return value is the number of microseconds of sleep actually
6205** requested from the underlying operating system, a number which
6206** might be greater than or equal to the argument, but not less
6207** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006208*/
danielk1977397d65f2008-11-19 11:35:39 +00006209static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006210#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006211 struct timespec sp;
6212
6213 sp.tv_sec = microseconds / 1000000;
6214 sp.tv_nsec = (microseconds % 1000000) * 1000;
6215 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006216 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006217 return microseconds;
6218#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006219 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006220 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006221 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006222#else
danielk1977b4b47412007-08-17 15:53:36 +00006223 int seconds = (microseconds+999999)/1000000;
6224 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006225 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006226 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006227#endif
drh88f474a2006-01-02 20:00:12 +00006228}
6229
6230/*
drh6b9d6dd2008-12-03 19:34:47 +00006231** The following variable, if set to a non-zero value, is interpreted as
6232** the number of seconds since 1970 and is used to set the result of
6233** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006234*/
6235#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006236int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006237#endif
6238
6239/*
drhb7e8ea22010-05-03 14:32:30 +00006240** Find the current time (in Universal Coordinated Time). Write into *piNow
6241** the current time and date as a Julian Day number times 86_400_000. In
6242** other words, write into *piNow the number of milliseconds since the Julian
6243** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6244** proleptic Gregorian calendar.
6245**
drh31702252011-10-12 23:13:43 +00006246** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6247** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006248*/
6249static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6250 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006251 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006252#if defined(NO_GETTOD)
6253 time_t t;
6254 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006255 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006256#elif OS_VXWORKS
6257 struct timespec sNow;
6258 clock_gettime(CLOCK_REALTIME, &sNow);
6259 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6260#else
6261 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006262 if( gettimeofday(&sNow, 0)==0 ){
6263 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6264 }else{
6265 rc = SQLITE_ERROR;
6266 }
drhb7e8ea22010-05-03 14:32:30 +00006267#endif
6268
6269#ifdef SQLITE_TEST
6270 if( sqlite3_current_time ){
6271 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6272 }
6273#endif
6274 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006275 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006276}
6277
6278/*
drhbbd42a62004-05-22 17:41:58 +00006279** Find the current time (in Universal Coordinated Time). Write the
6280** current time and date as a Julian Day number into *prNow and
6281** return 0. Return 1 if the time and date cannot be found.
6282*/
danielk1977397d65f2008-11-19 11:35:39 +00006283static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006284 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006285 int rc;
drhff828942010-06-26 21:34:06 +00006286 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006287 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006288 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006289 return rc;
drhbbd42a62004-05-22 17:41:58 +00006290}
danielk1977b4b47412007-08-17 15:53:36 +00006291
drh6b9d6dd2008-12-03 19:34:47 +00006292/*
6293** We added the xGetLastError() method with the intention of providing
6294** better low-level error messages when operating-system problems come up
6295** during SQLite operation. But so far, none of that has been implemented
6296** in the core. So this routine is never called. For now, it is merely
6297** a place-holder.
6298*/
danielk1977397d65f2008-11-19 11:35:39 +00006299static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6300 UNUSED_PARAMETER(NotUsed);
6301 UNUSED_PARAMETER(NotUsed2);
6302 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006303 return 0;
6304}
6305
drhf2424c52010-04-26 00:04:55 +00006306
6307/*
drh734c9862008-11-28 15:37:20 +00006308************************ End of sqlite3_vfs methods ***************************
6309******************************************************************************/
6310
drh715ff302008-12-03 22:32:44 +00006311/******************************************************************************
6312************************** Begin Proxy Locking ********************************
6313**
6314** Proxy locking is a "uber-locking-method" in this sense: It uses the
6315** other locking methods on secondary lock files. Proxy locking is a
6316** meta-layer over top of the primitive locking implemented above. For
6317** this reason, the division that implements of proxy locking is deferred
6318** until late in the file (here) after all of the other I/O methods have
6319** been defined - so that the primitive locking methods are available
6320** as services to help with the implementation of proxy locking.
6321**
6322****
6323**
6324** The default locking schemes in SQLite use byte-range locks on the
6325** database file to coordinate safe, concurrent access by multiple readers
6326** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6327** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6328** as POSIX read & write locks over fixed set of locations (via fsctl),
6329** on AFP and SMB only exclusive byte-range locks are available via fsctl
6330** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6331** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6332** address in the shared range is taken for a SHARED lock, the entire
6333** shared range is taken for an EXCLUSIVE lock):
6334**
drhf2f105d2012-08-20 15:53:54 +00006335** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006336** RESERVED_BYTE 0x40000001
6337** SHARED_RANGE 0x40000002 -> 0x40000200
6338**
6339** This works well on the local file system, but shows a nearly 100x
6340** slowdown in read performance on AFP because the AFP client disables
6341** the read cache when byte-range locks are present. Enabling the read
6342** cache exposes a cache coherency problem that is present on all OS X
6343** supported network file systems. NFS and AFP both observe the
6344** close-to-open semantics for ensuring cache coherency
6345** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6346** address the requirements for concurrent database access by multiple
6347** readers and writers
6348** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6349**
6350** To address the performance and cache coherency issues, proxy file locking
6351** changes the way database access is controlled by limiting access to a
6352** single host at a time and moving file locks off of the database file
6353** and onto a proxy file on the local file system.
6354**
6355**
6356** Using proxy locks
6357** -----------------
6358**
6359** C APIs
6360**
drh4bf66fd2015-02-19 02:43:02 +00006361** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006362** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006363** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6364** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006365**
6366**
6367** SQL pragmas
6368**
6369** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6370** PRAGMA [database.]lock_proxy_file
6371**
6372** Specifying ":auto:" means that if there is a conch file with a matching
6373** host ID in it, the proxy path in the conch file will be used, otherwise
6374** a proxy path based on the user's temp dir
6375** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6376** actual proxy file name is generated from the name and path of the
6377** database file. For example:
6378**
6379** For database path "/Users/me/foo.db"
6380** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6381**
6382** Once a lock proxy is configured for a database connection, it can not
6383** be removed, however it may be switched to a different proxy path via
6384** the above APIs (assuming the conch file is not being held by another
6385** connection or process).
6386**
6387**
6388** How proxy locking works
6389** -----------------------
6390**
6391** Proxy file locking relies primarily on two new supporting files:
6392**
6393** * conch file to limit access to the database file to a single host
6394** at a time
6395**
6396** * proxy file to act as a proxy for the advisory locks normally
6397** taken on the database
6398**
6399** The conch file - to use a proxy file, sqlite must first "hold the conch"
6400** by taking an sqlite-style shared lock on the conch file, reading the
6401** contents and comparing the host's unique host ID (see below) and lock
6402** proxy path against the values stored in the conch. The conch file is
6403** stored in the same directory as the database file and the file name
6404** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006405** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006406** host ID and/or proxy path, then the lock is escalated to an exclusive
6407** lock and the conch file contents is updated with the host ID and proxy
6408** path and the lock is downgraded to a shared lock again. If the conch
6409** is held by another process (with a shared lock), the exclusive lock
6410** will fail and SQLITE_BUSY is returned.
6411**
6412** The proxy file - a single-byte file used for all advisory file locks
6413** normally taken on the database file. This allows for safe sharing
6414** of the database file for multiple readers and writers on the same
6415** host (the conch ensures that they all use the same local lock file).
6416**
drh715ff302008-12-03 22:32:44 +00006417** Requesting the lock proxy does not immediately take the conch, it is
6418** only taken when the first request to lock database file is made.
6419** This matches the semantics of the traditional locking behavior, where
6420** opening a connection to a database file does not take a lock on it.
6421** The shared lock and an open file descriptor are maintained until
6422** the connection to the database is closed.
6423**
6424** The proxy file and the lock file are never deleted so they only need
6425** to be created the first time they are used.
6426**
6427** Configuration options
6428** ---------------------
6429**
6430** SQLITE_PREFER_PROXY_LOCKING
6431**
6432** Database files accessed on non-local file systems are
6433** automatically configured for proxy locking, lock files are
6434** named automatically using the same logic as
6435** PRAGMA lock_proxy_file=":auto:"
6436**
6437** SQLITE_PROXY_DEBUG
6438**
6439** Enables the logging of error messages during host id file
6440** retrieval and creation
6441**
drh715ff302008-12-03 22:32:44 +00006442** LOCKPROXYDIR
6443**
6444** Overrides the default directory used for lock proxy files that
6445** are named automatically via the ":auto:" setting
6446**
6447** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6448**
6449** Permissions to use when creating a directory for storing the
6450** lock proxy files, only used when LOCKPROXYDIR is not set.
6451**
6452**
6453** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6454** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6455** force proxy locking to be used for every database file opened, and 0
6456** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006457** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006458** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6459*/
6460
6461/*
6462** Proxy locking is only available on MacOSX
6463*/
drhd2cb50b2009-01-09 21:41:17 +00006464#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006465
drh715ff302008-12-03 22:32:44 +00006466/*
6467** The proxyLockingContext has the path and file structures for the remote
6468** and local proxy files in it
6469*/
6470typedef struct proxyLockingContext proxyLockingContext;
6471struct proxyLockingContext {
6472 unixFile *conchFile; /* Open conch file */
6473 char *conchFilePath; /* Name of the conch file */
6474 unixFile *lockProxy; /* Open proxy lock file */
6475 char *lockProxyPath; /* Name of the proxy lock file */
6476 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006477 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006478 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006479 void *oldLockingContext; /* Original lockingcontext to restore on close */
6480 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6481};
6482
drh7ed97b92010-01-20 13:07:21 +00006483/*
6484** The proxy lock file path for the database at dbPath is written into lPath,
6485** which must point to valid, writable memory large enough for a maxLen length
6486** file path.
drh715ff302008-12-03 22:32:44 +00006487*/
drh715ff302008-12-03 22:32:44 +00006488static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6489 int len;
6490 int dbLen;
6491 int i;
6492
6493#ifdef LOCKPROXYDIR
6494 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6495#else
6496# ifdef _CS_DARWIN_USER_TEMP_DIR
6497 {
drh7ed97b92010-01-20 13:07:21 +00006498 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006499 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006500 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006501 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006502 }
drh7ed97b92010-01-20 13:07:21 +00006503 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006504 }
6505# else
6506 len = strlcpy(lPath, "/tmp/", maxLen);
6507# endif
6508#endif
6509
6510 if( lPath[len-1]!='/' ){
6511 len = strlcat(lPath, "/", maxLen);
6512 }
6513
6514 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006515 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006516 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006517 char c = dbPath[i];
6518 lPath[i+len] = (c=='/')?'_':c;
6519 }
6520 lPath[i+len]='\0';
6521 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006522 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006523 return SQLITE_OK;
6524}
6525
drh7ed97b92010-01-20 13:07:21 +00006526/*
6527 ** Creates the lock file and any missing directories in lockPath
6528 */
6529static int proxyCreateLockPath(const char *lockPath){
6530 int i, len;
6531 char buf[MAXPATHLEN];
6532 int start = 0;
6533
6534 assert(lockPath!=NULL);
6535 /* try to create all the intermediate directories */
6536 len = (int)strlen(lockPath);
6537 buf[0] = lockPath[0];
6538 for( i=1; i<len; i++ ){
6539 if( lockPath[i] == '/' && (i - start > 0) ){
6540 /* only mkdir if leaf dir != "." or "/" or ".." */
6541 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6542 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6543 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006544 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006545 int err=errno;
6546 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006547 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006548 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006549 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006550 return err;
6551 }
6552 }
6553 }
6554 start=i+1;
6555 }
6556 buf[i] = lockPath[i];
6557 }
drh62aaa6c2015-11-21 17:27:42 +00006558 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006559 return 0;
6560}
6561
drh715ff302008-12-03 22:32:44 +00006562/*
6563** Create a new VFS file descriptor (stored in memory obtained from
6564** sqlite3_malloc) and open the file named "path" in the file descriptor.
6565**
6566** The caller is responsible not only for closing the file descriptor
6567** but also for freeing the memory associated with the file descriptor.
6568*/
drh7ed97b92010-01-20 13:07:21 +00006569static int proxyCreateUnixFile(
6570 const char *path, /* path for the new unixFile */
6571 unixFile **ppFile, /* unixFile created and returned by ref */
6572 int islockfile /* if non zero missing dirs will be created */
6573) {
6574 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006575 unixFile *pNew;
6576 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006577 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006578 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006579 int terrno = 0;
6580 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006581
drh7ed97b92010-01-20 13:07:21 +00006582 /* 1. first try to open/create the file
6583 ** 2. if that fails, and this is a lock file (not-conch), try creating
6584 ** the parent directories and then try again.
6585 ** 3. if that fails, try to open the file read-only
6586 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6587 */
6588 pUnused = findReusableFd(path, openFlags);
6589 if( pUnused ){
6590 fd = pUnused->fd;
6591 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006592 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006593 if( !pUnused ){
6594 return SQLITE_NOMEM;
6595 }
6596 }
6597 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006598 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006599 terrno = errno;
6600 if( fd<0 && errno==ENOENT && islockfile ){
6601 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006602 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006603 }
6604 }
6605 }
6606 if( fd<0 ){
6607 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006608 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006609 terrno = errno;
6610 }
6611 if( fd<0 ){
6612 if( islockfile ){
6613 return SQLITE_BUSY;
6614 }
6615 switch (terrno) {
6616 case EACCES:
6617 return SQLITE_PERM;
6618 case EIO:
6619 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6620 default:
drh9978c972010-02-23 17:36:32 +00006621 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006622 }
6623 }
6624
drhf3cdcdc2015-04-29 16:50:28 +00006625 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006626 if( pNew==NULL ){
6627 rc = SQLITE_NOMEM;
6628 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006629 }
6630 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006631 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006632 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006633 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006634 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006635 pUnused->fd = fd;
6636 pUnused->flags = openFlags;
6637 pNew->pUnused = pUnused;
6638
drhc02a43a2012-01-10 23:18:38 +00006639 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006640 if( rc==SQLITE_OK ){
6641 *ppFile = pNew;
6642 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006643 }
drh7ed97b92010-01-20 13:07:21 +00006644end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006645 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006646 sqlite3_free(pNew);
6647 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006648 return rc;
6649}
6650
drh7ed97b92010-01-20 13:07:21 +00006651#ifdef SQLITE_TEST
6652/* simulate multiple hosts by creating unique hostid file paths */
6653int sqlite3_hostid_num = 0;
6654#endif
6655
6656#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6657
drh6bca6512015-04-13 23:05:28 +00006658#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006659/* Not always defined in the headers as it ought to be */
6660extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006661#endif
drh0ab216a2010-07-02 17:10:40 +00006662
drh7ed97b92010-01-20 13:07:21 +00006663/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6664** bytes of writable memory.
6665*/
6666static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006667 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6668 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006669#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006670 {
drh4bf66fd2015-02-19 02:43:02 +00006671 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006672 if( gethostuuid(pHostID, &timeout) ){
6673 int err = errno;
6674 if( pError ){
6675 *pError = err;
6676 }
6677 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006678 }
drh7ed97b92010-01-20 13:07:21 +00006679 }
drh3d4435b2011-08-26 20:55:50 +00006680#else
6681 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006682#endif
drh7ed97b92010-01-20 13:07:21 +00006683#ifdef SQLITE_TEST
6684 /* simulate multiple hosts by creating unique hostid file paths */
6685 if( sqlite3_hostid_num != 0){
6686 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6687 }
6688#endif
6689
6690 return SQLITE_OK;
6691}
6692
6693/* The conch file contains the header, host id and lock file path
6694 */
6695#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6696#define PROXY_HEADERLEN 1 /* conch file header length */
6697#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6698#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6699
6700/*
6701** Takes an open conch file, copies the contents to a new path and then moves
6702** it back. The newly created file's file descriptor is assigned to the
6703** conch file structure and finally the original conch file descriptor is
6704** closed. Returns zero if successful.
6705*/
6706static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6707 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6708 unixFile *conchFile = pCtx->conchFile;
6709 char tPath[MAXPATHLEN];
6710 char buf[PROXY_MAXCONCHLEN];
6711 char *cPath = pCtx->conchFilePath;
6712 size_t readLen = 0;
6713 size_t pathLen = 0;
6714 char errmsg[64] = "";
6715 int fd = -1;
6716 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006717 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006718
6719 /* create a new path by replace the trailing '-conch' with '-break' */
6720 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6721 if( pathLen>MAXPATHLEN || pathLen<6 ||
6722 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006723 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006724 goto end_breaklock;
6725 }
6726 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006727 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006728 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006729 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006730 goto end_breaklock;
6731 }
6732 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006733 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006734 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006735 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006736 goto end_breaklock;
6737 }
drhe562be52011-03-02 18:01:10 +00006738 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006739 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006740 goto end_breaklock;
6741 }
6742 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006743 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006744 goto end_breaklock;
6745 }
6746 rc = 0;
6747 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006748 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006749 conchFile->h = fd;
6750 conchFile->openFlags = O_RDWR | O_CREAT;
6751
6752end_breaklock:
6753 if( rc ){
6754 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006755 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006756 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006757 }
6758 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6759 }
6760 return rc;
6761}
6762
6763/* Take the requested lock on the conch file and break a stale lock if the
6764** host id matches.
6765*/
6766static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6767 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6768 unixFile *conchFile = pCtx->conchFile;
6769 int rc = SQLITE_OK;
6770 int nTries = 0;
6771 struct timespec conchModTime;
6772
drh3d4435b2011-08-26 20:55:50 +00006773 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006774 do {
6775 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6776 nTries ++;
6777 if( rc==SQLITE_BUSY ){
6778 /* If the lock failed (busy):
6779 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6780 * 2nd try: fail if the mod time changed or host id is different, wait
6781 * 10 sec and try again
6782 * 3rd try: break the lock unless the mod time has changed.
6783 */
6784 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006785 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006786 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006787 return SQLITE_IOERR_LOCK;
6788 }
6789
6790 if( nTries==1 ){
6791 conchModTime = buf.st_mtimespec;
6792 usleep(500000); /* wait 0.5 sec and try the lock again*/
6793 continue;
6794 }
6795
6796 assert( nTries>1 );
6797 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6798 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6799 return SQLITE_BUSY;
6800 }
6801
6802 if( nTries==2 ){
6803 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006804 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006805 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006806 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006807 return SQLITE_IOERR_LOCK;
6808 }
6809 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6810 /* don't break the lock if the host id doesn't match */
6811 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6812 return SQLITE_BUSY;
6813 }
6814 }else{
6815 /* don't break the lock on short read or a version mismatch */
6816 return SQLITE_BUSY;
6817 }
6818 usleep(10000000); /* wait 10 sec and try the lock again */
6819 continue;
6820 }
6821
6822 assert( nTries==3 );
6823 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6824 rc = SQLITE_OK;
6825 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006826 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006827 }
6828 if( !rc ){
6829 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6830 }
6831 }
6832 }
6833 } while( rc==SQLITE_BUSY && nTries<3 );
6834
6835 return rc;
6836}
6837
6838/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006839** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6840** lockPath means that the lockPath in the conch file will be used if the
6841** host IDs match, or a new lock path will be generated automatically
6842** and written to the conch file.
6843*/
6844static int proxyTakeConch(unixFile *pFile){
6845 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6846
drh7ed97b92010-01-20 13:07:21 +00006847 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006848 return SQLITE_OK;
6849 }else{
6850 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006851 uuid_t myHostID;
6852 int pError = 0;
6853 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006854 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006855 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006856 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006857 int createConch = 0;
6858 int hostIdMatch = 0;
6859 int readLen = 0;
6860 int tryOldLockPath = 0;
6861 int forceNewLockPath = 0;
6862
drh308c2a52010-05-14 11:30:18 +00006863 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006864 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006865 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006866
drh7ed97b92010-01-20 13:07:21 +00006867 rc = proxyGetHostID(myHostID, &pError);
6868 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006869 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006870 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006871 }
drh7ed97b92010-01-20 13:07:21 +00006872 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006873 if( rc!=SQLITE_OK ){
6874 goto end_takeconch;
6875 }
drh7ed97b92010-01-20 13:07:21 +00006876 /* read the existing conch file */
6877 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6878 if( readLen<0 ){
6879 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006880 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006881 rc = SQLITE_IOERR_READ;
6882 goto end_takeconch;
6883 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6884 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6885 /* a short read or version format mismatch means we need to create a new
6886 ** conch file.
6887 */
6888 createConch = 1;
6889 }
6890 /* if the host id matches and the lock path already exists in the conch
6891 ** we'll try to use the path there, if we can't open that path, we'll
6892 ** retry with a new auto-generated path
6893 */
6894 do { /* in case we need to try again for an :auto: named lock file */
6895
6896 if( !createConch && !forceNewLockPath ){
6897 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6898 PROXY_HOSTIDLEN);
6899 /* if the conch has data compare the contents */
6900 if( !pCtx->lockProxyPath ){
6901 /* for auto-named local lock file, just check the host ID and we'll
6902 ** use the local lock file path that's already in there
6903 */
6904 if( hostIdMatch ){
6905 size_t pathLen = (readLen - PROXY_PATHINDEX);
6906
6907 if( pathLen>=MAXPATHLEN ){
6908 pathLen=MAXPATHLEN-1;
6909 }
6910 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6911 lockPath[pathLen] = 0;
6912 tempLockPath = lockPath;
6913 tryOldLockPath = 1;
6914 /* create a copy of the lock path if the conch is taken */
6915 goto end_takeconch;
6916 }
6917 }else if( hostIdMatch
6918 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6919 readLen-PROXY_PATHINDEX)
6920 ){
6921 /* conch host and lock path match */
6922 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006923 }
drh7ed97b92010-01-20 13:07:21 +00006924 }
6925
6926 /* if the conch isn't writable and doesn't match, we can't take it */
6927 if( (conchFile->openFlags&O_RDWR) == 0 ){
6928 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006929 goto end_takeconch;
6930 }
drh7ed97b92010-01-20 13:07:21 +00006931
6932 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006933 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006934 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6935 tempLockPath = lockPath;
6936 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006937 }
drh7ed97b92010-01-20 13:07:21 +00006938
6939 /* update conch with host and path (this will fail if other process
6940 ** has a shared lock already), if the host id matches, use the big
6941 ** stick.
drh715ff302008-12-03 22:32:44 +00006942 */
drh7ed97b92010-01-20 13:07:21 +00006943 futimes(conchFile->h, NULL);
6944 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006945 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006946 /* We are trying for an exclusive lock but another thread in this
6947 ** same process is still holding a shared lock. */
6948 rc = SQLITE_BUSY;
6949 } else {
6950 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006951 }
drh715ff302008-12-03 22:32:44 +00006952 }else{
drh4bf66fd2015-02-19 02:43:02 +00006953 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006954 }
drh7ed97b92010-01-20 13:07:21 +00006955 if( rc==SQLITE_OK ){
6956 char writeBuffer[PROXY_MAXCONCHLEN];
6957 int writeSize = 0;
6958
6959 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6960 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6961 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006962 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6963 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006964 }else{
6965 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6966 }
6967 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006968 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006969 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6970 fsync(conchFile->h);
6971 /* If we created a new conch file (not just updated the contents of a
6972 ** valid conch file), try to match the permissions of the database
6973 */
6974 if( rc==SQLITE_OK && createConch ){
6975 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006976 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006977 if( err==0 ){
6978 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6979 S_IROTH|S_IWOTH);
6980 /* try to match the database file R/W permissions, ignore failure */
6981#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006982 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006983#else
drhff812312011-02-23 13:33:46 +00006984 do{
drhe562be52011-03-02 18:01:10 +00006985 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006986 }while( rc==(-1) && errno==EINTR );
6987 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006988 int code = errno;
6989 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6990 cmode, code, strerror(code));
6991 } else {
6992 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6993 }
6994 }else{
6995 int code = errno;
6996 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6997 err, code, strerror(code));
6998#endif
6999 }
drh715ff302008-12-03 22:32:44 +00007000 }
7001 }
drh7ed97b92010-01-20 13:07:21 +00007002 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7003
7004 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007005 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007006 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007007 int fd;
drh7ed97b92010-01-20 13:07:21 +00007008 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007009 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007010 }
7011 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007012 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007013 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007014 if( fd>=0 ){
7015 pFile->h = fd;
7016 }else{
drh9978c972010-02-23 17:36:32 +00007017 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007018 during locking */
7019 }
7020 }
7021 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7022 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7023 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7024 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7025 /* we couldn't create the proxy lock file with the old lock file path
7026 ** so try again via auto-naming
7027 */
7028 forceNewLockPath = 1;
7029 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007030 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007031 }
7032 }
7033 if( rc==SQLITE_OK ){
7034 /* Need to make a copy of path if we extracted the value
7035 ** from the conch file or the path was allocated on the stack
7036 */
7037 if( tempLockPath ){
7038 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7039 if( !pCtx->lockProxyPath ){
7040 rc = SQLITE_NOMEM;
7041 }
7042 }
7043 }
7044 if( rc==SQLITE_OK ){
7045 pCtx->conchHeld = 1;
7046
7047 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7048 afpLockingContext *afpCtx;
7049 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7050 afpCtx->dbPath = pCtx->lockProxyPath;
7051 }
7052 } else {
7053 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7054 }
drh308c2a52010-05-14 11:30:18 +00007055 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7056 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007057 return rc;
drh308c2a52010-05-14 11:30:18 +00007058 } while (1); /* in case we need to retry the :auto: lock file -
7059 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007060 }
7061}
7062
7063/*
7064** If pFile holds a lock on a conch file, then release that lock.
7065*/
7066static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007067 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007068 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7069 unixFile *conchFile; /* Name of the conch file */
7070
7071 pCtx = (proxyLockingContext *)pFile->lockingContext;
7072 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007073 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007074 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007075 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007076 if( pCtx->conchHeld>0 ){
7077 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7078 }
drh715ff302008-12-03 22:32:44 +00007079 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007080 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7081 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007082 return rc;
7083}
7084
7085/*
7086** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007087** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007088** Make *pConchPath point to the new name. Return SQLITE_OK on success
7089** or SQLITE_NOMEM if unable to obtain memory.
7090**
7091** The caller is responsible for ensuring that the allocated memory
7092** space is eventually freed.
7093**
7094** *pConchPath is set to NULL if a memory allocation error occurs.
7095*/
7096static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7097 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007098 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007099 char *conchPath; /* buffer in which to construct conch name */
7100
7101 /* Allocate space for the conch filename and initialize the name to
7102 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007103 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007104 if( conchPath==0 ){
7105 return SQLITE_NOMEM;
7106 }
7107 memcpy(conchPath, dbPath, len+1);
7108
7109 /* now insert a "." before the last / character */
7110 for( i=(len-1); i>=0; i-- ){
7111 if( conchPath[i]=='/' ){
7112 i++;
7113 break;
7114 }
7115 }
7116 conchPath[i]='.';
7117 while ( i<len ){
7118 conchPath[i+1]=dbPath[i];
7119 i++;
7120 }
7121
7122 /* append the "-conch" suffix to the file */
7123 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007124 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007125
7126 return SQLITE_OK;
7127}
7128
7129
7130/* Takes a fully configured proxy locking-style unix file and switches
7131** the local lock file path
7132*/
7133static int switchLockProxyPath(unixFile *pFile, const char *path) {
7134 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7135 char *oldPath = pCtx->lockProxyPath;
7136 int rc = SQLITE_OK;
7137
drh308c2a52010-05-14 11:30:18 +00007138 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007139 return SQLITE_BUSY;
7140 }
7141
7142 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7143 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7144 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7145 return SQLITE_OK;
7146 }else{
7147 unixFile *lockProxy = pCtx->lockProxy;
7148 pCtx->lockProxy=NULL;
7149 pCtx->conchHeld = 0;
7150 if( lockProxy!=NULL ){
7151 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7152 if( rc ) return rc;
7153 sqlite3_free(lockProxy);
7154 }
7155 sqlite3_free(oldPath);
7156 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7157 }
7158
7159 return rc;
7160}
7161
7162/*
7163** pFile is a file that has been opened by a prior xOpen call. dbPath
7164** is a string buffer at least MAXPATHLEN+1 characters in size.
7165**
7166** This routine find the filename associated with pFile and writes it
7167** int dbPath.
7168*/
7169static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007170#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007171 if( pFile->pMethod == &afpIoMethods ){
7172 /* afp style keeps a reference to the db path in the filePath field
7173 ** of the struct */
drhea678832008-12-10 19:26:22 +00007174 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007175 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7176 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007177 } else
drh715ff302008-12-03 22:32:44 +00007178#endif
7179 if( pFile->pMethod == &dotlockIoMethods ){
7180 /* dot lock style uses the locking context to store the dot lock
7181 ** file path */
7182 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7183 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7184 }else{
7185 /* all other styles use the locking context to store the db file path */
7186 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007187 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007188 }
7189 return SQLITE_OK;
7190}
7191
7192/*
7193** Takes an already filled in unix file and alters it so all file locking
7194** will be performed on the local proxy lock file. The following fields
7195** are preserved in the locking context so that they can be restored and
7196** the unix structure properly cleaned up at close time:
7197** ->lockingContext
7198** ->pMethod
7199*/
7200static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7201 proxyLockingContext *pCtx;
7202 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7203 char *lockPath=NULL;
7204 int rc = SQLITE_OK;
7205
drh308c2a52010-05-14 11:30:18 +00007206 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007207 return SQLITE_BUSY;
7208 }
7209 proxyGetDbPathForUnixFile(pFile, dbPath);
7210 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7211 lockPath=NULL;
7212 }else{
7213 lockPath=(char *)path;
7214 }
7215
drh308c2a52010-05-14 11:30:18 +00007216 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007217 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007218
drhf3cdcdc2015-04-29 16:50:28 +00007219 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007220 if( pCtx==0 ){
7221 return SQLITE_NOMEM;
7222 }
7223 memset(pCtx, 0, sizeof(*pCtx));
7224
7225 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7226 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007227 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7228 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7229 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7230 ** (c) the file system is read-only, then enable no-locking access.
7231 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7232 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7233 */
7234 struct statfs fsInfo;
7235 struct stat conchInfo;
7236 int goLockless = 0;
7237
drh99ab3b12011-03-02 15:09:07 +00007238 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007239 int err = errno;
7240 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7241 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7242 }
7243 }
7244 if( goLockless ){
7245 pCtx->conchHeld = -1; /* read only FS/ lockless */
7246 rc = SQLITE_OK;
7247 }
7248 }
drh715ff302008-12-03 22:32:44 +00007249 }
7250 if( rc==SQLITE_OK && lockPath ){
7251 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7252 }
7253
7254 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007255 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7256 if( pCtx->dbPath==NULL ){
7257 rc = SQLITE_NOMEM;
7258 }
7259 }
7260 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007261 /* all memory is allocated, proxys are created and assigned,
7262 ** switch the locking context and pMethod then return.
7263 */
drh715ff302008-12-03 22:32:44 +00007264 pCtx->oldLockingContext = pFile->lockingContext;
7265 pFile->lockingContext = pCtx;
7266 pCtx->pOldMethod = pFile->pMethod;
7267 pFile->pMethod = &proxyIoMethods;
7268 }else{
7269 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007270 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007271 sqlite3_free(pCtx->conchFile);
7272 }
drhd56b1212010-08-11 06:14:15 +00007273 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007274 sqlite3_free(pCtx->conchFilePath);
7275 sqlite3_free(pCtx);
7276 }
drh308c2a52010-05-14 11:30:18 +00007277 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7278 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007279 return rc;
7280}
7281
7282
7283/*
7284** This routine handles sqlite3_file_control() calls that are specific
7285** to proxy locking.
7286*/
7287static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7288 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007289 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007290 unixFile *pFile = (unixFile*)id;
7291 if( pFile->pMethod == &proxyIoMethods ){
7292 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7293 proxyTakeConch(pFile);
7294 if( pCtx->lockProxyPath ){
7295 *(const char **)pArg = pCtx->lockProxyPath;
7296 }else{
7297 *(const char **)pArg = ":auto: (not held)";
7298 }
7299 } else {
7300 *(const char **)pArg = NULL;
7301 }
7302 return SQLITE_OK;
7303 }
drh4bf66fd2015-02-19 02:43:02 +00007304 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007305 unixFile *pFile = (unixFile*)id;
7306 int rc = SQLITE_OK;
7307 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7308 if( pArg==NULL || (const char *)pArg==0 ){
7309 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007310 /* turn off proxy locking - not supported. If support is added for
7311 ** switching proxy locking mode off then it will need to fail if
7312 ** the journal mode is WAL mode.
7313 */
drh715ff302008-12-03 22:32:44 +00007314 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7315 }else{
7316 /* turn off proxy locking - already off - NOOP */
7317 rc = SQLITE_OK;
7318 }
7319 }else{
7320 const char *proxyPath = (const char *)pArg;
7321 if( isProxyStyle ){
7322 proxyLockingContext *pCtx =
7323 (proxyLockingContext*)pFile->lockingContext;
7324 if( !strcmp(pArg, ":auto:")
7325 || (pCtx->lockProxyPath &&
7326 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7327 ){
7328 rc = SQLITE_OK;
7329 }else{
7330 rc = switchLockProxyPath(pFile, proxyPath);
7331 }
7332 }else{
7333 /* turn on proxy file locking */
7334 rc = proxyTransformUnixFile(pFile, proxyPath);
7335 }
7336 }
7337 return rc;
7338 }
7339 default: {
7340 assert( 0 ); /* The call assures that only valid opcodes are sent */
7341 }
7342 }
7343 /*NOTREACHED*/
7344 return SQLITE_ERROR;
7345}
7346
7347/*
7348** Within this division (the proxying locking implementation) the procedures
7349** above this point are all utilities. The lock-related methods of the
7350** proxy-locking sqlite3_io_method object follow.
7351*/
7352
7353
7354/*
7355** This routine checks if there is a RESERVED lock held on the specified
7356** file by this or any other process. If such a lock is held, set *pResOut
7357** to a non-zero value otherwise *pResOut is set to zero. The return value
7358** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7359*/
7360static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7361 unixFile *pFile = (unixFile*)id;
7362 int rc = proxyTakeConch(pFile);
7363 if( rc==SQLITE_OK ){
7364 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007365 if( pCtx->conchHeld>0 ){
7366 unixFile *proxy = pCtx->lockProxy;
7367 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7368 }else{ /* conchHeld < 0 is lockless */
7369 pResOut=0;
7370 }
drh715ff302008-12-03 22:32:44 +00007371 }
7372 return rc;
7373}
7374
7375/*
drh308c2a52010-05-14 11:30:18 +00007376** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007377** of the following:
7378**
7379** (1) SHARED_LOCK
7380** (2) RESERVED_LOCK
7381** (3) PENDING_LOCK
7382** (4) EXCLUSIVE_LOCK
7383**
7384** Sometimes when requesting one lock state, additional lock states
7385** are inserted in between. The locking might fail on one of the later
7386** transitions leaving the lock state different from what it started but
7387** still short of its goal. The following chart shows the allowed
7388** transitions and the inserted intermediate states:
7389**
7390** UNLOCKED -> SHARED
7391** SHARED -> RESERVED
7392** SHARED -> (PENDING) -> EXCLUSIVE
7393** RESERVED -> (PENDING) -> EXCLUSIVE
7394** PENDING -> EXCLUSIVE
7395**
7396** This routine will only increase a lock. Use the sqlite3OsUnlock()
7397** routine to lower a locking level.
7398*/
drh308c2a52010-05-14 11:30:18 +00007399static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007400 unixFile *pFile = (unixFile*)id;
7401 int rc = proxyTakeConch(pFile);
7402 if( rc==SQLITE_OK ){
7403 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007404 if( pCtx->conchHeld>0 ){
7405 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007406 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7407 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007408 }else{
7409 /* conchHeld < 0 is lockless */
7410 }
drh715ff302008-12-03 22:32:44 +00007411 }
7412 return rc;
7413}
7414
7415
7416/*
drh308c2a52010-05-14 11:30:18 +00007417** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007418** must be either NO_LOCK or SHARED_LOCK.
7419**
7420** If the locking level of the file descriptor is already at or below
7421** the requested locking level, this routine is a no-op.
7422*/
drh308c2a52010-05-14 11:30:18 +00007423static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007424 unixFile *pFile = (unixFile*)id;
7425 int rc = proxyTakeConch(pFile);
7426 if( rc==SQLITE_OK ){
7427 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007428 if( pCtx->conchHeld>0 ){
7429 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007430 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7431 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007432 }else{
7433 /* conchHeld < 0 is lockless */
7434 }
drh715ff302008-12-03 22:32:44 +00007435 }
7436 return rc;
7437}
7438
7439/*
7440** Close a file that uses proxy locks.
7441*/
7442static int proxyClose(sqlite3_file *id) {
7443 if( id ){
7444 unixFile *pFile = (unixFile*)id;
7445 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7446 unixFile *lockProxy = pCtx->lockProxy;
7447 unixFile *conchFile = pCtx->conchFile;
7448 int rc = SQLITE_OK;
7449
7450 if( lockProxy ){
7451 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7452 if( rc ) return rc;
7453 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7454 if( rc ) return rc;
7455 sqlite3_free(lockProxy);
7456 pCtx->lockProxy = 0;
7457 }
7458 if( conchFile ){
7459 if( pCtx->conchHeld ){
7460 rc = proxyReleaseConch(pFile);
7461 if( rc ) return rc;
7462 }
7463 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7464 if( rc ) return rc;
7465 sqlite3_free(conchFile);
7466 }
drhd56b1212010-08-11 06:14:15 +00007467 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007468 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007469 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007470 /* restore the original locking context and pMethod then close it */
7471 pFile->lockingContext = pCtx->oldLockingContext;
7472 pFile->pMethod = pCtx->pOldMethod;
7473 sqlite3_free(pCtx);
7474 return pFile->pMethod->xClose(id);
7475 }
7476 return SQLITE_OK;
7477}
7478
7479
7480
drhd2cb50b2009-01-09 21:41:17 +00007481#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007482/*
7483** The proxy locking style is intended for use with AFP filesystems.
7484** And since AFP is only supported on MacOSX, the proxy locking is also
7485** restricted to MacOSX.
7486**
7487**
7488******************* End of the proxy lock implementation **********************
7489******************************************************************************/
7490
drh734c9862008-11-28 15:37:20 +00007491/*
danielk1977e339d652008-06-28 11:23:00 +00007492** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007493**
7494** This routine registers all VFS implementations for unix-like operating
7495** systems. This routine, and the sqlite3_os_end() routine that follows,
7496** should be the only routines in this file that are visible from other
7497** files.
drh6b9d6dd2008-12-03 19:34:47 +00007498**
7499** This routine is called once during SQLite initialization and by a
7500** single thread. The memory allocation and mutex subsystems have not
7501** necessarily been initialized when this routine is called, and so they
7502** should not be used.
drh153c62c2007-08-24 03:51:33 +00007503*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007504int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007505 /*
7506 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007507 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7508 ** to the "finder" function. (pAppData is a pointer to a pointer because
7509 ** silly C90 rules prohibit a void* from being cast to a function pointer
7510 ** and so we have to go through the intermediate pointer to avoid problems
7511 ** when compiling with -pedantic-errors on GCC.)
7512 **
7513 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007514 ** finder-function. The finder-function returns a pointer to the
7515 ** sqlite_io_methods object that implements the desired locking
7516 ** behaviors. See the division above that contains the IOMETHODS
7517 ** macro for addition information on finder-functions.
7518 **
7519 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7520 ** object. But the "autolockIoFinder" available on MacOSX does a little
7521 ** more than that; it looks at the filesystem type that hosts the
7522 ** database file and tries to choose an locking method appropriate for
7523 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007524 */
drh7708e972008-11-29 00:56:52 +00007525 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007526 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007527 sizeof(unixFile), /* szOsFile */ \
7528 MAX_PATHNAME, /* mxPathname */ \
7529 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007530 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007531 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007532 unixOpen, /* xOpen */ \
7533 unixDelete, /* xDelete */ \
7534 unixAccess, /* xAccess */ \
7535 unixFullPathname, /* xFullPathname */ \
7536 unixDlOpen, /* xDlOpen */ \
7537 unixDlError, /* xDlError */ \
7538 unixDlSym, /* xDlSym */ \
7539 unixDlClose, /* xDlClose */ \
7540 unixRandomness, /* xRandomness */ \
7541 unixSleep, /* xSleep */ \
7542 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007543 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007544 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007545 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007546 unixGetSystemCall, /* xGetSystemCall */ \
7547 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007548 }
7549
drh6b9d6dd2008-12-03 19:34:47 +00007550 /*
7551 ** All default VFSes for unix are contained in the following array.
7552 **
7553 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7554 ** by the SQLite core when the VFS is registered. So the following
7555 ** array cannot be const.
7556 */
danielk1977e339d652008-06-28 11:23:00 +00007557 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007558#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007559 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007560#elif OS_VXWORKS
7561 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007562#else
7563 UNIXVFS("unix", posixIoFinder ),
7564#endif
7565 UNIXVFS("unix-none", nolockIoFinder ),
7566 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007567 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007568#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007569 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007570#endif
drhe89b2912015-03-03 20:42:01 +00007571#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007572 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007573#endif
drhe89b2912015-03-03 20:42:01 +00007574#if SQLITE_ENABLE_LOCKING_STYLE
7575 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007576#endif
drhd2cb50b2009-01-09 21:41:17 +00007577#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007578 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007579 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007580 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007581#endif
drh153c62c2007-08-24 03:51:33 +00007582 };
drh6b9d6dd2008-12-03 19:34:47 +00007583 unsigned int i; /* Loop counter */
7584
drh2aa5a002011-04-13 13:42:25 +00007585 /* Double-check that the aSyscall[] array has been constructed
7586 ** correctly. See ticket [bb3a86e890c8e96ab] */
dan245fdc62015-10-31 17:58:33 +00007587 assert( ArraySize(aSyscall)==26 );
drh2aa5a002011-04-13 13:42:25 +00007588
drh6b9d6dd2008-12-03 19:34:47 +00007589 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007590 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007591 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007592 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007593 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007594}
danielk1977e339d652008-06-28 11:23:00 +00007595
7596/*
drh6b9d6dd2008-12-03 19:34:47 +00007597** Shutdown the operating system interface.
7598**
7599** Some operating systems might need to do some cleanup in this routine,
7600** to release dynamically allocated objects. But not on unix.
7601** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007602*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007603int sqlite3_os_end(void){
7604 return SQLITE_OK;
7605}
drhdce8bdb2007-08-16 13:01:44 +00007606
danielk197729bafea2008-06-26 10:41:19 +00007607#endif /* SQLITE_OS_UNIX */