blob: 93657f6898b9756dcb0e6480a33323bd2d857065 [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
dan702eec12014-06-23 10:04:58 +0000467#endif
468
drhe562be52011-03-02 18:01:10 +0000469}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000470
471/*
472** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000473** "unix" VFSes. Return SQLITE_OK opon successfully updating the
474** system call pointer, or SQLITE_NOTFOUND if there is no configurable
475** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000476*/
477static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000478 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
479 const char *zName, /* Name of system call to override */
480 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000481){
drh58ad5802011-03-23 22:02:23 +0000482 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000483 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000484
485 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000486 if( zName==0 ){
487 /* If no zName is given, restore all system calls to their default
488 ** settings and return NULL
489 */
dan51438a72011-04-02 17:00:47 +0000490 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000491 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
492 if( aSyscall[i].pDefault ){
493 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000494 }
495 }
496 }else{
497 /* If zName is specified, operate on only the one system call
498 ** specified.
499 */
500 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
501 if( strcmp(zName, aSyscall[i].zName)==0 ){
502 if( aSyscall[i].pDefault==0 ){
503 aSyscall[i].pDefault = aSyscall[i].pCurrent;
504 }
drh1df30962011-03-02 19:06:42 +0000505 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000506 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
507 aSyscall[i].pCurrent = pNewFunc;
508 break;
509 }
510 }
511 }
512 return rc;
513}
514
drh1df30962011-03-02 19:06:42 +0000515/*
516** Return the value of a system call. Return NULL if zName is not a
517** recognized system call name. NULL is also returned if the system call
518** is currently undefined.
519*/
drh58ad5802011-03-23 22:02:23 +0000520static sqlite3_syscall_ptr unixGetSystemCall(
521 sqlite3_vfs *pNotUsed,
522 const char *zName
523){
524 unsigned int i;
525
526 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000527 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
528 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
529 }
530 return 0;
531}
532
533/*
534** Return the name of the first system call after zName. If zName==NULL
535** then return the name of the first system call. Return NULL if zName
536** is the last system call or if zName is not the name of a valid
537** system call.
538*/
539static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000540 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000541
542 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000543 if( zName ){
544 for(i=0; i<ArraySize(aSyscall)-1; i++){
545 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000546 }
547 }
dan0fd7d862011-03-29 10:04:23 +0000548 for(i++; i<ArraySize(aSyscall); i++){
549 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000550 }
551 return 0;
552}
553
drhad4f1e52011-03-04 15:43:57 +0000554/*
drh77a3fdc2013-08-30 14:24:12 +0000555** Do not accept any file descriptor less than this value, in order to avoid
556** opening database file using file descriptors that are commonly used for
557** standard input, output, and error.
558*/
559#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
560# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
561#endif
562
563/*
drh8c815d12012-02-13 20:16:37 +0000564** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000565** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000566**
567** If the file creation mode "m" is 0 then set it to the default for
568** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
569** 0644) as modified by the system umask. If m is not 0, then
570** make the file creation mode be exactly m ignoring the umask.
571**
572** The m parameter will be non-zero only when creating -wal, -journal,
573** and -shm files. We want those files to have *exactly* the same
574** permissions as their original database, unadulterated by the umask.
575** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
576** transaction crashes and leaves behind hot journals, then any
577** process that is able to write to the database will also be able to
578** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000579*/
drh8c815d12012-02-13 20:16:37 +0000580static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000581 int fd;
drhe1186ab2013-01-04 20:45:13 +0000582 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000583 while(1){
drh5adc60b2012-04-14 13:25:11 +0000584#if defined(O_CLOEXEC)
585 fd = osOpen(z,f|O_CLOEXEC,m2);
586#else
587 fd = osOpen(z,f,m2);
588#endif
drh5128d002013-08-30 06:20:23 +0000589 if( fd<0 ){
590 if( errno==EINTR ) continue;
591 break;
592 }
drh77a3fdc2013-08-30 14:24:12 +0000593 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000594 osClose(fd);
595 sqlite3_log(SQLITE_WARNING,
596 "attempt to open \"%s\" as file descriptor %d", z, fd);
597 fd = -1;
598 if( osOpen("/dev/null", f, m)<0 ) break;
599 }
drhe1186ab2013-01-04 20:45:13 +0000600 if( fd>=0 ){
601 if( m!=0 ){
602 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000603 if( osFstat(fd, &statbuf)==0
604 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000605 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000606 ){
drhe1186ab2013-01-04 20:45:13 +0000607 osFchmod(fd, m);
608 }
609 }
drh5adc60b2012-04-14 13:25:11 +0000610#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000611 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000612#endif
drhe1186ab2013-01-04 20:45:13 +0000613 }
drh5adc60b2012-04-14 13:25:11 +0000614 return fd;
drhad4f1e52011-03-04 15:43:57 +0000615}
danielk197713adf8a2004-06-03 16:08:41 +0000616
drh107886a2008-11-21 22:21:50 +0000617/*
dan9359c7b2009-08-21 08:29:10 +0000618** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000619** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000620** vxworksFileId objects used by this file, all of which may be
621** shared by multiple threads.
622**
623** Function unixMutexHeld() is used to assert() that the global mutex
624** is held when required. This function is only used as part of assert()
625** statements. e.g.
626**
627** unixEnterMutex()
628** assert( unixMutexHeld() );
629** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000630*/
631static void unixEnterMutex(void){
632 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
633}
634static void unixLeaveMutex(void){
635 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
636}
dan9359c7b2009-08-21 08:29:10 +0000637#ifdef SQLITE_DEBUG
638static int unixMutexHeld(void) {
639 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
640}
641#endif
drh107886a2008-11-21 22:21:50 +0000642
drh734c9862008-11-28 15:37:20 +0000643
mistachkinfb383e92015-04-16 03:24:38 +0000644#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000645/*
646** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000647** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000648** integer lock-type.
649*/
drh308c2a52010-05-14 11:30:18 +0000650static const char *azFileLock(int eFileLock){
651 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000652 case NO_LOCK: return "NONE";
653 case SHARED_LOCK: return "SHARED";
654 case RESERVED_LOCK: return "RESERVED";
655 case PENDING_LOCK: return "PENDING";
656 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000657 }
658 return "ERROR";
659}
660#endif
661
662#ifdef SQLITE_LOCK_TRACE
663/*
664** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000665**
drh734c9862008-11-28 15:37:20 +0000666** This routine is used for troubleshooting locks on multithreaded
667** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
668** command-line option on the compiler. This code is normally
669** turned off.
670*/
671static int lockTrace(int fd, int op, struct flock *p){
672 char *zOpName, *zType;
673 int s;
674 int savedErrno;
675 if( op==F_GETLK ){
676 zOpName = "GETLK";
677 }else if( op==F_SETLK ){
678 zOpName = "SETLK";
679 }else{
drh99ab3b12011-03-02 15:09:07 +0000680 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000681 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
682 return s;
683 }
684 if( p->l_type==F_RDLCK ){
685 zType = "RDLCK";
686 }else if( p->l_type==F_WRLCK ){
687 zType = "WRLCK";
688 }else if( p->l_type==F_UNLCK ){
689 zType = "UNLCK";
690 }else{
691 assert( 0 );
692 }
693 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000694 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000695 savedErrno = errno;
696 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
697 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
698 (int)p->l_pid, s);
699 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
700 struct flock l2;
701 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000702 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000703 if( l2.l_type==F_RDLCK ){
704 zType = "RDLCK";
705 }else if( l2.l_type==F_WRLCK ){
706 zType = "WRLCK";
707 }else if( l2.l_type==F_UNLCK ){
708 zType = "UNLCK";
709 }else{
710 assert( 0 );
711 }
712 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
713 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
714 }
715 errno = savedErrno;
716 return s;
717}
drh99ab3b12011-03-02 15:09:07 +0000718#undef osFcntl
719#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000720#endif /* SQLITE_LOCK_TRACE */
721
drhff812312011-02-23 13:33:46 +0000722/*
723** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000724**
drhe6d41732015-02-21 00:49:00 +0000725** All calls to ftruncate() within this file should be made through
726** this wrapper. On the Android platform, bypassing the logic below
727** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000728*/
drhff812312011-02-23 13:33:46 +0000729static int robust_ftruncate(int h, sqlite3_int64 sz){
730 int rc;
dan2ee53412014-09-06 16:49:40 +0000731#ifdef __ANDROID__
732 /* On Android, ftruncate() always uses 32-bit offsets, even if
733 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000734 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000735 ** such attempts. */
736 if( sz>(sqlite3_int64)0x7FFFFFFF ){
737 rc = SQLITE_OK;
738 }else
739#endif
drh99ab3b12011-03-02 15:09:07 +0000740 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000741 return rc;
742}
drh734c9862008-11-28 15:37:20 +0000743
744/*
745** This routine translates a standard POSIX errno code into something
746** useful to the clients of the sqlite3 functions. Specifically, it is
747** intended to translate a variety of "try again" errors into SQLITE_BUSY
748** and a variety of "please close the file descriptor NOW" errors into
749** SQLITE_IOERR
750**
751** Errors during initialization of locks, or file system support for locks,
752** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
753*/
754static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
755 switch (posixError) {
dan661d71a2011-03-30 19:08:03 +0000756#if 0
757 /* At one point this code was not commented out. In theory, this branch
758 ** should never be hit, as this function should only be called after
759 ** a locking-related function (i.e. fcntl()) has returned non-zero with
760 ** the value of errno as the first argument. Since a system call has failed,
761 ** errno should be non-zero.
762 **
763 ** Despite this, if errno really is zero, we still don't want to return
764 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
765 ** propagated back to the caller. Commenting this branch out means errno==0
766 ** will be handled by the "default:" case below.
767 */
drh734c9862008-11-28 15:37:20 +0000768 case 0:
769 return SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +0000770#endif
771
drh734c9862008-11-28 15:37:20 +0000772 case EAGAIN:
773 case ETIMEDOUT:
774 case EBUSY:
775 case EINTR:
776 case ENOLCK:
777 /* random NFS retry error, unless during file system support
778 * introspection, in which it actually means what it says */
779 return SQLITE_BUSY;
780
781 case EACCES:
782 /* EACCES is like EAGAIN during locking operations, but not any other time*/
783 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
drhf2f105d2012-08-20 15:53:54 +0000784 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
785 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
786 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
drh734c9862008-11-28 15:37:20 +0000787 return SQLITE_BUSY;
788 }
789 /* else fall through */
790 case EPERM:
791 return SQLITE_PERM;
792
drh734c9862008-11-28 15:37:20 +0000793#if EOPNOTSUPP!=ENOTSUP
794 case EOPNOTSUPP:
795 /* something went terribly awry, unless during file system support
796 * introspection, in which it actually means what it says */
797#endif
798#ifdef ENOTSUP
799 case ENOTSUP:
800 /* invalid fd, unless during file system support introspection, in which
801 * it actually means what it says */
802#endif
803 case EIO:
804 case EBADF:
805 case EINVAL:
806 case ENOTCONN:
807 case ENODEV:
808 case ENXIO:
809 case ENOENT:
dan33067e72011-07-15 13:43:34 +0000810#ifdef ESTALE /* ESTALE is not defined on Interix systems */
drh734c9862008-11-28 15:37:20 +0000811 case ESTALE:
dan33067e72011-07-15 13:43:34 +0000812#endif
drh734c9862008-11-28 15:37:20 +0000813 case ENOSYS:
814 /* these should force the client to close the file and reconnect */
815
816 default:
817 return sqliteIOErr;
818 }
819}
820
821
drh734c9862008-11-28 15:37:20 +0000822/******************************************************************************
823****************** Begin Unique File ID Utility Used By VxWorks ***************
824**
825** On most versions of unix, we can get a unique ID for a file by concatenating
826** the device number and the inode number. But this does not work on VxWorks.
827** On VxWorks, a unique file id must be based on the canonical filename.
828**
829** A pointer to an instance of the following structure can be used as a
830** unique file ID in VxWorks. Each instance of this structure contains
831** a copy of the canonical filename. There is also a reference count.
832** The structure is reclaimed when the number of pointers to it drops to
833** zero.
834**
835** There are never very many files open at one time and lookups are not
836** a performance-critical path, so it is sufficient to put these
837** structures on a linked list.
838*/
839struct vxworksFileId {
840 struct vxworksFileId *pNext; /* Next in a list of them all */
841 int nRef; /* Number of references to this one */
842 int nName; /* Length of the zCanonicalName[] string */
843 char *zCanonicalName; /* Canonical filename */
844};
845
846#if OS_VXWORKS
847/*
drh9b35ea62008-11-29 02:20:26 +0000848** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000849** variable:
850*/
851static struct vxworksFileId *vxworksFileList = 0;
852
853/*
854** Simplify a filename into its canonical form
855** by making the following changes:
856**
857** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000858** * convert /./ into just /
859** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000860**
861** Changes are made in-place. Return the new name length.
862**
863** The original filename is in z[0..n-1]. Return the number of
864** characters in the simplified name.
865*/
866static int vxworksSimplifyName(char *z, int n){
867 int i, j;
868 while( n>1 && z[n-1]=='/' ){ n--; }
869 for(i=j=0; i<n; i++){
870 if( z[i]=='/' ){
871 if( z[i+1]=='/' ) continue;
872 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
873 i += 1;
874 continue;
875 }
876 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
877 while( j>0 && z[j-1]!='/' ){ j--; }
878 if( j>0 ){ j--; }
879 i += 2;
880 continue;
881 }
882 }
883 z[j++] = z[i];
884 }
885 z[j] = 0;
886 return j;
887}
888
889/*
890** Find a unique file ID for the given absolute pathname. Return
891** a pointer to the vxworksFileId object. This pointer is the unique
892** file ID.
893**
894** The nRef field of the vxworksFileId object is incremented before
895** the object is returned. A new vxworksFileId object is created
896** and added to the global list if necessary.
897**
898** If a memory allocation error occurs, return NULL.
899*/
900static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
901 struct vxworksFileId *pNew; /* search key and new file ID */
902 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
903 int n; /* Length of zAbsoluteName string */
904
905 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000906 n = (int)strlen(zAbsoluteName);
drh734c9862008-11-28 15:37:20 +0000907 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
908 if( pNew==0 ) return 0;
909 pNew->zCanonicalName = (char*)&pNew[1];
910 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
911 n = vxworksSimplifyName(pNew->zCanonicalName, n);
912
913 /* Search for an existing entry that matching the canonical name.
914 ** If found, increment the reference count and return a pointer to
915 ** the existing file ID.
916 */
917 unixEnterMutex();
918 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
919 if( pCandidate->nName==n
920 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
921 ){
922 sqlite3_free(pNew);
923 pCandidate->nRef++;
924 unixLeaveMutex();
925 return pCandidate;
926 }
927 }
928
929 /* No match was found. We will make a new file ID */
930 pNew->nRef = 1;
931 pNew->nName = n;
932 pNew->pNext = vxworksFileList;
933 vxworksFileList = pNew;
934 unixLeaveMutex();
935 return pNew;
936}
937
938/*
939** Decrement the reference count on a vxworksFileId object. Free
940** the object when the reference count reaches zero.
941*/
942static void vxworksReleaseFileId(struct vxworksFileId *pId){
943 unixEnterMutex();
944 assert( pId->nRef>0 );
945 pId->nRef--;
946 if( pId->nRef==0 ){
947 struct vxworksFileId **pp;
948 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
949 assert( *pp==pId );
950 *pp = pId->pNext;
951 sqlite3_free(pId);
952 }
953 unixLeaveMutex();
954}
955#endif /* OS_VXWORKS */
956/*************** End of Unique File ID Utility Used By VxWorks ****************
957******************************************************************************/
958
959
960/******************************************************************************
961*************************** Posix Advisory Locking ****************************
962**
drh9b35ea62008-11-29 02:20:26 +0000963** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000964** section 6.5.2.2 lines 483 through 490 specify that when a process
965** sets or clears a lock, that operation overrides any prior locks set
966** by the same process. It does not explicitly say so, but this implies
967** that it overrides locks set by the same process using a different
968** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000969**
970** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000971** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
972**
973** Suppose ./file1 and ./file2 are really the same file (because
974** one is a hard or symbolic link to the other) then if you set
975** an exclusive lock on fd1, then try to get an exclusive lock
976** on fd2, it works. I would have expected the second lock to
977** fail since there was already a lock on the file due to fd1.
978** But not so. Since both locks came from the same process, the
979** second overrides the first, even though they were on different
980** file descriptors opened on different file names.
981**
drh734c9862008-11-28 15:37:20 +0000982** This means that we cannot use POSIX locks to synchronize file access
983** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000984** to synchronize access for threads in separate processes, but not
985** threads within the same process.
986**
987** To work around the problem, SQLite has to manage file locks internally
988** on its own. Whenever a new database is opened, we have to find the
989** specific inode of the database file (the inode is determined by the
990** st_dev and st_ino fields of the stat structure that fstat() fills in)
991** and check for locks already existing on that inode. When locks are
992** created or removed, we have to look at our own internal record of the
993** locks to see if another thread has previously set a lock on that same
994** inode.
995**
drh9b35ea62008-11-29 02:20:26 +0000996** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
997** For VxWorks, we have to use the alternative unique ID system based on
998** canonical filename and implemented in the previous division.)
999**
danielk1977ad94b582007-08-20 06:44:22 +00001000** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001001** descriptor. It is now a structure that holds the integer file
1002** descriptor and a pointer to a structure that describes the internal
1003** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001004** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001005** point to the same locking structure. The locking structure keeps
1006** a reference count (so we will know when to delete it) and a "cnt"
1007** field that tells us its internal lock status. cnt==0 means the
1008** file is unlocked. cnt==-1 means the file has an exclusive lock.
1009** cnt>0 means there are cnt shared locks on the file.
1010**
1011** Any attempt to lock or unlock a file first checks the locking
1012** structure. The fcntl() system call is only invoked to set a
1013** POSIX lock if the internal lock structure transitions between
1014** a locked and an unlocked state.
1015**
drh734c9862008-11-28 15:37:20 +00001016** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001017**
1018** If you close a file descriptor that points to a file that has locks,
1019** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001020** released. To work around this problem, each unixInodeInfo object
1021** maintains a count of the number of pending locks on tha inode.
1022** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001023** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001024** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001025** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001026** be closed and that list is walked (and cleared) when the last lock
1027** clears.
1028**
drh9b35ea62008-11-29 02:20:26 +00001029** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001030**
drh9b35ea62008-11-29 02:20:26 +00001031** Many older versions of linux use the LinuxThreads library which is
1032** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001033** A cannot be modified or overridden by a different thread B.
1034** Only thread A can modify the lock. Locking behavior is correct
1035** if the appliation uses the newer Native Posix Thread Library (NPTL)
1036** on linux - with NPTL a lock created by thread A can override locks
1037** in thread B. But there is no way to know at compile-time which
1038** threading library is being used. So there is no way to know at
1039** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001040** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001041** current process.
drh5fdae772004-06-29 03:29:00 +00001042**
drh8af6c222010-05-14 12:43:01 +00001043** SQLite used to support LinuxThreads. But support for LinuxThreads
1044** was dropped beginning with version 3.7.0. SQLite will still work with
1045** LinuxThreads provided that (1) there is no more than one connection
1046** per database file in the same process and (2) database connections
1047** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001048*/
1049
1050/*
1051** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001052** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001053*/
1054struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001055 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001056#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001057 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001058#else
drh107886a2008-11-21 22:21:50 +00001059 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001060#endif
1061};
1062
1063/*
drhbbd42a62004-05-22 17:41:58 +00001064** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001065** inode. Or, on LinuxThreads, there is one of these structures for
1066** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001067**
danielk1977ad94b582007-08-20 06:44:22 +00001068** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001069** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001070** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001071*/
drh8af6c222010-05-14 12:43:01 +00001072struct unixInodeInfo {
1073 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001074 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001075 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1076 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001077 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001078 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1079 int nLock; /* Number of outstanding file locks */
1080 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1081 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1082 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001083#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001084 unsigned long long sharedByte; /* for AFP simulated shared lock */
1085#endif
drh6c7d5c52008-11-21 20:32:33 +00001086#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001087 sem_t *pSem; /* Named POSIX semaphore */
1088 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001089#endif
drhbbd42a62004-05-22 17:41:58 +00001090};
1091
drhda0e7682008-07-30 15:27:54 +00001092/*
drh8af6c222010-05-14 12:43:01 +00001093** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001094*/
drhd91c68f2010-05-14 14:52:25 +00001095static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001096
drh5fdae772004-06-29 03:29:00 +00001097/*
dane18d4952011-02-21 11:46:24 +00001098**
1099** This function - unixLogError_x(), is only ever called via the macro
1100** unixLogError().
1101**
1102** It is invoked after an error occurs in an OS function and errno has been
1103** set. It logs a message using sqlite3_log() containing the current value of
1104** errno and, if possible, the human-readable equivalent from strerror() or
1105** strerror_r().
1106**
1107** The first argument passed to the macro should be the error code that
1108** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1109** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001110** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001111** if any.
1112*/
drh0e9365c2011-03-02 02:08:13 +00001113#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1114static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001115 int errcode, /* SQLite error code */
1116 const char *zFunc, /* Name of OS function that failed */
1117 const char *zPath, /* File path associated with error */
1118 int iLine /* Source line number where error occurred */
1119){
1120 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001121 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001122
1123 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1124 ** the strerror() function to obtain the human-readable error message
1125 ** equivalent to errno. Otherwise, use strerror_r().
1126 */
1127#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1128 char aErr[80];
1129 memset(aErr, 0, sizeof(aErr));
1130 zErr = aErr;
1131
1132 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001133 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001134 ** returns a pointer to a buffer containing the error message. That pointer
1135 ** may point to aErr[], or it may point to some static storage somewhere.
1136 ** Otherwise, assume that the system provides the POSIX version of
1137 ** strerror_r(), which always writes an error message into aErr[].
1138 **
1139 ** If the code incorrectly assumes that it is the POSIX version that is
1140 ** available, the error message will often be an empty string. Not a
1141 ** huge problem. Incorrectly concluding that the GNU version is available
1142 ** could lead to a segfault though.
1143 */
1144#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1145 zErr =
1146# endif
drh0e9365c2011-03-02 02:08:13 +00001147 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001148
1149#elif SQLITE_THREADSAFE
1150 /* This is a threadsafe build, but strerror_r() is not available. */
1151 zErr = "";
1152#else
1153 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001154 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001155#endif
1156
drh0e9365c2011-03-02 02:08:13 +00001157 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001158 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001159 "os_unix.c:%d: (%d) %s(%s) - %s",
1160 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001161 );
1162
1163 return errcode;
1164}
1165
drh0e9365c2011-03-02 02:08:13 +00001166/*
1167** Close a file descriptor.
1168**
1169** We assume that close() almost always works, since it is only in a
1170** very sick application or on a very sick platform that it might fail.
1171** If it does fail, simply leak the file descriptor, but do log the
1172** error.
1173**
1174** Note that it is not safe to retry close() after EINTR since the
1175** file descriptor might have already been reused by another thread.
1176** So we don't even try to recover from an EINTR. Just log the error
1177** and move on.
1178*/
1179static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001180 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001181 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1182 pFile ? pFile->zPath : 0, lineno);
1183 }
1184}
dane18d4952011-02-21 11:46:24 +00001185
1186/*
drhe6d41732015-02-21 00:49:00 +00001187** Set the pFile->lastErrno. Do this in a subroutine as that provides
1188** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001189*/
1190static void storeLastErrno(unixFile *pFile, int error){
1191 pFile->lastErrno = error;
1192}
1193
1194/*
danb0ac3e32010-06-16 10:55:42 +00001195** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001196*/
drh0e9365c2011-03-02 02:08:13 +00001197static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001198 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001199 UnixUnusedFd *p;
1200 UnixUnusedFd *pNext;
1201 for(p=pInode->pUnused; p; p=pNext){
1202 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001203 robust_close(pFile, p->fd, __LINE__);
1204 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001205 }
drh0e9365c2011-03-02 02:08:13 +00001206 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001207}
1208
1209/*
drh8af6c222010-05-14 12:43:01 +00001210** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001211**
1212** The mutex entered using the unixEnterMutex() function must be held
1213** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001214*/
danb0ac3e32010-06-16 10:55:42 +00001215static void releaseInodeInfo(unixFile *pFile){
1216 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001217 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001218 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001219 pInode->nRef--;
1220 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001221 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001222 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001223 if( pInode->pPrev ){
1224 assert( pInode->pPrev->pNext==pInode );
1225 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001226 }else{
drh8af6c222010-05-14 12:43:01 +00001227 assert( inodeList==pInode );
1228 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001229 }
drh8af6c222010-05-14 12:43:01 +00001230 if( pInode->pNext ){
1231 assert( pInode->pNext->pPrev==pInode );
1232 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001233 }
drh8af6c222010-05-14 12:43:01 +00001234 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001235 }
drhbbd42a62004-05-22 17:41:58 +00001236 }
1237}
1238
1239/*
drh8af6c222010-05-14 12:43:01 +00001240** Given a file descriptor, locate the unixInodeInfo object that
1241** describes that file descriptor. Create a new one if necessary. The
1242** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001243**
dan9359c7b2009-08-21 08:29:10 +00001244** The mutex entered using the unixEnterMutex() function must be held
1245** when this function is called.
1246**
drh6c7d5c52008-11-21 20:32:33 +00001247** Return an appropriate error code.
1248*/
drh8af6c222010-05-14 12:43:01 +00001249static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001250 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001251 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001252){
1253 int rc; /* System call return code */
1254 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001255 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1256 struct stat statbuf; /* Low-level file information */
1257 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001258
dan9359c7b2009-08-21 08:29:10 +00001259 assert( unixMutexHeld() );
1260
drh6c7d5c52008-11-21 20:32:33 +00001261 /* Get low-level information about the file that we can used to
1262 ** create a unique name for the file.
1263 */
1264 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001265 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001266 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001267 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001268#ifdef EOVERFLOW
1269 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1270#endif
1271 return SQLITE_IOERR;
1272 }
1273
drheb0d74f2009-02-03 15:27:02 +00001274#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001275 /* On OS X on an msdos filesystem, the inode number is reported
1276 ** incorrectly for zero-size files. See ticket #3260. To work
1277 ** around this problem (we consider it a bug in OS X, not SQLite)
1278 ** we always increase the file size to 1 by writing a single byte
1279 ** prior to accessing the inode number. The one byte written is
1280 ** an ASCII 'S' character which also happens to be the first byte
1281 ** in the header of every SQLite database. In this way, if there
1282 ** is a race condition such that another thread has already populated
1283 ** the first page of the database, no damage is done.
1284 */
drh7ed97b92010-01-20 13:07:21 +00001285 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001286 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001287 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001288 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001289 return SQLITE_IOERR;
1290 }
drh99ab3b12011-03-02 15:09:07 +00001291 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001292 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001293 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001294 return SQLITE_IOERR;
1295 }
1296 }
drheb0d74f2009-02-03 15:27:02 +00001297#endif
drh6c7d5c52008-11-21 20:32:33 +00001298
drh8af6c222010-05-14 12:43:01 +00001299 memset(&fileId, 0, sizeof(fileId));
1300 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001301#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001302 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001303#else
drh8af6c222010-05-14 12:43:01 +00001304 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001305#endif
drh8af6c222010-05-14 12:43:01 +00001306 pInode = inodeList;
1307 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1308 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001309 }
drh8af6c222010-05-14 12:43:01 +00001310 if( pInode==0 ){
1311 pInode = sqlite3_malloc( sizeof(*pInode) );
1312 if( pInode==0 ){
1313 return SQLITE_NOMEM;
drh6c7d5c52008-11-21 20:32:33 +00001314 }
drh8af6c222010-05-14 12:43:01 +00001315 memset(pInode, 0, sizeof(*pInode));
1316 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1317 pInode->nRef = 1;
1318 pInode->pNext = inodeList;
1319 pInode->pPrev = 0;
1320 if( inodeList ) inodeList->pPrev = pInode;
1321 inodeList = pInode;
1322 }else{
1323 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001324 }
drh8af6c222010-05-14 12:43:01 +00001325 *ppInode = pInode;
1326 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001327}
drh6c7d5c52008-11-21 20:32:33 +00001328
drhb959a012013-12-07 12:29:22 +00001329/*
1330** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1331*/
1332static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001333#if OS_VXWORKS
1334 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1335#else
drhb959a012013-12-07 12:29:22 +00001336 struct stat buf;
1337 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001338 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001339#endif
drhb959a012013-12-07 12:29:22 +00001340}
1341
aswift5b1a2562008-08-22 00:22:35 +00001342
1343/*
drhfbc7e882013-04-11 01:16:15 +00001344** Check a unixFile that is a database. Verify the following:
1345**
1346** (1) There is exactly one hard link on the file
1347** (2) The file is not a symbolic link
1348** (3) The file has not been renamed or unlinked
1349**
1350** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1351*/
1352static void verifyDbFile(unixFile *pFile){
1353 struct stat buf;
1354 int rc;
drh3044b512014-06-16 16:41:52 +00001355 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
1356 /* One or more of the following warnings have already been issued. Do not
1357 ** repeat them so as not to clutter the error log */
drhfbc7e882013-04-11 01:16:15 +00001358 return;
1359 }
1360 rc = osFstat(pFile->h, &buf);
1361 if( rc!=0 ){
1362 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
1363 pFile->ctrlFlags |= UNIXFILE_WARNED;
1364 return;
1365 }
drh3044b512014-06-16 16:41:52 +00001366 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001367 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
1368 pFile->ctrlFlags |= UNIXFILE_WARNED;
1369 return;
1370 }
1371 if( buf.st_nlink>1 ){
1372 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
1373 pFile->ctrlFlags |= UNIXFILE_WARNED;
1374 return;
1375 }
drhb959a012013-12-07 12:29:22 +00001376 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001377 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
1378 pFile->ctrlFlags |= UNIXFILE_WARNED;
1379 return;
1380 }
1381}
1382
1383
1384/*
danielk197713adf8a2004-06-03 16:08:41 +00001385** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001386** file by this or any other process. If such a lock is held, set *pResOut
1387** to a non-zero value otherwise *pResOut is set to zero. The return value
1388** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001389*/
danielk1977861f7452008-06-05 11:39:11 +00001390static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001391 int rc = SQLITE_OK;
1392 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001393 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001394
danielk1977861f7452008-06-05 11:39:11 +00001395 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1396
drh054889e2005-11-30 03:20:31 +00001397 assert( pFile );
drh8af6c222010-05-14 12:43:01 +00001398 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001399
1400 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001401 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001402 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001403 }
1404
drh2ac3ee92004-06-07 16:27:46 +00001405 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001406 */
danielk197709480a92009-02-09 05:32:32 +00001407#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001408 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001409 struct flock lock;
1410 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001411 lock.l_start = RESERVED_BYTE;
1412 lock.l_len = 1;
1413 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001414 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1415 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001416 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001417 } else if( lock.l_type!=F_UNLCK ){
1418 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001419 }
1420 }
danielk197709480a92009-02-09 05:32:32 +00001421#endif
danielk197713adf8a2004-06-03 16:08:41 +00001422
drh6c7d5c52008-11-21 20:32:33 +00001423 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001424 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001425
aswift5b1a2562008-08-22 00:22:35 +00001426 *pResOut = reserved;
1427 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001428}
1429
1430/*
drha7e61d82011-03-12 17:02:57 +00001431** Attempt to set a system-lock on the file pFile. The lock is
1432** described by pLock.
1433**
drh77197112011-03-15 19:08:48 +00001434** If the pFile was opened read/write from unix-excl, then the only lock
1435** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001436** the first time any lock is attempted. All subsequent system locking
1437** operations become no-ops. Locking operations still happen internally,
1438** in order to coordinate access between separate database connections
1439** within this process, but all of that is handled in memory and the
1440** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001441**
1442** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1443** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1444** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001445**
1446** Zero is returned if the call completes successfully, or -1 if a call
1447** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001448*/
1449static int unixFileLock(unixFile *pFile, struct flock *pLock){
1450 int rc;
drh3cb93392011-03-12 18:10:44 +00001451 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001452 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001453 assert( pInode!=0 );
drh77197112011-03-15 19:08:48 +00001454 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
1455 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
1456 ){
drh3cb93392011-03-12 18:10:44 +00001457 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001458 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001459 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001460 lock.l_whence = SEEK_SET;
1461 lock.l_start = SHARED_FIRST;
1462 lock.l_len = SHARED_SIZE;
1463 lock.l_type = F_WRLCK;
1464 rc = osFcntl(pFile->h, F_SETLK, &lock);
1465 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001466 pInode->bProcessLock = 1;
1467 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001468 }else{
1469 rc = 0;
1470 }
1471 }else{
1472 rc = osFcntl(pFile->h, F_SETLK, pLock);
1473 }
1474 return rc;
1475}
1476
1477/*
drh308c2a52010-05-14 11:30:18 +00001478** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001479** of the following:
1480**
drh2ac3ee92004-06-07 16:27:46 +00001481** (1) SHARED_LOCK
1482** (2) RESERVED_LOCK
1483** (3) PENDING_LOCK
1484** (4) EXCLUSIVE_LOCK
1485**
drhb3e04342004-06-08 00:47:47 +00001486** Sometimes when requesting one lock state, additional lock states
1487** are inserted in between. The locking might fail on one of the later
1488** transitions leaving the lock state different from what it started but
1489** still short of its goal. The following chart shows the allowed
1490** transitions and the inserted intermediate states:
1491**
1492** UNLOCKED -> SHARED
1493** SHARED -> RESERVED
1494** SHARED -> (PENDING) -> EXCLUSIVE
1495** RESERVED -> (PENDING) -> EXCLUSIVE
1496** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001497**
drha6abd042004-06-09 17:37:22 +00001498** This routine will only increase a lock. Use the sqlite3OsUnlock()
1499** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001500*/
drh308c2a52010-05-14 11:30:18 +00001501static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001502 /* The following describes the implementation of the various locks and
1503 ** lock transitions in terms of the POSIX advisory shared and exclusive
1504 ** lock primitives (called read-locks and write-locks below, to avoid
1505 ** confusion with SQLite lock names). The algorithms are complicated
1506 ** slightly in order to be compatible with windows systems simultaneously
1507 ** accessing the same database file, in case that is ever required.
1508 **
1509 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1510 ** byte', each single bytes at well known offsets, and the 'shared byte
1511 ** range', a range of 510 bytes at a well known offset.
1512 **
1513 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1514 ** byte'. If this is successful, a random byte from the 'shared byte
1515 ** range' is read-locked and the lock on the 'pending byte' released.
1516 **
danielk197790ba3bd2004-06-25 08:32:25 +00001517 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1518 ** A RESERVED lock is implemented by grabbing a write-lock on the
1519 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001520 **
1521 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001522 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1523 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1524 ** obtained, but existing SHARED locks are allowed to persist. A process
1525 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1526 ** This property is used by the algorithm for rolling back a journal file
1527 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001528 **
danielk197790ba3bd2004-06-25 08:32:25 +00001529 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1530 ** implemented by obtaining a write-lock on the entire 'shared byte
1531 ** range'. Since all other locks require a read-lock on one of the bytes
1532 ** within this range, this ensures that no other locks are held on the
1533 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001534 **
1535 ** The reason a single byte cannot be used instead of the 'shared byte
1536 ** range' is that some versions of windows do not support read-locks. By
1537 ** locking a random byte from a range, concurrent SHARED locks may exist
1538 ** even if the locking primitive used is always a write-lock.
1539 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001540 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001541 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001542 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001543 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001544 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001545
drh054889e2005-11-30 03:20:31 +00001546 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001547 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1548 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001549 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001550 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001551
1552 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001553 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001554 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001555 */
drh308c2a52010-05-14 11:30:18 +00001556 if( pFile->eFileLock>=eFileLock ){
1557 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1558 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001559 return SQLITE_OK;
1560 }
1561
drh0c2694b2009-09-03 16:23:44 +00001562 /* Make sure the locking sequence is correct.
1563 ** (1) We never move from unlocked to anything higher than shared lock.
1564 ** (2) SQLite never explicitly requests a pendig lock.
1565 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001566 */
drh308c2a52010-05-14 11:30:18 +00001567 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1568 assert( eFileLock!=PENDING_LOCK );
1569 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001570
drh8af6c222010-05-14 12:43:01 +00001571 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001572 */
drh6c7d5c52008-11-21 20:32:33 +00001573 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001574 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001575
danielk1977ad94b582007-08-20 06:44:22 +00001576 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001577 ** handle that precludes the requested lock, return BUSY.
1578 */
drh8af6c222010-05-14 12:43:01 +00001579 if( (pFile->eFileLock!=pInode->eFileLock &&
1580 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001581 ){
1582 rc = SQLITE_BUSY;
1583 goto end_lock;
1584 }
1585
1586 /* If a SHARED lock is requested, and some thread using this PID already
1587 ** has a SHARED or RESERVED lock, then increment reference counts and
1588 ** return SQLITE_OK.
1589 */
drh308c2a52010-05-14 11:30:18 +00001590 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001591 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001592 assert( eFileLock==SHARED_LOCK );
1593 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001594 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001595 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001596 pInode->nShared++;
1597 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001598 goto end_lock;
1599 }
1600
danielk19779a1d0ab2004-06-01 14:09:28 +00001601
drh3cde3bb2004-06-12 02:17:14 +00001602 /* A PENDING lock is needed before acquiring a SHARED lock and before
1603 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1604 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001605 */
drh0c2694b2009-09-03 16:23:44 +00001606 lock.l_len = 1L;
1607 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001608 if( eFileLock==SHARED_LOCK
1609 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001610 ){
drh308c2a52010-05-14 11:30:18 +00001611 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001612 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001613 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001614 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001615 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001616 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001617 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001618 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001619 goto end_lock;
1620 }
drh3cde3bb2004-06-12 02:17:14 +00001621 }
1622
1623
1624 /* If control gets to this point, then actually go ahead and make
1625 ** operating system calls for the specified lock.
1626 */
drh308c2a52010-05-14 11:30:18 +00001627 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001628 assert( pInode->nShared==0 );
1629 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001630 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001631
drh2ac3ee92004-06-07 16:27:46 +00001632 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001633 lock.l_start = SHARED_FIRST;
1634 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001635 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001636 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001637 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001638 }
dan661d71a2011-03-30 19:08:03 +00001639
drh2ac3ee92004-06-07 16:27:46 +00001640 /* Drop the temporary PENDING lock */
1641 lock.l_start = PENDING_BYTE;
1642 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001643 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001644 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1645 /* This could happen with a network mount */
1646 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001647 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001648 }
dan661d71a2011-03-30 19:08:03 +00001649
1650 if( rc ){
1651 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001652 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001653 }
dan661d71a2011-03-30 19:08:03 +00001654 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001655 }else{
drh308c2a52010-05-14 11:30:18 +00001656 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001657 pInode->nLock++;
1658 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001659 }
drh8af6c222010-05-14 12:43:01 +00001660 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001661 /* We are trying for an exclusive lock but another thread in this
1662 ** same process is still holding a shared lock. */
1663 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001664 }else{
drh3cde3bb2004-06-12 02:17:14 +00001665 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001666 ** assumed that there is a SHARED or greater lock on the file
1667 ** already.
1668 */
drh308c2a52010-05-14 11:30:18 +00001669 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001670 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001671
1672 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1673 if( eFileLock==RESERVED_LOCK ){
1674 lock.l_start = RESERVED_BYTE;
1675 lock.l_len = 1L;
1676 }else{
1677 lock.l_start = SHARED_FIRST;
1678 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001679 }
dan661d71a2011-03-30 19:08:03 +00001680
1681 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001682 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001683 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001684 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001685 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001686 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001687 }
drhbbd42a62004-05-22 17:41:58 +00001688 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001689
drh8f941bc2009-01-14 23:03:40 +00001690
drhd3d8c042012-05-29 17:02:40 +00001691#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001692 /* Set up the transaction-counter change checking flags when
1693 ** transitioning from a SHARED to a RESERVED lock. The change
1694 ** from SHARED to RESERVED marks the beginning of a normal
1695 ** write operation (not a hot journal rollback).
1696 */
1697 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001698 && pFile->eFileLock<=SHARED_LOCK
1699 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001700 ){
1701 pFile->transCntrChng = 0;
1702 pFile->dbUpdate = 0;
1703 pFile->inNormalWrite = 1;
1704 }
1705#endif
1706
1707
danielk1977ecb2a962004-06-02 06:30:16 +00001708 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001709 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001710 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001711 }else if( eFileLock==EXCLUSIVE_LOCK ){
1712 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001713 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001714 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001715
1716end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001717 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001718 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1719 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001720 return rc;
1721}
1722
1723/*
dan08da86a2009-08-21 17:18:03 +00001724** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001725** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001726*/
1727static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001728 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001729 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001730 p->pNext = pInode->pUnused;
1731 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001732 pFile->h = -1;
1733 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001734}
1735
1736/*
drh308c2a52010-05-14 11:30:18 +00001737** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001738** must be either NO_LOCK or SHARED_LOCK.
1739**
1740** If the locking level of the file descriptor is already at or below
1741** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001742**
1743** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1744** the byte range is divided into 2 parts and the first part is unlocked then
1745** set to a read lock, then the other part is simply unlocked. This works
1746** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1747** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001748*/
drha7e61d82011-03-12 17:02:57 +00001749static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001750 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001751 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001752 struct flock lock;
1753 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001754
drh054889e2005-11-30 03:20:31 +00001755 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001756 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001757 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001758 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001759
drh308c2a52010-05-14 11:30:18 +00001760 assert( eFileLock<=SHARED_LOCK );
1761 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001762 return SQLITE_OK;
1763 }
drh6c7d5c52008-11-21 20:32:33 +00001764 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001765 pInode = pFile->pInode;
1766 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001767 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001768 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001769
drhd3d8c042012-05-29 17:02:40 +00001770#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001771 /* When reducing a lock such that other processes can start
1772 ** reading the database file again, make sure that the
1773 ** transaction counter was updated if any part of the database
1774 ** file changed. If the transaction counter is not updated,
1775 ** other connections to the same file might not realize that
1776 ** the file has changed and hence might not know to flush their
1777 ** cache. The use of a stale cache can lead to database corruption.
1778 */
drh8f941bc2009-01-14 23:03:40 +00001779 pFile->inNormalWrite = 0;
1780#endif
1781
drh7ed97b92010-01-20 13:07:21 +00001782 /* downgrading to a shared lock on NFS involves clearing the write lock
1783 ** before establishing the readlock - to avoid a race condition we downgrade
1784 ** the lock in 2 blocks, so that part of the range will be covered by a
1785 ** write lock until the rest is covered by a read lock:
1786 ** 1: [WWWWW]
1787 ** 2: [....W]
1788 ** 3: [RRRRW]
1789 ** 4: [RRRR.]
1790 */
drh308c2a52010-05-14 11:30:18 +00001791 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001792#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001793 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001794 assert( handleNFSUnlock==0 );
1795#endif
1796#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001797 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001798 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001799 off_t divSize = SHARED_SIZE - 1;
1800
1801 lock.l_type = F_UNLCK;
1802 lock.l_whence = SEEK_SET;
1803 lock.l_start = SHARED_FIRST;
1804 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001805 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001806 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001807 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001808 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001809 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001810 }
1811 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001812 }
drh7ed97b92010-01-20 13:07:21 +00001813 lock.l_type = F_RDLCK;
1814 lock.l_whence = SEEK_SET;
1815 lock.l_start = SHARED_FIRST;
1816 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001817 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001818 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001819 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1820 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001821 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001822 }
1823 goto end_unlock;
1824 }
1825 lock.l_type = F_UNLCK;
1826 lock.l_whence = SEEK_SET;
1827 lock.l_start = SHARED_FIRST+divSize;
1828 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001829 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001830 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001831 rc = SQLITE_IOERR_UNLOCK;
drh7ed97b92010-01-20 13:07:21 +00001832 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001833 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001834 }
1835 goto end_unlock;
1836 }
drh30f776f2011-02-25 03:25:07 +00001837 }else
1838#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1839 {
drh7ed97b92010-01-20 13:07:21 +00001840 lock.l_type = F_RDLCK;
1841 lock.l_whence = SEEK_SET;
1842 lock.l_start = SHARED_FIRST;
1843 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001844 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001845 /* In theory, the call to unixFileLock() cannot fail because another
1846 ** process is holding an incompatible lock. If it does, this
1847 ** indicates that the other process is not following the locking
1848 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1849 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1850 ** an assert to fail). */
1851 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001852 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001853 goto end_unlock;
1854 }
drh9c105bb2004-10-02 20:38:28 +00001855 }
1856 }
drhbbd42a62004-05-22 17:41:58 +00001857 lock.l_type = F_UNLCK;
1858 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001859 lock.l_start = PENDING_BYTE;
1860 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001861 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001862 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001863 }else{
danea83bc62011-04-01 11:56:32 +00001864 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001865 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001866 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001867 }
drhbbd42a62004-05-22 17:41:58 +00001868 }
drh308c2a52010-05-14 11:30:18 +00001869 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001870 /* Decrement the shared lock counter. Release the lock using an
1871 ** OS call only when all threads in this same process have released
1872 ** the lock.
1873 */
drh8af6c222010-05-14 12:43:01 +00001874 pInode->nShared--;
1875 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001876 lock.l_type = F_UNLCK;
1877 lock.l_whence = SEEK_SET;
1878 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001879 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001880 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001881 }else{
danea83bc62011-04-01 11:56:32 +00001882 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001883 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001884 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001885 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001886 }
drha6abd042004-06-09 17:37:22 +00001887 }
1888
drhbbd42a62004-05-22 17:41:58 +00001889 /* Decrement the count of locks against this same file. When the
1890 ** count reaches zero, close any other file descriptors whose close
1891 ** was deferred because of outstanding locks.
1892 */
drh8af6c222010-05-14 12:43:01 +00001893 pInode->nLock--;
1894 assert( pInode->nLock>=0 );
1895 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001896 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001897 }
1898 }
drhf2f105d2012-08-20 15:53:54 +00001899
aswift5b1a2562008-08-22 00:22:35 +00001900end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001901 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001902 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001903 return rc;
drhbbd42a62004-05-22 17:41:58 +00001904}
1905
1906/*
drh308c2a52010-05-14 11:30:18 +00001907** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001908** must be either NO_LOCK or SHARED_LOCK.
1909**
1910** If the locking level of the file descriptor is already at or below
1911** the requested locking level, this routine is a no-op.
1912*/
drh308c2a52010-05-14 11:30:18 +00001913static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001914#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001915 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001916#endif
drha7e61d82011-03-12 17:02:57 +00001917 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001918}
1919
mistachkine98844f2013-08-24 00:59:24 +00001920#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001921static int unixMapfile(unixFile *pFd, i64 nByte);
1922static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001923#endif
danf23da962013-03-23 21:00:41 +00001924
drh7ed97b92010-01-20 13:07:21 +00001925/*
danielk1977e339d652008-06-28 11:23:00 +00001926** This function performs the parts of the "close file" operation
1927** common to all locking schemes. It closes the directory and file
1928** handles, if they are valid, and sets all fields of the unixFile
1929** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001930**
1931** It is *not* necessary to hold the mutex when this routine is called,
1932** even on VxWorks. A mutex will be acquired on VxWorks by the
1933** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001934*/
1935static int closeUnixFile(sqlite3_file *id){
1936 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001937#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001938 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001939#endif
dan661d71a2011-03-30 19:08:03 +00001940 if( pFile->h>=0 ){
1941 robust_close(pFile, pFile->h, __LINE__);
1942 pFile->h = -1;
1943 }
1944#if OS_VXWORKS
1945 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001946 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001947 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001948 }
1949 vxworksReleaseFileId(pFile->pId);
1950 pFile->pId = 0;
1951 }
1952#endif
drh0bdbc902014-06-16 18:35:06 +00001953#ifdef SQLITE_UNLINK_AFTER_CLOSE
1954 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1955 osUnlink(pFile->zPath);
1956 sqlite3_free(*(char**)&pFile->zPath);
1957 pFile->zPath = 0;
1958 }
1959#endif
dan661d71a2011-03-30 19:08:03 +00001960 OSTRACE(("CLOSE %-3d\n", pFile->h));
1961 OpenCounter(-1);
1962 sqlite3_free(pFile->pUnused);
1963 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001964 return SQLITE_OK;
1965}
1966
1967/*
danielk1977e3026632004-06-22 11:29:02 +00001968** Close a file.
1969*/
danielk197762079062007-08-15 17:08:46 +00001970static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001971 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001972 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001973 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001974 unixUnlock(id, NO_LOCK);
1975 unixEnterMutex();
1976
1977 /* unixFile.pInode is always valid here. Otherwise, a different close
1978 ** routine (e.g. nolockClose()) would be called instead.
1979 */
1980 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1981 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1982 /* If there are outstanding locks, do not actually close the file just
1983 ** yet because that would clear those locks. Instead, add the file
1984 ** descriptor to pInode->pUnused list. It will be automatically closed
1985 ** when the last lock is cleared.
1986 */
1987 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001988 }
dan661d71a2011-03-30 19:08:03 +00001989 releaseInodeInfo(pFile);
1990 rc = closeUnixFile(id);
1991 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001992 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001993}
1994
drh734c9862008-11-28 15:37:20 +00001995/************** End of the posix advisory lock implementation *****************
1996******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001997
drh734c9862008-11-28 15:37:20 +00001998/******************************************************************************
1999****************************** No-op Locking **********************************
2000**
2001** Of the various locking implementations available, this is by far the
2002** simplest: locking is ignored. No attempt is made to lock the database
2003** file for reading or writing.
2004**
2005** This locking mode is appropriate for use on read-only databases
2006** (ex: databases that are burned into CD-ROM, for example.) It can
2007** also be used if the application employs some external mechanism to
2008** prevent simultaneous access of the same database by two or more
2009** database connections. But there is a serious risk of database
2010** corruption if this locking mode is used in situations where multiple
2011** database connections are accessing the same database file at the same
2012** time and one or more of those connections are writing.
2013*/
drhbfe66312006-10-03 17:40:40 +00002014
drh734c9862008-11-28 15:37:20 +00002015static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2016 UNUSED_PARAMETER(NotUsed);
2017 *pResOut = 0;
2018 return SQLITE_OK;
2019}
drh734c9862008-11-28 15:37:20 +00002020static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2021 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2022 return SQLITE_OK;
2023}
drh734c9862008-11-28 15:37:20 +00002024static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2025 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2026 return SQLITE_OK;
2027}
2028
2029/*
drh9b35ea62008-11-29 02:20:26 +00002030** Close the file.
drh734c9862008-11-28 15:37:20 +00002031*/
2032static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002033 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002034}
2035
2036/******************* End of the no-op lock implementation *********************
2037******************************************************************************/
2038
2039/******************************************************************************
2040************************* Begin dot-file Locking ******************************
2041**
mistachkin48864df2013-03-21 21:20:32 +00002042** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002043** files (really a directory) to control access to the database. This works
2044** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002045**
2046** (1) There is zero concurrency. A single reader blocks all other
2047** connections from reading or writing the database.
2048**
2049** (2) An application crash or power loss can leave stale lock files
2050** sitting around that need to be cleared manually.
2051**
2052** Nevertheless, a dotlock is an appropriate locking mode for use if no
2053** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002054**
drh9ef6bc42011-11-04 02:24:02 +00002055** Dotfile locking works by creating a subdirectory in the same directory as
2056** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002057** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002058** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002059*/
2060
2061/*
2062** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002063** lock directory.
drh734c9862008-11-28 15:37:20 +00002064*/
2065#define DOTLOCK_SUFFIX ".lock"
2066
drh7708e972008-11-29 00:56:52 +00002067/*
2068** This routine checks if there is a RESERVED lock held on the specified
2069** file by this or any other process. If such a lock is held, set *pResOut
2070** to a non-zero value otherwise *pResOut is set to zero. The return value
2071** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2072**
2073** In dotfile locking, either a lock exists or it does not. So in this
2074** variation of CheckReservedLock(), *pResOut is set to true if any lock
2075** is held on the file and false if the file is unlocked.
2076*/
drh734c9862008-11-28 15:37:20 +00002077static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2078 int rc = SQLITE_OK;
2079 int reserved = 0;
2080 unixFile *pFile = (unixFile*)id;
2081
2082 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2083
2084 assert( pFile );
2085
2086 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002087 if( pFile->eFileLock>SHARED_LOCK ){
drh7708e972008-11-29 00:56:52 +00002088 /* Either this connection or some other connection in the same process
2089 ** holds a lock on the file. No need to check further. */
drh734c9862008-11-28 15:37:20 +00002090 reserved = 1;
drh7708e972008-11-29 00:56:52 +00002091 }else{
2092 /* The lock is held if and only if the lockfile exists */
2093 const char *zLockFile = (const char*)pFile->lockingContext;
drh99ab3b12011-03-02 15:09:07 +00002094 reserved = osAccess(zLockFile, 0)==0;
drh734c9862008-11-28 15:37:20 +00002095 }
drh308c2a52010-05-14 11:30:18 +00002096 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002097 *pResOut = reserved;
2098 return rc;
2099}
2100
drh7708e972008-11-29 00:56:52 +00002101/*
drh308c2a52010-05-14 11:30:18 +00002102** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002103** of the following:
2104**
2105** (1) SHARED_LOCK
2106** (2) RESERVED_LOCK
2107** (3) PENDING_LOCK
2108** (4) EXCLUSIVE_LOCK
2109**
2110** Sometimes when requesting one lock state, additional lock states
2111** are inserted in between. The locking might fail on one of the later
2112** transitions leaving the lock state different from what it started but
2113** still short of its goal. The following chart shows the allowed
2114** transitions and the inserted intermediate states:
2115**
2116** UNLOCKED -> SHARED
2117** SHARED -> RESERVED
2118** SHARED -> (PENDING) -> EXCLUSIVE
2119** RESERVED -> (PENDING) -> EXCLUSIVE
2120** PENDING -> EXCLUSIVE
2121**
2122** This routine will only increase a lock. Use the sqlite3OsUnlock()
2123** routine to lower a locking level.
2124**
2125** With dotfile locking, we really only support state (4): EXCLUSIVE.
2126** But we track the other locking levels internally.
2127*/
drh308c2a52010-05-14 11:30:18 +00002128static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002129 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002130 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002131 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002132
drh7708e972008-11-29 00:56:52 +00002133
2134 /* If we have any lock, then the lock file already exists. All we have
2135 ** to do is adjust our internal record of the lock level.
2136 */
drh308c2a52010-05-14 11:30:18 +00002137 if( pFile->eFileLock > NO_LOCK ){
2138 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002139 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002140#ifdef HAVE_UTIME
2141 utime(zLockFile, NULL);
2142#else
drh734c9862008-11-28 15:37:20 +00002143 utimes(zLockFile, NULL);
2144#endif
drh7708e972008-11-29 00:56:52 +00002145 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002146 }
2147
2148 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002149 rc = osMkdir(zLockFile, 0777);
2150 if( rc<0 ){
2151 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002152 int tErrno = errno;
2153 if( EEXIST == tErrno ){
2154 rc = SQLITE_BUSY;
2155 } else {
2156 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2157 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002158 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002159 }
2160 }
drh7708e972008-11-29 00:56:52 +00002161 return rc;
drh734c9862008-11-28 15:37:20 +00002162 }
drh734c9862008-11-28 15:37:20 +00002163
2164 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002165 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002166 return rc;
2167}
2168
drh7708e972008-11-29 00:56:52 +00002169/*
drh308c2a52010-05-14 11:30:18 +00002170** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002171** must be either NO_LOCK or SHARED_LOCK.
2172**
2173** If the locking level of the file descriptor is already at or below
2174** the requested locking level, this routine is a no-op.
2175**
2176** When the locking level reaches NO_LOCK, delete the lock file.
2177*/
drh308c2a52010-05-14 11:30:18 +00002178static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002179 unixFile *pFile = (unixFile*)id;
2180 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002181 int rc;
drh734c9862008-11-28 15:37:20 +00002182
2183 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002184 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002185 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002186 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002187
2188 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002189 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002190 return SQLITE_OK;
2191 }
drh7708e972008-11-29 00:56:52 +00002192
2193 /* To downgrade to shared, simply update our internal notion of the
2194 ** lock state. No need to mess with the file on disk.
2195 */
drh308c2a52010-05-14 11:30:18 +00002196 if( eFileLock==SHARED_LOCK ){
2197 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002198 return SQLITE_OK;
2199 }
2200
drh7708e972008-11-29 00:56:52 +00002201 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002202 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002203 rc = osRmdir(zLockFile);
2204 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
2205 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002206 int tErrno = errno;
drh13e0ea92011-12-11 02:29:25 +00002207 rc = 0;
drh734c9862008-11-28 15:37:20 +00002208 if( ENOENT != tErrno ){
danea83bc62011-04-01 11:56:32 +00002209 rc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002210 }
2211 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002212 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002213 }
2214 return rc;
2215 }
drh308c2a52010-05-14 11:30:18 +00002216 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002217 return SQLITE_OK;
2218}
2219
2220/*
drh9b35ea62008-11-29 02:20:26 +00002221** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002222*/
2223static int dotlockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002224 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002225 if( id ){
2226 unixFile *pFile = (unixFile*)id;
2227 dotlockUnlock(id, NO_LOCK);
2228 sqlite3_free(pFile->lockingContext);
drh5a05be12012-10-09 18:51:44 +00002229 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002230 }
drh734c9862008-11-28 15:37:20 +00002231 return rc;
2232}
2233/****************** End of the dot-file lock implementation *******************
2234******************************************************************************/
2235
2236/******************************************************************************
2237************************** Begin flock Locking ********************************
2238**
2239** Use the flock() system call to do file locking.
2240**
drh6b9d6dd2008-12-03 19:34:47 +00002241** flock() locking is like dot-file locking in that the various
2242** fine-grain locking levels supported by SQLite are collapsed into
2243** a single exclusive lock. In other words, SHARED, RESERVED, and
2244** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2245** still works when you do this, but concurrency is reduced since
2246** only a single process can be reading the database at a time.
2247**
drhe89b2912015-03-03 20:42:01 +00002248** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002249*/
drhe89b2912015-03-03 20:42:01 +00002250#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002251
drh6b9d6dd2008-12-03 19:34:47 +00002252/*
drhff812312011-02-23 13:33:46 +00002253** Retry flock() calls that fail with EINTR
2254*/
2255#ifdef EINTR
2256static int robust_flock(int fd, int op){
2257 int rc;
2258 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2259 return rc;
2260}
2261#else
drh5c819272011-02-23 14:00:12 +00002262# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002263#endif
2264
2265
2266/*
drh6b9d6dd2008-12-03 19:34:47 +00002267** This routine checks if there is a RESERVED lock held on the specified
2268** file by this or any other process. If such a lock is held, set *pResOut
2269** to a non-zero value otherwise *pResOut is set to zero. The return value
2270** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2271*/
drh734c9862008-11-28 15:37:20 +00002272static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2273 int rc = SQLITE_OK;
2274 int reserved = 0;
2275 unixFile *pFile = (unixFile*)id;
2276
2277 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2278
2279 assert( pFile );
2280
2281 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002282 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002283 reserved = 1;
2284 }
2285
2286 /* Otherwise see if some other process holds it. */
2287 if( !reserved ){
2288 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002289 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002290 if( !lrc ){
2291 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002292 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002293 if ( lrc ) {
2294 int tErrno = errno;
2295 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002296 lrc = SQLITE_IOERR_UNLOCK;
drh734c9862008-11-28 15:37:20 +00002297 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002298 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002299 rc = lrc;
2300 }
2301 }
2302 } else {
2303 int tErrno = errno;
2304 reserved = 1;
2305 /* someone else might have it reserved */
2306 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2307 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002308 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002309 rc = lrc;
2310 }
2311 }
2312 }
drh308c2a52010-05-14 11:30:18 +00002313 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002314
2315#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2316 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2317 rc = SQLITE_OK;
2318 reserved=1;
2319 }
2320#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2321 *pResOut = reserved;
2322 return rc;
2323}
2324
drh6b9d6dd2008-12-03 19:34:47 +00002325/*
drh308c2a52010-05-14 11:30:18 +00002326** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002327** of the following:
2328**
2329** (1) SHARED_LOCK
2330** (2) RESERVED_LOCK
2331** (3) PENDING_LOCK
2332** (4) EXCLUSIVE_LOCK
2333**
2334** Sometimes when requesting one lock state, additional lock states
2335** are inserted in between. The locking might fail on one of the later
2336** transitions leaving the lock state different from what it started but
2337** still short of its goal. The following chart shows the allowed
2338** transitions and the inserted intermediate states:
2339**
2340** UNLOCKED -> SHARED
2341** SHARED -> RESERVED
2342** SHARED -> (PENDING) -> EXCLUSIVE
2343** RESERVED -> (PENDING) -> EXCLUSIVE
2344** PENDING -> EXCLUSIVE
2345**
2346** flock() only really support EXCLUSIVE locks. We track intermediate
2347** lock states in the sqlite3_file structure, but all locks SHARED or
2348** above are really EXCLUSIVE locks and exclude all other processes from
2349** access the file.
2350**
2351** This routine will only increase a lock. Use the sqlite3OsUnlock()
2352** routine to lower a locking level.
2353*/
drh308c2a52010-05-14 11:30:18 +00002354static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002355 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002356 unixFile *pFile = (unixFile*)id;
2357
2358 assert( pFile );
2359
2360 /* if we already have a lock, it is exclusive.
2361 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002362 if (pFile->eFileLock > NO_LOCK) {
2363 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002364 return SQLITE_OK;
2365 }
2366
2367 /* grab an exclusive lock */
2368
drhff812312011-02-23 13:33:46 +00002369 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002370 int tErrno = errno;
2371 /* didn't get, must be busy */
2372 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2373 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002374 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002375 }
2376 } else {
2377 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002378 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002379 }
drh308c2a52010-05-14 11:30:18 +00002380 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2381 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002382#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2383 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2384 rc = SQLITE_BUSY;
2385 }
2386#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2387 return rc;
2388}
2389
drh6b9d6dd2008-12-03 19:34:47 +00002390
2391/*
drh308c2a52010-05-14 11:30:18 +00002392** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002393** must be either NO_LOCK or SHARED_LOCK.
2394**
2395** If the locking level of the file descriptor is already at or below
2396** the requested locking level, this routine is a no-op.
2397*/
drh308c2a52010-05-14 11:30:18 +00002398static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002399 unixFile *pFile = (unixFile*)id;
2400
2401 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002402 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002403 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002404 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002405
2406 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002407 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002408 return SQLITE_OK;
2409 }
2410
2411 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002412 if (eFileLock==SHARED_LOCK) {
2413 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002414 return SQLITE_OK;
2415 }
2416
2417 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002418 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002419#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002420 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002421#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002422 return SQLITE_IOERR_UNLOCK;
2423 }else{
drh308c2a52010-05-14 11:30:18 +00002424 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002425 return SQLITE_OK;
2426 }
2427}
2428
2429/*
2430** Close a file.
2431*/
2432static int flockClose(sqlite3_file *id) {
drh5a05be12012-10-09 18:51:44 +00002433 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002434 if( id ){
2435 flockUnlock(id, NO_LOCK);
drh5a05be12012-10-09 18:51:44 +00002436 rc = closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002437 }
drh5a05be12012-10-09 18:51:44 +00002438 return rc;
drh734c9862008-11-28 15:37:20 +00002439}
2440
2441#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2442
2443/******************* End of the flock lock implementation *********************
2444******************************************************************************/
2445
2446/******************************************************************************
2447************************ Begin Named Semaphore Locking ************************
2448**
2449** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002450**
2451** Semaphore locking is like dot-lock and flock in that it really only
2452** supports EXCLUSIVE locking. Only a single process can read or write
2453** the database file at a time. This reduces potential concurrency, but
2454** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002455*/
2456#if OS_VXWORKS
2457
drh6b9d6dd2008-12-03 19:34:47 +00002458/*
2459** This routine checks if there is a RESERVED lock held on the specified
2460** file by this or any other process. If such a lock is held, set *pResOut
2461** to a non-zero value otherwise *pResOut is set to zero. The return value
2462** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2463*/
drh8cd5b252015-03-02 22:06:43 +00002464static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002465 int rc = SQLITE_OK;
2466 int reserved = 0;
2467 unixFile *pFile = (unixFile*)id;
2468
2469 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2470
2471 assert( pFile );
2472
2473 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002474 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002475 reserved = 1;
2476 }
2477
2478 /* Otherwise see if some other process holds it. */
2479 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002480 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002481
2482 if( sem_trywait(pSem)==-1 ){
2483 int tErrno = errno;
2484 if( EAGAIN != tErrno ){
2485 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002486 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002487 } else {
2488 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002489 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002490 }
2491 }else{
2492 /* we could have it if we want it */
2493 sem_post(pSem);
2494 }
2495 }
drh308c2a52010-05-14 11:30:18 +00002496 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002497
2498 *pResOut = reserved;
2499 return rc;
2500}
2501
drh6b9d6dd2008-12-03 19:34:47 +00002502/*
drh308c2a52010-05-14 11:30:18 +00002503** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002504** of the following:
2505**
2506** (1) SHARED_LOCK
2507** (2) RESERVED_LOCK
2508** (3) PENDING_LOCK
2509** (4) EXCLUSIVE_LOCK
2510**
2511** Sometimes when requesting one lock state, additional lock states
2512** are inserted in between. The locking might fail on one of the later
2513** transitions leaving the lock state different from what it started but
2514** still short of its goal. The following chart shows the allowed
2515** transitions and the inserted intermediate states:
2516**
2517** UNLOCKED -> SHARED
2518** SHARED -> RESERVED
2519** SHARED -> (PENDING) -> EXCLUSIVE
2520** RESERVED -> (PENDING) -> EXCLUSIVE
2521** PENDING -> EXCLUSIVE
2522**
2523** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2524** lock states in the sqlite3_file structure, but all locks SHARED or
2525** above are really EXCLUSIVE locks and exclude all other processes from
2526** access the file.
2527**
2528** This routine will only increase a lock. Use the sqlite3OsUnlock()
2529** routine to lower a locking level.
2530*/
drh8cd5b252015-03-02 22:06:43 +00002531static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002532 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002533 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002534 int rc = SQLITE_OK;
2535
2536 /* if we already have a lock, it is exclusive.
2537 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002538 if (pFile->eFileLock > NO_LOCK) {
2539 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002540 rc = SQLITE_OK;
2541 goto sem_end_lock;
2542 }
2543
2544 /* lock semaphore now but bail out when already locked. */
2545 if( sem_trywait(pSem)==-1 ){
2546 rc = SQLITE_BUSY;
2547 goto sem_end_lock;
2548 }
2549
2550 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002551 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002552
2553 sem_end_lock:
2554 return rc;
2555}
2556
drh6b9d6dd2008-12-03 19:34:47 +00002557/*
drh308c2a52010-05-14 11:30:18 +00002558** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002559** must be either NO_LOCK or SHARED_LOCK.
2560**
2561** If the locking level of the file descriptor is already at or below
2562** the requested locking level, this routine is a no-op.
2563*/
drh8cd5b252015-03-02 22:06:43 +00002564static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002565 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002566 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002567
2568 assert( pFile );
2569 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002570 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002571 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002572 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002573
2574 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002575 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002576 return SQLITE_OK;
2577 }
2578
2579 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002580 if (eFileLock==SHARED_LOCK) {
2581 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002582 return SQLITE_OK;
2583 }
2584
2585 /* no, really unlock. */
2586 if ( sem_post(pSem)==-1 ) {
2587 int rc, tErrno = errno;
2588 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2589 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002590 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002591 }
2592 return rc;
2593 }
drh308c2a52010-05-14 11:30:18 +00002594 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002595 return SQLITE_OK;
2596}
2597
2598/*
2599 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002600 */
drh8cd5b252015-03-02 22:06:43 +00002601static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002602 if( id ){
2603 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002604 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002605 assert( pFile );
2606 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002607 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002608 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002609 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002610 }
2611 return SQLITE_OK;
2612}
2613
2614#endif /* OS_VXWORKS */
2615/*
2616** Named semaphore locking is only available on VxWorks.
2617**
2618*************** End of the named semaphore lock implementation ****************
2619******************************************************************************/
2620
2621
2622/******************************************************************************
2623*************************** Begin AFP Locking *********************************
2624**
2625** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2626** on Apple Macintosh computers - both OS9 and OSX.
2627**
2628** Third-party implementations of AFP are available. But this code here
2629** only works on OSX.
2630*/
2631
drhd2cb50b2009-01-09 21:41:17 +00002632#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002633/*
2634** The afpLockingContext structure contains all afp lock specific state
2635*/
drhbfe66312006-10-03 17:40:40 +00002636typedef struct afpLockingContext afpLockingContext;
2637struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002638 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002639 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002640};
2641
2642struct ByteRangeLockPB2
2643{
2644 unsigned long long offset; /* offset to first byte to lock */
2645 unsigned long long length; /* nbr of bytes to lock */
2646 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2647 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2648 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2649 int fd; /* file desc to assoc this lock with */
2650};
2651
drhfd131da2007-08-07 17:13:03 +00002652#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002653
drh6b9d6dd2008-12-03 19:34:47 +00002654/*
2655** This is a utility for setting or clearing a bit-range lock on an
2656** AFP filesystem.
2657**
2658** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2659*/
2660static int afpSetLock(
2661 const char *path, /* Name of the file to be locked or unlocked */
2662 unixFile *pFile, /* Open file descriptor on path */
2663 unsigned long long offset, /* First byte to be locked */
2664 unsigned long long length, /* Number of bytes to lock */
2665 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002666){
drh6b9d6dd2008-12-03 19:34:47 +00002667 struct ByteRangeLockPB2 pb;
2668 int err;
drhbfe66312006-10-03 17:40:40 +00002669
2670 pb.unLockFlag = setLockFlag ? 0 : 1;
2671 pb.startEndFlag = 0;
2672 pb.offset = offset;
2673 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002674 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002675
drh308c2a52010-05-14 11:30:18 +00002676 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002677 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002678 offset, length));
drhbfe66312006-10-03 17:40:40 +00002679 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2680 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002681 int rc;
2682 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002683 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2684 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002685#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2686 rc = SQLITE_BUSY;
2687#else
drh734c9862008-11-28 15:37:20 +00002688 rc = sqliteErrorFromPosixError(tErrno,
2689 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002690#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002691 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002692 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002693 }
2694 return rc;
drhbfe66312006-10-03 17:40:40 +00002695 } else {
aswift5b1a2562008-08-22 00:22:35 +00002696 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002697 }
2698}
2699
drh6b9d6dd2008-12-03 19:34:47 +00002700/*
2701** This routine checks if there is a RESERVED lock held on the specified
2702** file by this or any other process. If such a lock is held, set *pResOut
2703** to a non-zero value otherwise *pResOut is set to zero. The return value
2704** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2705*/
danielk1977e339d652008-06-28 11:23:00 +00002706static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002707 int rc = SQLITE_OK;
2708 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002709 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002710 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002711
aswift5b1a2562008-08-22 00:22:35 +00002712 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2713
2714 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002715 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002716 if( context->reserved ){
2717 *pResOut = 1;
2718 return SQLITE_OK;
2719 }
drh8af6c222010-05-14 12:43:01 +00002720 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002721
2722 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002723 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002724 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002725 }
2726
2727 /* Otherwise see if some other process holds it.
2728 */
aswift5b1a2562008-08-22 00:22:35 +00002729 if( !reserved ){
2730 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002731 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002732 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002733 /* if we succeeded in taking the reserved lock, unlock it to restore
2734 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002735 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002736 } else {
2737 /* if we failed to get the lock then someone else must have it */
2738 reserved = 1;
2739 }
2740 if( IS_LOCK_ERROR(lrc) ){
2741 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002742 }
2743 }
drhbfe66312006-10-03 17:40:40 +00002744
drh7ed97b92010-01-20 13:07:21 +00002745 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002746 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002747
2748 *pResOut = reserved;
2749 return rc;
drhbfe66312006-10-03 17:40:40 +00002750}
2751
drh6b9d6dd2008-12-03 19:34:47 +00002752/*
drh308c2a52010-05-14 11:30:18 +00002753** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002754** of the following:
2755**
2756** (1) SHARED_LOCK
2757** (2) RESERVED_LOCK
2758** (3) PENDING_LOCK
2759** (4) EXCLUSIVE_LOCK
2760**
2761** Sometimes when requesting one lock state, additional lock states
2762** are inserted in between. The locking might fail on one of the later
2763** transitions leaving the lock state different from what it started but
2764** still short of its goal. The following chart shows the allowed
2765** transitions and the inserted intermediate states:
2766**
2767** UNLOCKED -> SHARED
2768** SHARED -> RESERVED
2769** SHARED -> (PENDING) -> EXCLUSIVE
2770** RESERVED -> (PENDING) -> EXCLUSIVE
2771** PENDING -> EXCLUSIVE
2772**
2773** This routine will only increase a lock. Use the sqlite3OsUnlock()
2774** routine to lower a locking level.
2775*/
drh308c2a52010-05-14 11:30:18 +00002776static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002777 int rc = SQLITE_OK;
2778 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002779 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002780 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002781
2782 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002783 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2784 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002785 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002786
drhbfe66312006-10-03 17:40:40 +00002787 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002788 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002789 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002790 */
drh308c2a52010-05-14 11:30:18 +00002791 if( pFile->eFileLock>=eFileLock ){
2792 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2793 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002794 return SQLITE_OK;
2795 }
2796
2797 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002798 ** (1) We never move from unlocked to anything higher than shared lock.
2799 ** (2) SQLite never explicitly requests a pendig lock.
2800 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002801 */
drh308c2a52010-05-14 11:30:18 +00002802 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2803 assert( eFileLock!=PENDING_LOCK );
2804 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002805
drh8af6c222010-05-14 12:43:01 +00002806 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002807 */
drh6c7d5c52008-11-21 20:32:33 +00002808 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002809 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002810
2811 /* If some thread using this PID has a lock via a different unixFile*
2812 ** handle that precludes the requested lock, return BUSY.
2813 */
drh8af6c222010-05-14 12:43:01 +00002814 if( (pFile->eFileLock!=pInode->eFileLock &&
2815 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002816 ){
2817 rc = SQLITE_BUSY;
2818 goto afp_end_lock;
2819 }
2820
2821 /* If a SHARED lock is requested, and some thread using this PID already
2822 ** has a SHARED or RESERVED lock, then increment reference counts and
2823 ** return SQLITE_OK.
2824 */
drh308c2a52010-05-14 11:30:18 +00002825 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002826 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002827 assert( eFileLock==SHARED_LOCK );
2828 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002829 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002830 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002831 pInode->nShared++;
2832 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002833 goto afp_end_lock;
2834 }
drhbfe66312006-10-03 17:40:40 +00002835
2836 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002837 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2838 ** be released.
2839 */
drh308c2a52010-05-14 11:30:18 +00002840 if( eFileLock==SHARED_LOCK
2841 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002842 ){
2843 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002844 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002845 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002846 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002847 goto afp_end_lock;
2848 }
2849 }
2850
2851 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002852 ** operating system calls for the specified lock.
2853 */
drh308c2a52010-05-14 11:30:18 +00002854 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002855 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002856 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002857
drh8af6c222010-05-14 12:43:01 +00002858 assert( pInode->nShared==0 );
2859 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002860
2861 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002862 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002863 /* note that the quality of the randomness doesn't matter that much */
2864 lk = random();
drh8af6c222010-05-14 12:43:01 +00002865 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002866 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002867 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002868 if( IS_LOCK_ERROR(lrc1) ){
2869 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002870 }
aswift5b1a2562008-08-22 00:22:35 +00002871 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002872 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002873
aswift5b1a2562008-08-22 00:22:35 +00002874 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002875 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002876 rc = lrc1;
2877 goto afp_end_lock;
2878 } else if( IS_LOCK_ERROR(lrc2) ){
2879 rc = lrc2;
2880 goto afp_end_lock;
2881 } else if( lrc1 != SQLITE_OK ) {
2882 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002883 } else {
drh308c2a52010-05-14 11:30:18 +00002884 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002885 pInode->nLock++;
2886 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002887 }
drh8af6c222010-05-14 12:43:01 +00002888 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002889 /* We are trying for an exclusive lock but another thread in this
2890 ** same process is still holding a shared lock. */
2891 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002892 }else{
2893 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2894 ** assumed that there is a SHARED or greater lock on the file
2895 ** already.
2896 */
2897 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002898 assert( 0!=pFile->eFileLock );
2899 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002900 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002901 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002902 if( !failed ){
2903 context->reserved = 1;
2904 }
drhbfe66312006-10-03 17:40:40 +00002905 }
drh308c2a52010-05-14 11:30:18 +00002906 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002907 /* Acquire an EXCLUSIVE lock */
2908
2909 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002910 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002911 */
drh6b9d6dd2008-12-03 19:34:47 +00002912 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002913 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002914 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002915 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002916 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002917 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002918 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002919 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002920 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2921 ** a critical I/O error
2922 */
2923 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2924 SQLITE_IOERR_LOCK;
2925 goto afp_end_lock;
2926 }
2927 }else{
aswift5b1a2562008-08-22 00:22:35 +00002928 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002929 }
2930 }
aswift5b1a2562008-08-22 00:22:35 +00002931 if( failed ){
2932 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002933 }
2934 }
2935
2936 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002937 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002938 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002939 }else if( eFileLock==EXCLUSIVE_LOCK ){
2940 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002941 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002942 }
2943
2944afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002945 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002946 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2947 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002948 return rc;
2949}
2950
2951/*
drh308c2a52010-05-14 11:30:18 +00002952** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002953** must be either NO_LOCK or SHARED_LOCK.
2954**
2955** If the locking level of the file descriptor is already at or below
2956** the requested locking level, this routine is a no-op.
2957*/
drh308c2a52010-05-14 11:30:18 +00002958static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002959 int rc = SQLITE_OK;
2960 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002961 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002962 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2963 int skipShared = 0;
2964#ifdef SQLITE_TEST
2965 int h = pFile->h;
2966#endif
drhbfe66312006-10-03 17:40:40 +00002967
2968 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002969 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002970 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002971 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002972
drh308c2a52010-05-14 11:30:18 +00002973 assert( eFileLock<=SHARED_LOCK );
2974 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002975 return SQLITE_OK;
2976 }
drh6c7d5c52008-11-21 20:32:33 +00002977 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002978 pInode = pFile->pInode;
2979 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002980 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002981 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002982 SimulateIOErrorBenign(1);
2983 SimulateIOError( h=(-1) )
2984 SimulateIOErrorBenign(0);
2985
drhd3d8c042012-05-29 17:02:40 +00002986#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002987 /* When reducing a lock such that other processes can start
2988 ** reading the database file again, make sure that the
2989 ** transaction counter was updated if any part of the database
2990 ** file changed. If the transaction counter is not updated,
2991 ** other connections to the same file might not realize that
2992 ** the file has changed and hence might not know to flush their
2993 ** cache. The use of a stale cache can lead to database corruption.
2994 */
2995 assert( pFile->inNormalWrite==0
2996 || pFile->dbUpdate==0
2997 || pFile->transCntrChng==1 );
2998 pFile->inNormalWrite = 0;
2999#endif
aswiftaebf4132008-11-21 00:10:35 +00003000
drh308c2a52010-05-14 11:30:18 +00003001 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003002 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003003 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003004 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003005 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003006 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3007 } else {
3008 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003009 }
3010 }
drh308c2a52010-05-14 11:30:18 +00003011 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003012 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003013 }
drh308c2a52010-05-14 11:30:18 +00003014 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003015 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3016 if( !rc ){
3017 context->reserved = 0;
3018 }
aswiftaebf4132008-11-21 00:10:35 +00003019 }
drh8af6c222010-05-14 12:43:01 +00003020 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3021 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003022 }
aswiftaebf4132008-11-21 00:10:35 +00003023 }
drh308c2a52010-05-14 11:30:18 +00003024 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003025
drh7ed97b92010-01-20 13:07:21 +00003026 /* Decrement the shared lock counter. Release the lock using an
3027 ** OS call only when all threads in this same process have released
3028 ** the lock.
3029 */
drh8af6c222010-05-14 12:43:01 +00003030 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3031 pInode->nShared--;
3032 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003033 SimulateIOErrorBenign(1);
3034 SimulateIOError( h=(-1) )
3035 SimulateIOErrorBenign(0);
3036 if( !skipShared ){
3037 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3038 }
3039 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003040 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003041 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003042 }
3043 }
3044 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003045 pInode->nLock--;
3046 assert( pInode->nLock>=0 );
3047 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003048 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003049 }
3050 }
drhbfe66312006-10-03 17:40:40 +00003051 }
drh7ed97b92010-01-20 13:07:21 +00003052
drh6c7d5c52008-11-21 20:32:33 +00003053 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003054 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003055 return rc;
3056}
3057
3058/*
drh339eb0b2008-03-07 15:34:11 +00003059** Close a file & cleanup AFP specific locking context
3060*/
danielk1977e339d652008-06-28 11:23:00 +00003061static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003062 int rc = SQLITE_OK;
danielk1977e339d652008-06-28 11:23:00 +00003063 if( id ){
3064 unixFile *pFile = (unixFile*)id;
3065 afpUnlock(id, NO_LOCK);
drh6c7d5c52008-11-21 20:32:33 +00003066 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00003067 if( pFile->pInode && pFile->pInode->nLock ){
aswiftaebf4132008-11-21 00:10:35 +00003068 /* If there are outstanding locks, do not actually close the file just
drh734c9862008-11-28 15:37:20 +00003069 ** yet because that would clear those locks. Instead, add the file
drh8af6c222010-05-14 12:43:01 +00003070 ** descriptor to pInode->aPending. It will be automatically closed when
drh734c9862008-11-28 15:37:20 +00003071 ** the last lock is cleared.
3072 */
dan08da86a2009-08-21 17:18:03 +00003073 setPendingFd(pFile);
aswiftaebf4132008-11-21 00:10:35 +00003074 }
danb0ac3e32010-06-16 10:55:42 +00003075 releaseInodeInfo(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003076 sqlite3_free(pFile->lockingContext);
drh7ed97b92010-01-20 13:07:21 +00003077 rc = closeUnixFile(id);
drh6c7d5c52008-11-21 20:32:33 +00003078 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00003079 }
drh7ed97b92010-01-20 13:07:21 +00003080 return rc;
drhbfe66312006-10-03 17:40:40 +00003081}
3082
drhd2cb50b2009-01-09 21:41:17 +00003083#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003084/*
3085** The code above is the AFP lock implementation. The code is specific
3086** to MacOSX and does not work on other unix platforms. No alternative
3087** is available. If you don't compile for a mac, then the "unix-afp"
3088** VFS is not available.
3089**
3090********************* End of the AFP lock implementation **********************
3091******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003092
drh7ed97b92010-01-20 13:07:21 +00003093/******************************************************************************
3094*************************** Begin NFS Locking ********************************/
3095
3096#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3097/*
drh308c2a52010-05-14 11:30:18 +00003098 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003099 ** must be either NO_LOCK or SHARED_LOCK.
3100 **
3101 ** If the locking level of the file descriptor is already at or below
3102 ** the requested locking level, this routine is a no-op.
3103 */
drh308c2a52010-05-14 11:30:18 +00003104static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003105 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003106}
3107
3108#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3109/*
3110** The code above is the NFS lock implementation. The code is specific
3111** to MacOSX and does not work on other unix platforms. No alternative
3112** is available.
3113**
3114********************* End of the NFS lock implementation **********************
3115******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003116
3117/******************************************************************************
3118**************** Non-locking sqlite3_file methods *****************************
3119**
3120** The next division contains implementations for all methods of the
3121** sqlite3_file object other than the locking methods. The locking
3122** methods were defined in divisions above (one locking method per
3123** division). Those methods that are common to all locking modes
3124** are gather together into this division.
3125*/
drhbfe66312006-10-03 17:40:40 +00003126
3127/*
drh734c9862008-11-28 15:37:20 +00003128** Seek to the offset passed as the second argument, then read cnt
3129** bytes into pBuf. Return the number of bytes actually read.
3130**
3131** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3132** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3133** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003134** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003135** See tickets #2741 and #2681.
3136**
3137** To avoid stomping the errno value on a failed read the lastErrno value
3138** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003139*/
drh734c9862008-11-28 15:37:20 +00003140static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3141 int got;
drh58024642011-11-07 18:16:00 +00003142 int prior = 0;
drh7ed97b92010-01-20 13:07:21 +00003143#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
drh734c9862008-11-28 15:37:20 +00003144 i64 newOffset;
drh7ed97b92010-01-20 13:07:21 +00003145#endif
drh734c9862008-11-28 15:37:20 +00003146 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003147 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003148 assert( id->h>2 );
drhc1fd2cf2012-10-01 12:16:26 +00003149 cnt &= 0x1ffff;
drh58024642011-11-07 18:16:00 +00003150 do{
drh734c9862008-11-28 15:37:20 +00003151#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003152 got = osPread(id->h, pBuf, cnt, offset);
3153 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003154#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003155 got = osPread64(id->h, pBuf, cnt, offset);
3156 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003157#else
drh58024642011-11-07 18:16:00 +00003158 newOffset = lseek(id->h, offset, SEEK_SET);
3159 SimulateIOError( newOffset-- );
3160 if( newOffset!=offset ){
3161 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003162 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003163 }else{
drh4bf66fd2015-02-19 02:43:02 +00003164 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003165 }
3166 return -1;
drh734c9862008-11-28 15:37:20 +00003167 }
drh58024642011-11-07 18:16:00 +00003168 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003169#endif
drh58024642011-11-07 18:16:00 +00003170 if( got==cnt ) break;
3171 if( got<0 ){
3172 if( errno==EINTR ){ got = 1; continue; }
3173 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003174 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003175 break;
3176 }else if( got>0 ){
3177 cnt -= got;
3178 offset += got;
3179 prior += got;
3180 pBuf = (void*)(got + (char*)pBuf);
3181 }
3182 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003183 TIMER_END;
drh58024642011-11-07 18:16:00 +00003184 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3185 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3186 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003187}
3188
3189/*
drh734c9862008-11-28 15:37:20 +00003190** Read data from a file into a buffer. Return SQLITE_OK if all
3191** bytes were read successfully and SQLITE_IOERR if anything goes
3192** wrong.
drh339eb0b2008-03-07 15:34:11 +00003193*/
drh734c9862008-11-28 15:37:20 +00003194static int unixRead(
3195 sqlite3_file *id,
3196 void *pBuf,
3197 int amt,
3198 sqlite3_int64 offset
3199){
dan08da86a2009-08-21 17:18:03 +00003200 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003201 int got;
3202 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003203 assert( offset>=0 );
3204 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003205
dan08da86a2009-08-21 17:18:03 +00003206 /* If this is a database file (not a journal, master-journal or temp
3207 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003208#if 0
dane946c392009-08-22 11:39:46 +00003209 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003210 || offset>=PENDING_BYTE+512
3211 || offset+amt<=PENDING_BYTE
3212 );
dan7c246102010-04-12 19:00:29 +00003213#endif
drh08c6d442009-02-09 17:34:07 +00003214
drh9b4c59f2013-04-15 17:03:42 +00003215#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003216 /* Deal with as much of this read request as possible by transfering
3217 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003218 if( offset<pFile->mmapSize ){
3219 if( offset+amt <= pFile->mmapSize ){
3220 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3221 return SQLITE_OK;
3222 }else{
3223 int nCopy = pFile->mmapSize - offset;
3224 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3225 pBuf = &((u8 *)pBuf)[nCopy];
3226 amt -= nCopy;
3227 offset += nCopy;
3228 }
3229 }
drh6e0b6d52013-04-09 16:19:20 +00003230#endif
danf23da962013-03-23 21:00:41 +00003231
dan08da86a2009-08-21 17:18:03 +00003232 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003233 if( got==amt ){
3234 return SQLITE_OK;
3235 }else if( got<0 ){
3236 /* lastErrno set by seekAndRead */
3237 return SQLITE_IOERR_READ;
3238 }else{
drh4bf66fd2015-02-19 02:43:02 +00003239 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003240 /* Unread parts of the buffer must be zero-filled */
3241 memset(&((char*)pBuf)[got], 0, amt-got);
3242 return SQLITE_IOERR_SHORT_READ;
3243 }
3244}
3245
3246/*
dan47a2b4a2013-04-26 16:09:29 +00003247** Attempt to seek the file-descriptor passed as the first argument to
3248** absolute offset iOff, then attempt to write nBuf bytes of data from
3249** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3250** return the actual number of bytes written (which may be less than
3251** nBuf).
3252*/
3253static int seekAndWriteFd(
3254 int fd, /* File descriptor to write to */
3255 i64 iOff, /* File offset to begin writing at */
3256 const void *pBuf, /* Copy data from this buffer to the file */
3257 int nBuf, /* Size of buffer pBuf in bytes */
3258 int *piErrno /* OUT: Error number if error occurs */
3259){
3260 int rc = 0; /* Value returned by system call */
3261
3262 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003263 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003264 nBuf &= 0x1ffff;
3265 TIMER_START;
3266
3267#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003268 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003269#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003270 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003271#else
3272 do{
3273 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3274 SimulateIOError( iSeek-- );
3275
3276 if( iSeek!=iOff ){
3277 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3278 return -1;
3279 }
3280 rc = osWrite(fd, pBuf, nBuf);
3281 }while( rc<0 && errno==EINTR );
3282#endif
3283
3284 TIMER_END;
3285 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3286
3287 if( rc<0 && piErrno ) *piErrno = errno;
3288 return rc;
3289}
3290
3291
3292/*
drh734c9862008-11-28 15:37:20 +00003293** Seek to the offset in id->offset then read cnt bytes into pBuf.
3294** Return the number of bytes actually read. Update the offset.
3295**
3296** To avoid stomping the errno value on a failed write the lastErrno value
3297** is set before returning.
3298*/
3299static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003300 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003301}
3302
3303
3304/*
3305** Write data from a buffer into a file. Return SQLITE_OK on success
3306** or some other error code on failure.
3307*/
3308static int unixWrite(
3309 sqlite3_file *id,
3310 const void *pBuf,
3311 int amt,
3312 sqlite3_int64 offset
3313){
dan08da86a2009-08-21 17:18:03 +00003314 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003315 int wrote = 0;
3316 assert( id );
3317 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003318
dan08da86a2009-08-21 17:18:03 +00003319 /* If this is a database file (not a journal, master-journal or temp
3320 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003321#if 0
dane946c392009-08-22 11:39:46 +00003322 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003323 || offset>=PENDING_BYTE+512
3324 || offset+amt<=PENDING_BYTE
3325 );
dan7c246102010-04-12 19:00:29 +00003326#endif
drh08c6d442009-02-09 17:34:07 +00003327
drhd3d8c042012-05-29 17:02:40 +00003328#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003329 /* If we are doing a normal write to a database file (as opposed to
3330 ** doing a hot-journal rollback or a write to some file other than a
3331 ** normal database file) then record the fact that the database
3332 ** has changed. If the transaction counter is modified, record that
3333 ** fact too.
3334 */
dan08da86a2009-08-21 17:18:03 +00003335 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003336 pFile->dbUpdate = 1; /* The database has been modified */
3337 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003338 int rc;
drh8f941bc2009-01-14 23:03:40 +00003339 char oldCntr[4];
3340 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003341 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003342 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003343 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003344 pFile->transCntrChng = 1; /* The transaction counter has changed */
3345 }
3346 }
3347 }
3348#endif
3349
drh9b4c59f2013-04-15 17:03:42 +00003350#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003351 /* Deal with as much of this write request as possible by transfering
3352 ** data from the memory mapping using memcpy(). */
3353 if( offset<pFile->mmapSize ){
3354 if( offset+amt <= pFile->mmapSize ){
3355 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3356 return SQLITE_OK;
3357 }else{
3358 int nCopy = pFile->mmapSize - offset;
3359 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3360 pBuf = &((u8 *)pBuf)[nCopy];
3361 amt -= nCopy;
3362 offset += nCopy;
3363 }
3364 }
drh6e0b6d52013-04-09 16:19:20 +00003365#endif
danf23da962013-03-23 21:00:41 +00003366
dan08da86a2009-08-21 17:18:03 +00003367 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
drh734c9862008-11-28 15:37:20 +00003368 amt -= wrote;
3369 offset += wrote;
3370 pBuf = &((char*)pBuf)[wrote];
3371 }
3372 SimulateIOError(( wrote=(-1), amt=1 ));
3373 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003374
drh734c9862008-11-28 15:37:20 +00003375 if( amt>0 ){
drha21b83b2011-04-15 12:36:10 +00003376 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003377 /* lastErrno set by seekAndWrite */
3378 return SQLITE_IOERR_WRITE;
3379 }else{
drh4bf66fd2015-02-19 02:43:02 +00003380 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003381 return SQLITE_FULL;
3382 }
3383 }
dan6e09d692010-07-27 18:34:15 +00003384
drh734c9862008-11-28 15:37:20 +00003385 return SQLITE_OK;
3386}
3387
3388#ifdef SQLITE_TEST
3389/*
3390** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003391** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003392*/
3393int sqlite3_sync_count = 0;
3394int sqlite3_fullsync_count = 0;
3395#endif
3396
3397/*
drh89240432009-03-25 01:06:01 +00003398** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003399** Others do no. To be safe, we will stick with the (slightly slower)
3400** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003401** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003402*/
drhf7a4a1b2015-01-10 18:02:45 +00003403#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003404# define fdatasync fsync
3405#endif
3406
3407/*
3408** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3409** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3410** only available on Mac OS X. But that could change.
3411*/
3412#ifdef F_FULLFSYNC
3413# define HAVE_FULLFSYNC 1
3414#else
3415# define HAVE_FULLFSYNC 0
3416#endif
3417
3418
3419/*
3420** The fsync() system call does not work as advertised on many
3421** unix systems. The following procedure is an attempt to make
3422** it work better.
3423**
3424** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3425** for testing when we want to run through the test suite quickly.
3426** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3427** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3428** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003429**
3430** SQLite sets the dataOnly flag if the size of the file is unchanged.
3431** The idea behind dataOnly is that it should only write the file content
3432** to disk, not the inode. We only set dataOnly if the file size is
3433** unchanged since the file size is part of the inode. However,
3434** Ted Ts'o tells us that fdatasync() will also write the inode if the
3435** file size has changed. The only real difference between fdatasync()
3436** and fsync(), Ted tells us, is that fdatasync() will not flush the
3437** inode if the mtime or owner or other inode attributes have changed.
3438** We only care about the file size, not the other file attributes, so
3439** as far as SQLite is concerned, an fdatasync() is always adequate.
3440** So, we always use fdatasync() if it is available, regardless of
3441** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003442*/
3443static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003444 int rc;
drh734c9862008-11-28 15:37:20 +00003445
3446 /* The following "ifdef/elif/else/" block has the same structure as
3447 ** the one below. It is replicated here solely to avoid cluttering
3448 ** up the real code with the UNUSED_PARAMETER() macros.
3449 */
3450#ifdef SQLITE_NO_SYNC
3451 UNUSED_PARAMETER(fd);
3452 UNUSED_PARAMETER(fullSync);
3453 UNUSED_PARAMETER(dataOnly);
3454#elif HAVE_FULLFSYNC
3455 UNUSED_PARAMETER(dataOnly);
3456#else
3457 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003458 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003459#endif
3460
3461 /* Record the number of times that we do a normal fsync() and
3462 ** FULLSYNC. This is used during testing to verify that this procedure
3463 ** gets called with the correct arguments.
3464 */
3465#ifdef SQLITE_TEST
3466 if( fullSync ) sqlite3_fullsync_count++;
3467 sqlite3_sync_count++;
3468#endif
3469
3470 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3471 ** no-op
3472 */
3473#ifdef SQLITE_NO_SYNC
3474 rc = SQLITE_OK;
3475#elif HAVE_FULLFSYNC
3476 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003477 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003478 }else{
3479 rc = 1;
3480 }
3481 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003482 ** It shouldn't be possible for fullfsync to fail on the local
3483 ** file system (on OSX), so failure indicates that FULLFSYNC
3484 ** isn't supported for this file system. So, attempt an fsync
3485 ** and (for now) ignore the overhead of a superfluous fcntl call.
3486 ** It'd be better to detect fullfsync support once and avoid
3487 ** the fcntl call every time sync is called.
3488 */
drh734c9862008-11-28 15:37:20 +00003489 if( rc ) rc = fsync(fd);
3490
drh7ed97b92010-01-20 13:07:21 +00003491#elif defined(__APPLE__)
3492 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3493 ** so currently we default to the macro that redefines fdatasync to fsync
3494 */
3495 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003496#else
drh0b647ff2009-03-21 14:41:04 +00003497 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003498#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003499 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003500 rc = fsync(fd);
3501 }
drh0b647ff2009-03-21 14:41:04 +00003502#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003503#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3504
3505 if( OS_VXWORKS && rc!= -1 ){
3506 rc = 0;
3507 }
chw97185482008-11-17 08:05:31 +00003508 return rc;
drhbfe66312006-10-03 17:40:40 +00003509}
3510
drh734c9862008-11-28 15:37:20 +00003511/*
drh0059eae2011-08-08 23:48:40 +00003512** Open a file descriptor to the directory containing file zFilename.
3513** If successful, *pFd is set to the opened file descriptor and
3514** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3515** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3516** value.
3517**
drh90315a22011-08-10 01:52:12 +00003518** The directory file descriptor is used for only one thing - to
3519** fsync() a directory to make sure file creation and deletion events
3520** are flushed to disk. Such fsyncs are not needed on newer
3521** journaling filesystems, but are required on older filesystems.
3522**
3523** This routine can be overridden using the xSetSysCall interface.
3524** The ability to override this routine was added in support of the
3525** chromium sandbox. Opening a directory is a security risk (we are
3526** told) so making it overrideable allows the chromium sandbox to
3527** replace this routine with a harmless no-op. To make this routine
3528** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3529** *pFd set to a negative number.
3530**
drh0059eae2011-08-08 23:48:40 +00003531** If SQLITE_OK is returned, the caller is responsible for closing
3532** the file descriptor *pFd using close().
3533*/
3534static int openDirectory(const char *zFilename, int *pFd){
3535 int ii;
3536 int fd = -1;
3537 char zDirname[MAX_PATHNAME+1];
3538
3539 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3540 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3541 if( ii>0 ){
3542 zDirname[ii] = '\0';
3543 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3544 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003545 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3546 }
3547 }
3548 *pFd = fd;
3549 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3550}
3551
3552/*
drh734c9862008-11-28 15:37:20 +00003553** Make sure all writes to a particular file are committed to disk.
3554**
3555** If dataOnly==0 then both the file itself and its metadata (file
3556** size, access time, etc) are synced. If dataOnly!=0 then only the
3557** file data is synced.
3558**
3559** Under Unix, also make sure that the directory entry for the file
3560** has been created by fsync-ing the directory that contains the file.
3561** If we do not do this and we encounter a power failure, the directory
3562** entry for the journal might not exist after we reboot. The next
3563** SQLite to access the file will not know that the journal exists (because
3564** the directory entry for the journal was never created) and the transaction
3565** will not roll back - possibly leading to database corruption.
3566*/
3567static int unixSync(sqlite3_file *id, int flags){
3568 int rc;
3569 unixFile *pFile = (unixFile*)id;
3570
3571 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3572 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3573
3574 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3575 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3576 || (flags&0x0F)==SQLITE_SYNC_FULL
3577 );
3578
3579 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3580 ** line is to test that doing so does not cause any problems.
3581 */
3582 SimulateDiskfullError( return SQLITE_FULL );
3583
3584 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003585 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003586 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3587 SimulateIOError( rc=1 );
3588 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003589 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003590 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003591 }
drh0059eae2011-08-08 23:48:40 +00003592
3593 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003594 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003595 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003596 */
3597 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3598 int dirfd;
3599 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003600 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003601 rc = osOpenDirectory(pFile->zPath, &dirfd);
3602 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003603 full_fsync(dirfd, 0, 0);
3604 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003605 }else if( rc==SQLITE_CANTOPEN ){
3606 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003607 }
drh0059eae2011-08-08 23:48:40 +00003608 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003609 }
3610 return rc;
3611}
3612
3613/*
3614** Truncate an open file to a specified size
3615*/
3616static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003617 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003618 int rc;
dan6e09d692010-07-27 18:34:15 +00003619 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003620 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003621
3622 /* If the user has configured a chunk-size for this file, truncate the
3623 ** file so that it consists of an integer number of chunks (i.e. the
3624 ** actual file size after the operation may be larger than the requested
3625 ** size).
3626 */
drhb8af4b72012-04-05 20:04:39 +00003627 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003628 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3629 }
3630
dan2ee53412014-09-06 16:49:40 +00003631 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003632 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003633 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003634 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003635 }else{
drhd3d8c042012-05-29 17:02:40 +00003636#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003637 /* If we are doing a normal write to a database file (as opposed to
3638 ** doing a hot-journal rollback or a write to some file other than a
3639 ** normal database file) and we truncate the file to zero length,
3640 ** that effectively updates the change counter. This might happen
3641 ** when restoring a database using the backup API from a zero-length
3642 ** source.
3643 */
dan6e09d692010-07-27 18:34:15 +00003644 if( pFile->inNormalWrite && nByte==0 ){
3645 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003646 }
danf23da962013-03-23 21:00:41 +00003647#endif
danc0003312013-03-22 17:46:11 +00003648
mistachkine98844f2013-08-24 00:59:24 +00003649#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003650 /* If the file was just truncated to a size smaller than the currently
3651 ** mapped region, reduce the effective mapping size as well. SQLite will
3652 ** use read() and write() to access data beyond this point from now on.
3653 */
3654 if( nByte<pFile->mmapSize ){
3655 pFile->mmapSize = nByte;
3656 }
mistachkine98844f2013-08-24 00:59:24 +00003657#endif
drh3313b142009-11-06 04:13:18 +00003658
drh734c9862008-11-28 15:37:20 +00003659 return SQLITE_OK;
3660 }
3661}
3662
3663/*
3664** Determine the current size of a file in bytes
3665*/
3666static int unixFileSize(sqlite3_file *id, i64 *pSize){
3667 int rc;
3668 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003669 assert( id );
3670 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003671 SimulateIOError( rc=1 );
3672 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003673 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003674 return SQLITE_IOERR_FSTAT;
3675 }
3676 *pSize = buf.st_size;
3677
drh8af6c222010-05-14 12:43:01 +00003678 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003679 ** writes a single byte into that file in order to work around a bug
3680 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3681 ** layers, we need to report this file size as zero even though it is
3682 ** really 1. Ticket #3260.
3683 */
3684 if( *pSize==1 ) *pSize = 0;
3685
3686
3687 return SQLITE_OK;
3688}
3689
drhd2cb50b2009-01-09 21:41:17 +00003690#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003691/*
3692** Handler for proxy-locking file-control verbs. Defined below in the
3693** proxying locking division.
3694*/
3695static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003696#endif
drh715ff302008-12-03 22:32:44 +00003697
dan502019c2010-07-28 14:26:17 +00003698/*
3699** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003700** file-control operation. Enlarge the database to nBytes in size
3701** (rounded up to the next chunk-size). If the database is already
3702** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003703*/
3704static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003705 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003706 i64 nSize; /* Required file size */
3707 struct stat buf; /* Used to hold return values of fstat() */
3708
drh4bf66fd2015-02-19 02:43:02 +00003709 if( osFstat(pFile->h, &buf) ){
3710 return SQLITE_IOERR_FSTAT;
3711 }
dan502019c2010-07-28 14:26:17 +00003712
3713 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3714 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003715
dan502019c2010-07-28 14:26:17 +00003716#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003717 /* The code below is handling the return value of osFallocate()
3718 ** correctly. posix_fallocate() is defined to "returns zero on success,
3719 ** or an error number on failure". See the manpage for details. */
3720 int err;
drhff812312011-02-23 13:33:46 +00003721 do{
dan661d71a2011-03-30 19:08:03 +00003722 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3723 }while( err==EINTR );
3724 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003725#else
dan592bf7f2014-12-30 19:58:31 +00003726 /* If the OS does not have posix_fallocate(), fake it. Write a
3727 ** single byte to the last byte in each block that falls entirely
3728 ** within the extended region. Then, if required, a single byte
3729 ** at offset (nSize-1), to set the size of the file correctly.
3730 ** This is a similar technique to that used by glibc on systems
3731 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003732 */
3733 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003734 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003735 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003736
dan502019c2010-07-28 14:26:17 +00003737 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003738 assert( iWrite>=buf.st_size );
3739 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3740 assert( ((iWrite+1)%nBlk)==0 );
3741 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003742 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003743 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003744 }
danef3d66c2015-01-06 21:31:47 +00003745 if( nWrite==0 || (nSize%nBlk) ){
3746 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003747 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003748 }
dan502019c2010-07-28 14:26:17 +00003749#endif
3750 }
3751 }
3752
mistachkine98844f2013-08-24 00:59:24 +00003753#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003754 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003755 int rc;
3756 if( pFile->szChunk<=0 ){
3757 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003758 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003759 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3760 }
3761 }
3762
3763 rc = unixMapfile(pFile, nByte);
3764 return rc;
3765 }
mistachkine98844f2013-08-24 00:59:24 +00003766#endif
danf23da962013-03-23 21:00:41 +00003767
dan502019c2010-07-28 14:26:17 +00003768 return SQLITE_OK;
3769}
danielk1977ad94b582007-08-20 06:44:22 +00003770
danielk1977e3026632004-06-22 11:29:02 +00003771/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003772** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003773** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3774**
3775** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3776*/
3777static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3778 if( *pArg<0 ){
3779 *pArg = (pFile->ctrlFlags & mask)!=0;
3780 }else if( (*pArg)==0 ){
3781 pFile->ctrlFlags &= ~mask;
3782 }else{
3783 pFile->ctrlFlags |= mask;
3784 }
3785}
3786
drh696b33e2012-12-06 19:01:42 +00003787/* Forward declaration */
3788static int unixGetTempname(int nBuf, char *zBuf);
3789
drhf12b3f62011-12-21 14:42:29 +00003790/*
drh9e33c2c2007-08-31 18:34:59 +00003791** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003792*/
drhcc6bb3e2007-08-31 16:11:35 +00003793static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003794 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003795 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003796 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003797 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003798 return SQLITE_OK;
3799 }
drh9e33c2c2007-08-31 18:34:59 +00003800 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003801 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003802 return SQLITE_OK;
3803 }
drh4bf66fd2015-02-19 02:43:02 +00003804 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003805 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003806 return SQLITE_OK;
3807 }
dan6e09d692010-07-27 18:34:15 +00003808 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003809 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003810 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003811 }
drh9ff27ec2010-05-19 19:26:05 +00003812 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003813 int rc;
3814 SimulateIOErrorBenign(1);
3815 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3816 SimulateIOErrorBenign(0);
3817 return rc;
drhf0b190d2011-07-26 16:03:07 +00003818 }
3819 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003820 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3821 return SQLITE_OK;
3822 }
drhcb15f352011-12-23 01:04:17 +00003823 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3824 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003825 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003826 }
drhde60fc22011-12-14 17:53:36 +00003827 case SQLITE_FCNTL_VFSNAME: {
3828 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3829 return SQLITE_OK;
3830 }
drh696b33e2012-12-06 19:01:42 +00003831 case SQLITE_FCNTL_TEMPFILENAME: {
3832 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
3833 if( zTFile ){
3834 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3835 *(char**)pArg = zTFile;
3836 }
3837 return SQLITE_OK;
3838 }
drhb959a012013-12-07 12:29:22 +00003839 case SQLITE_FCNTL_HAS_MOVED: {
3840 *(int*)pArg = fileHasMoved(pFile);
3841 return SQLITE_OK;
3842 }
mistachkine98844f2013-08-24 00:59:24 +00003843#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003844 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003845 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003846 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003847 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3848 newLimit = sqlite3GlobalConfig.mxMmap;
3849 }
3850 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003851 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003852 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003853 if( pFile->mmapSize>0 ){
3854 unixUnmapfile(pFile);
3855 rc = unixMapfile(pFile, -1);
3856 }
danbcb8a862013-04-08 15:30:41 +00003857 }
drh34e258c2013-05-23 01:40:53 +00003858 return rc;
danb2d3de32013-03-14 18:34:37 +00003859 }
mistachkine98844f2013-08-24 00:59:24 +00003860#endif
drhd3d8c042012-05-29 17:02:40 +00003861#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003862 /* The pager calls this method to signal that it has done
3863 ** a rollback and that the database is therefore unchanged and
3864 ** it hence it is OK for the transaction change counter to be
3865 ** unchanged.
3866 */
3867 case SQLITE_FCNTL_DB_UNCHANGED: {
3868 ((unixFile*)id)->dbUpdate = 0;
3869 return SQLITE_OK;
3870 }
3871#endif
drhd2cb50b2009-01-09 21:41:17 +00003872#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003873 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3874 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003875 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003876 }
drhd2cb50b2009-01-09 21:41:17 +00003877#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003878 }
drh0b52b7d2011-01-26 19:46:22 +00003879 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003880}
3881
3882/*
danielk1977a3d4c882007-03-23 10:08:38 +00003883** Return the sector size in bytes of the underlying block device for
3884** the specified file. This is almost always 512 bytes, but may be
3885** larger for some devices.
3886**
3887** SQLite code assumes this function cannot fail. It also assumes that
3888** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003889** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003890** same for both.
3891*/
drh537dddf2012-10-26 13:46:24 +00003892#ifndef __QNXNTO__
3893static int unixSectorSize(sqlite3_file *NotUsed){
3894 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003895 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003896}
drh537dddf2012-10-26 13:46:24 +00003897#endif
3898
3899/*
3900** The following version of unixSectorSize() is optimized for QNX.
3901*/
3902#ifdef __QNXNTO__
3903#include <sys/dcmd_blk.h>
3904#include <sys/statvfs.h>
3905static int unixSectorSize(sqlite3_file *id){
3906 unixFile *pFile = (unixFile*)id;
3907 if( pFile->sectorSize == 0 ){
3908 struct statvfs fsInfo;
3909
3910 /* Set defaults for non-supported filesystems */
3911 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3912 pFile->deviceCharacteristics = 0;
3913 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3914 return pFile->sectorSize;
3915 }
3916
3917 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3918 pFile->sectorSize = fsInfo.f_bsize;
3919 pFile->deviceCharacteristics =
3920 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3921 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3922 ** the write succeeds */
3923 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3924 ** so it is ordered */
3925 0;
3926 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3927 pFile->sectorSize = fsInfo.f_bsize;
3928 pFile->deviceCharacteristics =
3929 /* etfs cluster size writes are atomic */
3930 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3931 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3932 ** the write succeeds */
3933 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3934 ** so it is ordered */
3935 0;
3936 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3937 pFile->sectorSize = fsInfo.f_bsize;
3938 pFile->deviceCharacteristics =
3939 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3940 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3941 ** the write succeeds */
3942 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3943 ** so it is ordered */
3944 0;
3945 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3946 pFile->sectorSize = fsInfo.f_bsize;
3947 pFile->deviceCharacteristics =
3948 /* full bitset of atomics from max sector size and smaller */
3949 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3950 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3951 ** so it is ordered */
3952 0;
3953 }else if( strstr(fsInfo.f_basetype, "dos") ){
3954 pFile->sectorSize = fsInfo.f_bsize;
3955 pFile->deviceCharacteristics =
3956 /* full bitset of atomics from max sector size and smaller */
3957 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3958 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3959 ** so it is ordered */
3960 0;
3961 }else{
3962 pFile->deviceCharacteristics =
3963 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3964 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3965 ** the write succeeds */
3966 0;
3967 }
3968 }
3969 /* Last chance verification. If the sector size isn't a multiple of 512
3970 ** then it isn't valid.*/
3971 if( pFile->sectorSize % 512 != 0 ){
3972 pFile->deviceCharacteristics = 0;
3973 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3974 }
3975 return pFile->sectorSize;
3976}
3977#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003978
danielk197790949c22007-08-17 16:50:38 +00003979/*
drhf12b3f62011-12-21 14:42:29 +00003980** Return the device characteristics for the file.
3981**
drhcb15f352011-12-23 01:04:17 +00003982** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003983** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003984** file system does not always provide powersafe overwrites. (In other
3985** words, after a power-loss event, parts of the file that were never
3986** written might end up being altered.) However, non-PSOW behavior is very,
3987** very rare. And asserting PSOW makes a large reduction in the amount
3988** of required I/O for journaling, since a lot of padding is eliminated.
3989** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3990** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003991*/
drhf12b3f62011-12-21 14:42:29 +00003992static int unixDeviceCharacteristics(sqlite3_file *id){
3993 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003994 int rc = 0;
3995#ifdef __QNXNTO__
3996 if( p->sectorSize==0 ) unixSectorSize(id);
3997 rc = p->deviceCharacteristics;
3998#endif
drhcb15f352011-12-23 01:04:17 +00003999 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00004000 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00004001 }
drh537dddf2012-10-26 13:46:24 +00004002 return rc;
danielk197762079062007-08-15 17:08:46 +00004003}
4004
dan702eec12014-06-23 10:04:58 +00004005#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004006
dan702eec12014-06-23 10:04:58 +00004007/*
4008** Return the system page size.
4009**
4010** This function should not be called directly by other code in this file.
4011** Instead, it should be called via macro osGetpagesize().
4012*/
4013static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004014#if OS_VXWORKS
4015 return 1024;
4016#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004017 return getpagesize();
4018#else
4019 return (int)sysconf(_SC_PAGESIZE);
4020#endif
4021}
4022
4023#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4024
4025#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004026
4027/*
drhd91c68f2010-05-14 14:52:25 +00004028** Object used to represent an shared memory buffer.
4029**
4030** When multiple threads all reference the same wal-index, each thread
4031** has its own unixShm object, but they all point to a single instance
4032** of this unixShmNode object. In other words, each wal-index is opened
4033** only once per process.
4034**
4035** Each unixShmNode object is connected to a single unixInodeInfo object.
4036** We could coalesce this object into unixInodeInfo, but that would mean
4037** every open file that does not use shared memory (in other words, most
4038** open files) would have to carry around this extra information. So
4039** the unixInodeInfo object contains a pointer to this unixShmNode object
4040** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004041**
4042** unixMutexHeld() must be true when creating or destroying
4043** this object or while reading or writing the following fields:
4044**
4045** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004046**
4047** The following fields are read-only after the object is created:
4048**
4049** fid
4050** zFilename
4051**
drhd91c68f2010-05-14 14:52:25 +00004052** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004053** unixMutexHeld() is true when reading or writing any other field
4054** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004055*/
drhd91c68f2010-05-14 14:52:25 +00004056struct unixShmNode {
4057 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004058 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004059 char *zFilename; /* Name of the mmapped file */
4060 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004061 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004062 u16 nRegion; /* Size of array apRegion */
4063 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004064 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004065 int nRef; /* Number of unixShm objects pointing to this */
4066 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004067#ifdef SQLITE_DEBUG
4068 u8 exclMask; /* Mask of exclusive locks held */
4069 u8 sharedMask; /* Mask of shared locks held */
4070 u8 nextShmId; /* Next available unixShm.id value */
4071#endif
4072};
4073
4074/*
drhd9e5c4f2010-05-12 18:01:39 +00004075** Structure used internally by this VFS to record the state of an
4076** open shared memory connection.
4077**
drhd91c68f2010-05-14 14:52:25 +00004078** The following fields are initialized when this object is created and
4079** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004080**
drhd91c68f2010-05-14 14:52:25 +00004081** unixShm.pFile
4082** unixShm.id
4083**
4084** All other fields are read/write. The unixShm.pFile->mutex must be held
4085** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004086*/
4087struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004088 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4089 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004090 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004091 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004092 u16 sharedMask; /* Mask of shared locks held */
4093 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004094};
4095
4096/*
drhd9e5c4f2010-05-12 18:01:39 +00004097** Constants used for locking
4098*/
drhbd9676c2010-06-23 17:58:38 +00004099#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004100#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004101
drhd9e5c4f2010-05-12 18:01:39 +00004102/*
drh73b64e42010-05-30 19:55:15 +00004103** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004104**
4105** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4106** otherwise.
4107*/
4108static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004109 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004110 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004111 int ofst, /* First byte of the locking range */
4112 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004113){
drhbbf76ee2015-03-10 20:22:35 +00004114 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4115 struct flock f; /* The posix advisory locking structure */
4116 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004117
drhd91c68f2010-05-14 14:52:25 +00004118 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004119 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004120 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004121
drh73b64e42010-05-30 19:55:15 +00004122 /* Shared locks never span more than one byte */
4123 assert( n==1 || lockType!=F_RDLCK );
4124
4125 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004126 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004127
drh3cb93392011-03-12 18:10:44 +00004128 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004129 int lkType;
drh3cb93392011-03-12 18:10:44 +00004130 /* Initialize the locking parameters */
4131 memset(&f, 0, sizeof(f));
4132 f.l_type = lockType;
4133 f.l_whence = SEEK_SET;
4134 f.l_start = ofst;
4135 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004136
drhbbf76ee2015-03-10 20:22:35 +00004137 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4138 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004139 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004140 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004141 }
drhd9e5c4f2010-05-12 18:01:39 +00004142
4143 /* Update the global lock state and do debug tracing */
4144#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004145 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004146 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004147 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004148 if( rc==SQLITE_OK ){
4149 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004150 OSTRACE(("unlock %d ok", ofst));
4151 pShmNode->exclMask &= ~mask;
4152 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004153 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004154 OSTRACE(("read-lock %d ok", ofst));
4155 pShmNode->exclMask &= ~mask;
4156 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004157 }else{
4158 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004159 OSTRACE(("write-lock %d ok", ofst));
4160 pShmNode->exclMask |= mask;
4161 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004162 }
4163 }else{
4164 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004165 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004166 }else if( lockType==F_RDLCK ){
4167 OSTRACE(("read-lock failed"));
4168 }else{
4169 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004170 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004171 }
4172 }
drh20e1f082010-05-31 16:10:12 +00004173 OSTRACE((" - afterwards %03x,%03x\n",
4174 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004175 }
drhd9e5c4f2010-05-12 18:01:39 +00004176#endif
4177
4178 return rc;
4179}
4180
dan781e34c2014-03-20 08:59:47 +00004181/*
dan781e34c2014-03-20 08:59:47 +00004182** Return the minimum number of 32KB shm regions that should be mapped at
4183** a time, assuming that each mapping must be an integer multiple of the
4184** current system page-size.
4185**
4186** Usually, this is 1. The exception seems to be systems that are configured
4187** to use 64KB pages - in this case each mapping must cover at least two
4188** shm regions.
4189*/
4190static int unixShmRegionPerMap(void){
4191 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004192 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004193 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4194 if( pgsz<shmsz ) return 1;
4195 return pgsz/shmsz;
4196}
drhd9e5c4f2010-05-12 18:01:39 +00004197
4198/*
drhd91c68f2010-05-14 14:52:25 +00004199** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004200**
4201** This is not a VFS shared-memory method; it is a utility function called
4202** by VFS shared-memory methods.
4203*/
drhd91c68f2010-05-14 14:52:25 +00004204static void unixShmPurge(unixFile *pFd){
4205 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004206 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004207 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004208 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004209 int i;
drhd91c68f2010-05-14 14:52:25 +00004210 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004211 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004212 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004213 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004214 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004215 }else{
4216 sqlite3_free(p->apRegion[i]);
4217 }
dan13a3cb82010-06-11 19:04:21 +00004218 }
dan18801912010-06-14 14:07:50 +00004219 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004220 if( p->h>=0 ){
4221 robust_close(pFd, p->h, __LINE__);
4222 p->h = -1;
4223 }
drhd91c68f2010-05-14 14:52:25 +00004224 p->pInode->pShmNode = 0;
4225 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004226 }
4227}
4228
4229/*
danda9fe0c2010-07-13 18:44:03 +00004230** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004231** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004232**
drh7234c6d2010-06-19 15:10:09 +00004233** The file used to implement shared-memory is in the same directory
4234** as the open database file and has the same name as the open database
4235** file with the "-shm" suffix added. For example, if the database file
4236** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004237** for shared memory will be called "/home/user1/config.db-shm".
4238**
4239** Another approach to is to use files in /dev/shm or /dev/tmp or an
4240** some other tmpfs mount. But if a file in a different directory
4241** from the database file is used, then differing access permissions
4242** or a chroot() might cause two different processes on the same
4243** database to end up using different files for shared memory -
4244** meaning that their memory would not really be shared - resulting
4245** in database corruption. Nevertheless, this tmpfs file usage
4246** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4247** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4248** option results in an incompatible build of SQLite; builds of SQLite
4249** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4250** same database file at the same time, database corruption will likely
4251** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4252** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004253**
4254** When opening a new shared-memory file, if no other instances of that
4255** file are currently open, in this process or in other processes, then
4256** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004257**
4258** If the original database file (pDbFd) is using the "unix-excl" VFS
4259** that means that an exclusive lock is held on the database file and
4260** that no other processes are able to read or write the database. In
4261** that case, we do not really need shared memory. No shared memory
4262** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004263*/
danda9fe0c2010-07-13 18:44:03 +00004264static int unixOpenSharedMemory(unixFile *pDbFd){
4265 struct unixShm *p = 0; /* The connection to be opened */
4266 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4267 int rc; /* Result code */
4268 unixInodeInfo *pInode; /* The inode of fd */
4269 char *zShmFilename; /* Name of the file used for SHM */
4270 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004271
danda9fe0c2010-07-13 18:44:03 +00004272 /* Allocate space for the new unixShm object. */
drhd9e5c4f2010-05-12 18:01:39 +00004273 p = sqlite3_malloc( sizeof(*p) );
4274 if( p==0 ) return SQLITE_NOMEM;
4275 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004276 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004277
danda9fe0c2010-07-13 18:44:03 +00004278 /* Check to see if a unixShmNode object already exists. Reuse an existing
4279 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004280 */
4281 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004282 pInode = pDbFd->pInode;
4283 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004284 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004285 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004286#ifndef SQLITE_SHM_DIRECTORY
4287 const char *zBasePath = pDbFd->zPath;
4288#endif
danddb0ac42010-07-14 14:48:58 +00004289
4290 /* Call fstat() to figure out the permissions on the database file. If
4291 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004292 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004293 */
drh3cb93392011-03-12 18:10:44 +00004294 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004295 rc = SQLITE_IOERR_FSTAT;
4296 goto shm_open_err;
4297 }
4298
drha4ced192010-07-15 18:32:40 +00004299#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004300 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004301#else
drh4bf66fd2015-02-19 02:43:02 +00004302 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004303#endif
drh7234c6d2010-06-19 15:10:09 +00004304 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004305 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004306 rc = SQLITE_NOMEM;
4307 goto shm_open_err;
4308 }
drh9cb5a0d2012-01-05 21:19:54 +00004309 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004310 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004311#ifdef SQLITE_SHM_DIRECTORY
4312 sqlite3_snprintf(nShmFilename, zShmFilename,
4313 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4314 (u32)sStat.st_ino, (u32)sStat.st_dev);
4315#else
drh4bf66fd2015-02-19 02:43:02 +00004316 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004317 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004318#endif
drhd91c68f2010-05-14 14:52:25 +00004319 pShmNode->h = -1;
4320 pDbFd->pInode->pShmNode = pShmNode;
4321 pShmNode->pInode = pDbFd->pInode;
4322 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4323 if( pShmNode->mutex==0 ){
4324 rc = SQLITE_NOMEM;
4325 goto shm_open_err;
4326 }
drhd9e5c4f2010-05-12 18:01:39 +00004327
drh3cb93392011-03-12 18:10:44 +00004328 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004329 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004330 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004331 openFlags = O_RDONLY;
4332 pShmNode->isReadonly = 1;
4333 }
4334 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004335 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004336 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4337 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004338 }
drhac7c3ac2012-02-11 19:23:48 +00004339
4340 /* If this process is running as root, make sure that the SHM file
4341 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004342 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004343 */
drhed466822012-05-31 13:10:49 +00004344 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004345
4346 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004347 ** If not, truncate the file to zero length.
4348 */
4349 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004350 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004351 if( robust_ftruncate(pShmNode->h, 0) ){
4352 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004353 }
4354 }
drh66dfec8b2011-06-01 20:01:49 +00004355 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004356 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004357 }
4358 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004359 }
drhd9e5c4f2010-05-12 18:01:39 +00004360 }
4361
drhd91c68f2010-05-14 14:52:25 +00004362 /* Make the new connection a child of the unixShmNode */
4363 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004364#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004365 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004366#endif
drhd91c68f2010-05-14 14:52:25 +00004367 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004368 pDbFd->pShm = p;
4369 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004370
4371 /* The reference count on pShmNode has already been incremented under
4372 ** the cover of the unixEnterMutex() mutex and the pointer from the
4373 ** new (struct unixShm) object to the pShmNode has been set. All that is
4374 ** left to do is to link the new object into the linked list starting
4375 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4376 ** mutex.
4377 */
4378 sqlite3_mutex_enter(pShmNode->mutex);
4379 p->pNext = pShmNode->pFirst;
4380 pShmNode->pFirst = p;
4381 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004382 return SQLITE_OK;
4383
4384 /* Jump here on any error */
4385shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004386 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004387 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004388 unixLeaveMutex();
4389 return rc;
4390}
4391
4392/*
danda9fe0c2010-07-13 18:44:03 +00004393** This function is called to obtain a pointer to region iRegion of the
4394** shared-memory associated with the database file fd. Shared-memory regions
4395** are numbered starting from zero. Each shared-memory region is szRegion
4396** bytes in size.
4397**
4398** If an error occurs, an error code is returned and *pp is set to NULL.
4399**
4400** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4401** region has not been allocated (by any client, including one running in a
4402** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4403** bExtend is non-zero and the requested shared-memory region has not yet
4404** been allocated, it is allocated by this function.
4405**
4406** If the shared-memory region has already been allocated or is allocated by
4407** this call as described above, then it is mapped into this processes
4408** address space (if it is not already), *pp is set to point to the mapped
4409** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004410*/
danda9fe0c2010-07-13 18:44:03 +00004411static int unixShmMap(
4412 sqlite3_file *fd, /* Handle open on database file */
4413 int iRegion, /* Region to retrieve */
4414 int szRegion, /* Size of regions */
4415 int bExtend, /* True to extend file if necessary */
4416 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004417){
danda9fe0c2010-07-13 18:44:03 +00004418 unixFile *pDbFd = (unixFile*)fd;
4419 unixShm *p;
4420 unixShmNode *pShmNode;
4421 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004422 int nShmPerMap = unixShmRegionPerMap();
4423 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004424
danda9fe0c2010-07-13 18:44:03 +00004425 /* If the shared-memory file has not yet been opened, open it now. */
4426 if( pDbFd->pShm==0 ){
4427 rc = unixOpenSharedMemory(pDbFd);
4428 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004429 }
drhd9e5c4f2010-05-12 18:01:39 +00004430
danda9fe0c2010-07-13 18:44:03 +00004431 p = pDbFd->pShm;
4432 pShmNode = p->pShmNode;
4433 sqlite3_mutex_enter(pShmNode->mutex);
4434 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004435 assert( pShmNode->pInode==pDbFd->pInode );
4436 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4437 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004438
dan781e34c2014-03-20 08:59:47 +00004439 /* Minimum number of regions required to be mapped. */
4440 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4441
4442 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004443 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004444 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004445 struct stat sStat; /* Used by fstat() */
4446
4447 pShmNode->szRegion = szRegion;
4448
drh3cb93392011-03-12 18:10:44 +00004449 if( pShmNode->h>=0 ){
4450 /* The requested region is not mapped into this processes address space.
4451 ** Check to see if it has been allocated (i.e. if the wal-index file is
4452 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004453 */
drh3cb93392011-03-12 18:10:44 +00004454 if( osFstat(pShmNode->h, &sStat) ){
4455 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004456 goto shmpage_out;
4457 }
drh3cb93392011-03-12 18:10:44 +00004458
4459 if( sStat.st_size<nByte ){
4460 /* The requested memory region does not exist. If bExtend is set to
4461 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004462 */
dan47a2b4a2013-04-26 16:09:29 +00004463 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004464 goto shmpage_out;
4465 }
dan47a2b4a2013-04-26 16:09:29 +00004466
4467 /* Alternatively, if bExtend is true, extend the file. Do this by
4468 ** writing a single byte to the end of each (OS) page being
4469 ** allocated or extended. Technically, we need only write to the
4470 ** last page in order to extend the file. But writing to all new
4471 ** pages forces the OS to allocate them immediately, which reduces
4472 ** the chances of SIGBUS while accessing the mapped region later on.
4473 */
4474 else{
4475 static const int pgsz = 4096;
4476 int iPg;
4477
4478 /* Write to the last byte of each newly allocated or extended page */
4479 assert( (nByte % pgsz)==0 );
4480 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4481 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4482 const char *zFile = pShmNode->zFilename;
4483 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4484 goto shmpage_out;
4485 }
4486 }
drh3cb93392011-03-12 18:10:44 +00004487 }
4488 }
danda9fe0c2010-07-13 18:44:03 +00004489 }
4490
4491 /* Map the requested memory region into this processes address space. */
4492 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004493 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004494 );
4495 if( !apNew ){
4496 rc = SQLITE_IOERR_NOMEM;
4497 goto shmpage_out;
4498 }
4499 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004500 while( pShmNode->nRegion<nReqRegion ){
4501 int nMap = szRegion*nShmPerMap;
4502 int i;
drh3cb93392011-03-12 18:10:44 +00004503 void *pMem;
4504 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004505 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004506 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004507 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004508 );
4509 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004510 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004511 goto shmpage_out;
4512 }
4513 }else{
4514 pMem = sqlite3_malloc(szRegion);
4515 if( pMem==0 ){
4516 rc = SQLITE_NOMEM;
4517 goto shmpage_out;
4518 }
4519 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004520 }
dan781e34c2014-03-20 08:59:47 +00004521
4522 for(i=0; i<nShmPerMap; i++){
4523 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4524 }
4525 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004526 }
4527 }
4528
4529shmpage_out:
4530 if( pShmNode->nRegion>iRegion ){
4531 *pp = pShmNode->apRegion[iRegion];
4532 }else{
4533 *pp = 0;
4534 }
drh66dfec8b2011-06-01 20:01:49 +00004535 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004536 sqlite3_mutex_leave(pShmNode->mutex);
4537 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004538}
4539
4540/*
drhd9e5c4f2010-05-12 18:01:39 +00004541** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004542**
4543** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4544** different here than in posix. In xShmLock(), one can go from unlocked
4545** to shared and back or from unlocked to exclusive and back. But one may
4546** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004547*/
4548static int unixShmLock(
4549 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004550 int ofst, /* First lock to acquire or release */
4551 int n, /* Number of locks to acquire or release */
4552 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004553){
drh73b64e42010-05-30 19:55:15 +00004554 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4555 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4556 unixShm *pX; /* For looping over all siblings */
4557 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4558 int rc = SQLITE_OK; /* Result code */
4559 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004560
drhd91c68f2010-05-14 14:52:25 +00004561 assert( pShmNode==pDbFd->pInode->pShmNode );
4562 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004563 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004564 assert( n>=1 );
4565 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4566 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4567 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4568 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4569 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004570 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4571 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004572
drhc99597c2010-05-31 01:41:15 +00004573 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004574 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004575 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004576 if( flags & SQLITE_SHM_UNLOCK ){
4577 u16 allMask = 0; /* Mask of locks held by siblings */
4578
4579 /* See if any siblings hold this same lock */
4580 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4581 if( pX==p ) continue;
4582 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4583 allMask |= pX->sharedMask;
4584 }
4585
4586 /* Unlock the system-level locks */
4587 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004588 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004589 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004590 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004591 }
drh73b64e42010-05-30 19:55:15 +00004592
4593 /* Undo the local locks */
4594 if( rc==SQLITE_OK ){
4595 p->exclMask &= ~mask;
4596 p->sharedMask &= ~mask;
4597 }
4598 }else if( flags & SQLITE_SHM_SHARED ){
4599 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4600
4601 /* Find out which shared locks are already held by sibling connections.
4602 ** If any sibling already holds an exclusive lock, go ahead and return
4603 ** SQLITE_BUSY.
4604 */
4605 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004606 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004607 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004608 break;
4609 }
4610 allShared |= pX->sharedMask;
4611 }
4612
4613 /* Get shared locks at the system level, if necessary */
4614 if( rc==SQLITE_OK ){
4615 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004616 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004617 }else{
drh73b64e42010-05-30 19:55:15 +00004618 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004619 }
drhd9e5c4f2010-05-12 18:01:39 +00004620 }
drh73b64e42010-05-30 19:55:15 +00004621
4622 /* Get the local shared locks */
4623 if( rc==SQLITE_OK ){
4624 p->sharedMask |= mask;
4625 }
4626 }else{
4627 /* Make sure no sibling connections hold locks that will block this
4628 ** lock. If any do, return SQLITE_BUSY right away.
4629 */
4630 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004631 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4632 rc = SQLITE_BUSY;
4633 break;
4634 }
4635 }
4636
4637 /* Get the exclusive locks at the system level. Then if successful
4638 ** also mark the local connection as being locked.
4639 */
4640 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004641 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004642 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004643 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004644 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004645 }
drhd9e5c4f2010-05-12 18:01:39 +00004646 }
4647 }
drhd91c68f2010-05-14 14:52:25 +00004648 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004649 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004650 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004651 return rc;
4652}
4653
drh286a2882010-05-20 23:51:06 +00004654/*
4655** Implement a memory barrier or memory fence on shared memory.
4656**
4657** All loads and stores begun before the barrier must complete before
4658** any load or store begun after the barrier.
4659*/
4660static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004661 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004662){
drhff828942010-06-26 21:34:06 +00004663 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004664 unixEnterMutex();
4665 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004666}
4667
dan18801912010-06-14 14:07:50 +00004668/*
danda9fe0c2010-07-13 18:44:03 +00004669** Close a connection to shared-memory. Delete the underlying
4670** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004671**
4672** If there is no shared memory associated with the connection then this
4673** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004674*/
danda9fe0c2010-07-13 18:44:03 +00004675static int unixShmUnmap(
4676 sqlite3_file *fd, /* The underlying database file */
4677 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004678){
danda9fe0c2010-07-13 18:44:03 +00004679 unixShm *p; /* The connection to be closed */
4680 unixShmNode *pShmNode; /* The underlying shared-memory file */
4681 unixShm **pp; /* For looping over sibling connections */
4682 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004683
danda9fe0c2010-07-13 18:44:03 +00004684 pDbFd = (unixFile*)fd;
4685 p = pDbFd->pShm;
4686 if( p==0 ) return SQLITE_OK;
4687 pShmNode = p->pShmNode;
4688
4689 assert( pShmNode==pDbFd->pInode->pShmNode );
4690 assert( pShmNode->pInode==pDbFd->pInode );
4691
4692 /* Remove connection p from the set of connections associated
4693 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004694 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004695 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4696 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004697
danda9fe0c2010-07-13 18:44:03 +00004698 /* Free the connection p */
4699 sqlite3_free(p);
4700 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004701 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004702
4703 /* If pShmNode->nRef has reached 0, then close the underlying
4704 ** shared-memory file, too */
4705 unixEnterMutex();
4706 assert( pShmNode->nRef>0 );
4707 pShmNode->nRef--;
4708 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004709 if( deleteFlag && pShmNode->h>=0 ){
4710 osUnlink(pShmNode->zFilename);
4711 }
danda9fe0c2010-07-13 18:44:03 +00004712 unixShmPurge(pDbFd);
4713 }
4714 unixLeaveMutex();
4715
4716 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004717}
drh286a2882010-05-20 23:51:06 +00004718
danda9fe0c2010-07-13 18:44:03 +00004719
drhd9e5c4f2010-05-12 18:01:39 +00004720#else
drh6b017cc2010-06-14 18:01:46 +00004721# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004722# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004723# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004724# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004725#endif /* #ifndef SQLITE_OMIT_WAL */
4726
mistachkine98844f2013-08-24 00:59:24 +00004727#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004728/*
danaef49d72013-03-25 16:28:54 +00004729** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004730*/
danf23da962013-03-23 21:00:41 +00004731static void unixUnmapfile(unixFile *pFd){
4732 assert( pFd->nFetchOut==0 );
4733 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004734 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004735 pFd->pMapRegion = 0;
4736 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004737 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004738 }
4739}
dan5d8a1372013-03-19 19:28:06 +00004740
danaef49d72013-03-25 16:28:54 +00004741/*
dane6ecd662013-04-01 17:56:59 +00004742** Attempt to set the size of the memory mapping maintained by file
4743** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4744**
4745** If successful, this function sets the following variables:
4746**
4747** unixFile.pMapRegion
4748** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004749** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004750**
4751** If unsuccessful, an error message is logged via sqlite3_log() and
4752** the three variables above are zeroed. In this case SQLite should
4753** continue accessing the database using the xRead() and xWrite()
4754** methods.
4755*/
4756static void unixRemapfile(
4757 unixFile *pFd, /* File descriptor object */
4758 i64 nNew /* Required mapping size */
4759){
dan4ff7bc42013-04-02 12:04:09 +00004760 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004761 int h = pFd->h; /* File descriptor open on db file */
4762 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004763 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004764 u8 *pNew = 0; /* Location of new mapping */
4765 int flags = PROT_READ; /* Flags to pass to mmap() */
4766
4767 assert( pFd->nFetchOut==0 );
4768 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004769 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004770 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004771 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004772 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004773
4774 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4775
4776 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004777#if HAVE_MREMAP
4778 i64 nReuse = pFd->mmapSize;
4779#else
danbc760632014-03-20 09:42:09 +00004780 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004781 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004782#endif
dane6ecd662013-04-01 17:56:59 +00004783 u8 *pReq = &pOrig[nReuse];
4784
4785 /* Unmap any pages of the existing mapping that cannot be reused. */
4786 if( nReuse!=nOrig ){
4787 osMunmap(pReq, nOrig-nReuse);
4788 }
4789
4790#if HAVE_MREMAP
4791 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004792 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004793#else
4794 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4795 if( pNew!=MAP_FAILED ){
4796 if( pNew!=pReq ){
4797 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004798 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004799 }else{
4800 pNew = pOrig;
4801 }
4802 }
4803#endif
4804
dan48ccef82013-04-02 20:55:01 +00004805 /* The attempt to extend the existing mapping failed. Free it. */
4806 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004807 osMunmap(pOrig, nReuse);
4808 }
4809 }
4810
4811 /* If pNew is still NULL, try to create an entirely new mapping. */
4812 if( pNew==0 ){
4813 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004814 }
4815
dan4ff7bc42013-04-02 12:04:09 +00004816 if( pNew==MAP_FAILED ){
4817 pNew = 0;
4818 nNew = 0;
4819 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4820
4821 /* If the mmap() above failed, assume that all subsequent mmap() calls
4822 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4823 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004824 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004825 }
dane6ecd662013-04-01 17:56:59 +00004826 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004827 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004828}
4829
4830/*
danaef49d72013-03-25 16:28:54 +00004831** Memory map or remap the file opened by file-descriptor pFd (if the file
4832** is already mapped, the existing mapping is replaced by the new). Or, if
4833** there already exists a mapping for this file, and there are still
4834** outstanding xFetch() references to it, this function is a no-op.
4835**
4836** If parameter nByte is non-negative, then it is the requested size of
4837** the mapping to create. Otherwise, if nByte is less than zero, then the
4838** requested size is the size of the file on disk. The actual size of the
4839** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004840** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004841**
4842** SQLITE_OK is returned if no error occurs (even if the mapping is not
4843** recreated as a result of outstanding references) or an SQLite error
4844** code otherwise.
4845*/
danf23da962013-03-23 21:00:41 +00004846static int unixMapfile(unixFile *pFd, i64 nByte){
4847 i64 nMap = nByte;
4848 int rc;
daneb97b292013-03-20 14:26:59 +00004849
danf23da962013-03-23 21:00:41 +00004850 assert( nMap>=0 || pFd->nFetchOut==0 );
4851 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4852
4853 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004854 struct stat statbuf; /* Low-level file information */
4855 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004856 if( rc!=SQLITE_OK ){
4857 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004858 }
drh3044b512014-06-16 16:41:52 +00004859 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004860 }
drh9b4c59f2013-04-15 17:03:42 +00004861 if( nMap>pFd->mmapSizeMax ){
4862 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004863 }
4864
danf23da962013-03-23 21:00:41 +00004865 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004866 if( nMap>0 ){
4867 unixRemapfile(pFd, nMap);
4868 }else{
danb7e3a322013-03-25 20:30:13 +00004869 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004870 }
4871 }
4872
danf23da962013-03-23 21:00:41 +00004873 return SQLITE_OK;
4874}
mistachkine98844f2013-08-24 00:59:24 +00004875#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004876
danaef49d72013-03-25 16:28:54 +00004877/*
4878** If possible, return a pointer to a mapping of file fd starting at offset
4879** iOff. The mapping must be valid for at least nAmt bytes.
4880**
4881** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4882** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4883** Finally, if an error does occur, return an SQLite error code. The final
4884** value of *pp is undefined in this case.
4885**
4886** If this function does return a pointer, the caller must eventually
4887** release the reference by calling unixUnfetch().
4888*/
danf23da962013-03-23 21:00:41 +00004889static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004890#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004891 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004892#endif
danf23da962013-03-23 21:00:41 +00004893 *pp = 0;
4894
drh9b4c59f2013-04-15 17:03:42 +00004895#if SQLITE_MAX_MMAP_SIZE>0
4896 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004897 if( pFd->pMapRegion==0 ){
4898 int rc = unixMapfile(pFd, -1);
4899 if( rc!=SQLITE_OK ) return rc;
4900 }
4901 if( pFd->mmapSize >= iOff+nAmt ){
4902 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4903 pFd->nFetchOut++;
4904 }
4905 }
drh6e0b6d52013-04-09 16:19:20 +00004906#endif
danf23da962013-03-23 21:00:41 +00004907 return SQLITE_OK;
4908}
4909
danaef49d72013-03-25 16:28:54 +00004910/*
dandf737fe2013-03-25 17:00:24 +00004911** If the third argument is non-NULL, then this function releases a
4912** reference obtained by an earlier call to unixFetch(). The second
4913** argument passed to this function must be the same as the corresponding
4914** argument that was passed to the unixFetch() invocation.
4915**
4916** Or, if the third argument is NULL, then this function is being called
4917** to inform the VFS layer that, according to POSIX, any existing mapping
4918** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004919*/
dandf737fe2013-03-25 17:00:24 +00004920static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004921#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004922 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004923 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004924
danaef49d72013-03-25 16:28:54 +00004925 /* If p==0 (unmap the entire file) then there must be no outstanding
4926 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4927 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004928 assert( (p==0)==(pFd->nFetchOut==0) );
4929
dandf737fe2013-03-25 17:00:24 +00004930 /* If p!=0, it must match the iOff value. */
4931 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4932
danf23da962013-03-23 21:00:41 +00004933 if( p ){
4934 pFd->nFetchOut--;
4935 }else{
4936 unixUnmapfile(pFd);
4937 }
4938
4939 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004940#else
4941 UNUSED_PARAMETER(fd);
4942 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004943 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004944#endif
danf23da962013-03-23 21:00:41 +00004945 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004946}
4947
4948/*
drh734c9862008-11-28 15:37:20 +00004949** Here ends the implementation of all sqlite3_file methods.
4950**
4951********************** End sqlite3_file Methods *******************************
4952******************************************************************************/
4953
4954/*
drh6b9d6dd2008-12-03 19:34:47 +00004955** This division contains definitions of sqlite3_io_methods objects that
4956** implement various file locking strategies. It also contains definitions
4957** of "finder" functions. A finder-function is used to locate the appropriate
4958** sqlite3_io_methods object for a particular database file. The pAppData
4959** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4960** the correct finder-function for that VFS.
4961**
4962** Most finder functions return a pointer to a fixed sqlite3_io_methods
4963** object. The only interesting finder-function is autolockIoFinder, which
4964** looks at the filesystem type and tries to guess the best locking
4965** strategy from that.
4966**
peter.d.reid60ec9142014-09-06 16:39:46 +00004967** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004968**
4969** (1) The real finder-function named "FImpt()".
4970**
dane946c392009-08-22 11:39:46 +00004971** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004972**
4973**
4974** A pointer to the F pointer is used as the pAppData value for VFS
4975** objects. We have to do this instead of letting pAppData point
4976** directly at the finder-function since C90 rules prevent a void*
4977** from be cast into a function pointer.
4978**
drh6b9d6dd2008-12-03 19:34:47 +00004979**
drh7708e972008-11-29 00:56:52 +00004980** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004981**
drh7708e972008-11-29 00:56:52 +00004982** * A constant sqlite3_io_methods object call METHOD that has locking
4983** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4984**
4985** * An I/O method finder function called FINDER that returns a pointer
4986** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004987*/
drhe6d41732015-02-21 00:49:00 +00004988#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004989static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004990 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004991 CLOSE, /* xClose */ \
4992 unixRead, /* xRead */ \
4993 unixWrite, /* xWrite */ \
4994 unixTruncate, /* xTruncate */ \
4995 unixSync, /* xSync */ \
4996 unixFileSize, /* xFileSize */ \
4997 LOCK, /* xLock */ \
4998 UNLOCK, /* xUnlock */ \
4999 CKLOCK, /* xCheckReservedLock */ \
5000 unixFileControl, /* xFileControl */ \
5001 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005002 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005003 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005004 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005005 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005006 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005007 unixFetch, /* xFetch */ \
5008 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005009}; \
drh0c2694b2009-09-03 16:23:44 +00005010static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5011 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005012 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005013} \
drh0c2694b2009-09-03 16:23:44 +00005014static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005015 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005016
5017/*
5018** Here are all of the sqlite3_io_methods objects for each of the
5019** locking strategies. Functions that return pointers to these methods
5020** are also created.
5021*/
5022IOMETHODS(
5023 posixIoFinder, /* Finder function name */
5024 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005025 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005026 unixClose, /* xClose method */
5027 unixLock, /* xLock method */
5028 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005029 unixCheckReservedLock, /* xCheckReservedLock method */
5030 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005031)
drh7708e972008-11-29 00:56:52 +00005032IOMETHODS(
5033 nolockIoFinder, /* Finder function name */
5034 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005035 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005036 nolockClose, /* xClose method */
5037 nolockLock, /* xLock method */
5038 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005039 nolockCheckReservedLock, /* xCheckReservedLock method */
5040 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005041)
drh7708e972008-11-29 00:56:52 +00005042IOMETHODS(
5043 dotlockIoFinder, /* Finder function name */
5044 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005045 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005046 dotlockClose, /* xClose method */
5047 dotlockLock, /* xLock method */
5048 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005049 dotlockCheckReservedLock, /* xCheckReservedLock method */
5050 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005051)
drh7708e972008-11-29 00:56:52 +00005052
drhe89b2912015-03-03 20:42:01 +00005053#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005054IOMETHODS(
5055 flockIoFinder, /* Finder function name */
5056 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005057 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005058 flockClose, /* xClose method */
5059 flockLock, /* xLock method */
5060 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005061 flockCheckReservedLock, /* xCheckReservedLock method */
5062 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005063)
drh7708e972008-11-29 00:56:52 +00005064#endif
5065
drh6c7d5c52008-11-21 20:32:33 +00005066#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005067IOMETHODS(
5068 semIoFinder, /* Finder function name */
5069 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005070 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005071 semXClose, /* xClose method */
5072 semXLock, /* xLock method */
5073 semXUnlock, /* xUnlock method */
5074 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005075 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005076)
aswiftaebf4132008-11-21 00:10:35 +00005077#endif
drh7708e972008-11-29 00:56:52 +00005078
drhd2cb50b2009-01-09 21:41:17 +00005079#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005080IOMETHODS(
5081 afpIoFinder, /* Finder function name */
5082 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005083 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005084 afpClose, /* xClose method */
5085 afpLock, /* xLock method */
5086 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005087 afpCheckReservedLock, /* xCheckReservedLock method */
5088 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005089)
drh715ff302008-12-03 22:32:44 +00005090#endif
5091
5092/*
5093** The proxy locking method is a "super-method" in the sense that it
5094** opens secondary file descriptors for the conch and lock files and
5095** it uses proxy, dot-file, AFP, and flock() locking methods on those
5096** secondary files. For this reason, the division that implements
5097** proxy locking is located much further down in the file. But we need
5098** to go ahead and define the sqlite3_io_methods and finder function
5099** for proxy locking here. So we forward declare the I/O methods.
5100*/
drhd2cb50b2009-01-09 21:41:17 +00005101#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005102static int proxyClose(sqlite3_file*);
5103static int proxyLock(sqlite3_file*, int);
5104static int proxyUnlock(sqlite3_file*, int);
5105static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005106IOMETHODS(
5107 proxyIoFinder, /* Finder function name */
5108 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005109 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005110 proxyClose, /* xClose method */
5111 proxyLock, /* xLock method */
5112 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005113 proxyCheckReservedLock, /* xCheckReservedLock method */
5114 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005115)
aswiftaebf4132008-11-21 00:10:35 +00005116#endif
drh7708e972008-11-29 00:56:52 +00005117
drh7ed97b92010-01-20 13:07:21 +00005118/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5119#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5120IOMETHODS(
5121 nfsIoFinder, /* Finder function name */
5122 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005123 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005124 unixClose, /* xClose method */
5125 unixLock, /* xLock method */
5126 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005127 unixCheckReservedLock, /* xCheckReservedLock method */
5128 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005129)
5130#endif
drh7708e972008-11-29 00:56:52 +00005131
drhd2cb50b2009-01-09 21:41:17 +00005132#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005133/*
drh6b9d6dd2008-12-03 19:34:47 +00005134** This "finder" function attempts to determine the best locking strategy
5135** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005136** object that implements that strategy.
5137**
5138** This is for MacOSX only.
5139*/
drh1875f7a2008-12-08 18:19:17 +00005140static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005141 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005142 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005143){
5144 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005145 const char *zFilesystem; /* Filesystem type name */
5146 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005147 } aMap[] = {
5148 { "hfs", &posixIoMethods },
5149 { "ufs", &posixIoMethods },
5150 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005151 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005152 { "webdav", &nolockIoMethods },
5153 { 0, 0 }
5154 };
5155 int i;
5156 struct statfs fsInfo;
5157 struct flock lockInfo;
5158
5159 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005160 /* If filePath==NULL that means we are dealing with a transient file
5161 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005162 return &nolockIoMethods;
5163 }
5164 if( statfs(filePath, &fsInfo) != -1 ){
5165 if( fsInfo.f_flags & MNT_RDONLY ){
5166 return &nolockIoMethods;
5167 }
5168 for(i=0; aMap[i].zFilesystem; i++){
5169 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5170 return aMap[i].pMethods;
5171 }
5172 }
5173 }
5174
5175 /* Default case. Handles, amongst others, "nfs".
5176 ** Test byte-range lock using fcntl(). If the call succeeds,
5177 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005178 */
drh7708e972008-11-29 00:56:52 +00005179 lockInfo.l_len = 1;
5180 lockInfo.l_start = 0;
5181 lockInfo.l_whence = SEEK_SET;
5182 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005183 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005184 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5185 return &nfsIoMethods;
5186 } else {
5187 return &posixIoMethods;
5188 }
drh7708e972008-11-29 00:56:52 +00005189 }else{
5190 return &dotlockIoMethods;
5191 }
5192}
drh0c2694b2009-09-03 16:23:44 +00005193static const sqlite3_io_methods
5194 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005195
drhd2cb50b2009-01-09 21:41:17 +00005196#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005197
drhe89b2912015-03-03 20:42:01 +00005198#if OS_VXWORKS
5199/*
5200** This "finder" function for VxWorks checks to see if posix advisory
5201** locking works. If it does, then that is what is used. If it does not
5202** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005203*/
drhe89b2912015-03-03 20:42:01 +00005204static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005205 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005206 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005207){
5208 struct flock lockInfo;
5209
5210 if( !filePath ){
5211 /* If filePath==NULL that means we are dealing with a transient file
5212 ** that does not need to be locked. */
5213 return &nolockIoMethods;
5214 }
5215
5216 /* Test if fcntl() is supported and use POSIX style locks.
5217 ** Otherwise fall back to the named semaphore method.
5218 */
5219 lockInfo.l_len = 1;
5220 lockInfo.l_start = 0;
5221 lockInfo.l_whence = SEEK_SET;
5222 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005223 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005224 return &posixIoMethods;
5225 }else{
5226 return &semIoMethods;
5227 }
5228}
drh0c2694b2009-09-03 16:23:44 +00005229static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005230 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005231
drhe89b2912015-03-03 20:42:01 +00005232#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005233
drh7708e972008-11-29 00:56:52 +00005234/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005235** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005236*/
drh0c2694b2009-09-03 16:23:44 +00005237typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005238
aswiftaebf4132008-11-21 00:10:35 +00005239
drh734c9862008-11-28 15:37:20 +00005240/****************************************************************************
5241**************************** sqlite3_vfs methods ****************************
5242**
5243** This division contains the implementation of methods on the
5244** sqlite3_vfs object.
5245*/
5246
danielk1977a3d4c882007-03-23 10:08:38 +00005247/*
danielk1977e339d652008-06-28 11:23:00 +00005248** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005249*/
5250static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005251 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005252 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005253 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005254 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005255 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005256){
drh7708e972008-11-29 00:56:52 +00005257 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005258 unixFile *pNew = (unixFile *)pId;
5259 int rc = SQLITE_OK;
5260
drh8af6c222010-05-14 12:43:01 +00005261 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005262
dan00157392010-10-05 11:33:15 +00005263 /* Usually the path zFilename should not be a relative pathname. The
5264 ** exception is when opening the proxy "conch" file in builds that
5265 ** include the special Apple locking styles.
5266 */
dan00157392010-10-05 11:33:15 +00005267#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005268 assert( zFilename==0 || zFilename[0]=='/'
5269 || pVfs->pAppData==(void*)&autolockIoFinder );
5270#else
5271 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005272#endif
dan00157392010-10-05 11:33:15 +00005273
drhb07028f2011-10-14 21:49:18 +00005274 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005275 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005276
drh308c2a52010-05-14 11:30:18 +00005277 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005278 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005279 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005280 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005281 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005282#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005283 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005284#endif
drhc02a43a2012-01-10 23:18:38 +00005285 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5286 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005287 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005288 }
drh503a6862013-03-01 01:07:17 +00005289 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005290 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005291 }
drh339eb0b2008-03-07 15:34:11 +00005292
drh6c7d5c52008-11-21 20:32:33 +00005293#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005294 pNew->pId = vxworksFindFileId(zFilename);
5295 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005296 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005297 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005298 }
5299#endif
5300
drhc02a43a2012-01-10 23:18:38 +00005301 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005302 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005303 }else{
drh0c2694b2009-09-03 16:23:44 +00005304 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005305#if SQLITE_ENABLE_LOCKING_STYLE
5306 /* Cache zFilename in the locking context (AFP and dotlock override) for
5307 ** proxyLock activation is possible (remote proxy is based on db name)
5308 ** zFilename remains valid until file is closed, to support */
5309 pNew->lockingContext = (void*)zFilename;
5310#endif
drhda0e7682008-07-30 15:27:54 +00005311 }
danielk1977e339d652008-06-28 11:23:00 +00005312
drh7ed97b92010-01-20 13:07:21 +00005313 if( pLockingStyle == &posixIoMethods
5314#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5315 || pLockingStyle == &nfsIoMethods
5316#endif
5317 ){
drh7708e972008-11-29 00:56:52 +00005318 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005319 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005320 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005321 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005322 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005323 ** in two scenarios:
5324 **
5325 ** (a) A call to fstat() failed.
5326 ** (b) A malloc failed.
5327 **
5328 ** Scenario (b) may only occur if the process is holding no other
5329 ** file descriptors open on the same file. If there were other file
5330 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005331 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005332 ** handle h - as it is guaranteed that no posix locks will be released
5333 ** by doing so.
5334 **
5335 ** If scenario (a) caused the error then things are not so safe. The
5336 ** implicit assumption here is that if fstat() fails, things are in
5337 ** such bad shape that dropping a lock or two doesn't matter much.
5338 */
drh0e9365c2011-03-02 02:08:13 +00005339 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005340 h = -1;
5341 }
drh7708e972008-11-29 00:56:52 +00005342 unixLeaveMutex();
5343 }
danielk1977e339d652008-06-28 11:23:00 +00005344
drhd2cb50b2009-01-09 21:41:17 +00005345#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005346 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005347 /* AFP locking uses the file path so it needs to be included in
5348 ** the afpLockingContext.
5349 */
5350 afpLockingContext *pCtx;
5351 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
5352 if( pCtx==0 ){
5353 rc = SQLITE_NOMEM;
5354 }else{
5355 /* NB: zFilename exists and remains valid until the file is closed
5356 ** according to requirement F11141. So we do not need to make a
5357 ** copy of the filename. */
5358 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005359 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005360 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005361 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005362 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005363 if( rc!=SQLITE_OK ){
5364 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005365 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005366 h = -1;
5367 }
drh7708e972008-11-29 00:56:52 +00005368 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005369 }
drh7708e972008-11-29 00:56:52 +00005370 }
5371#endif
danielk1977e339d652008-06-28 11:23:00 +00005372
drh7708e972008-11-29 00:56:52 +00005373 else if( pLockingStyle == &dotlockIoMethods ){
5374 /* Dotfile locking uses the file path so it needs to be included in
5375 ** the dotlockLockingContext
5376 */
5377 char *zLockFile;
5378 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005379 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005380 nFilename = (int)strlen(zFilename) + 6;
drh7708e972008-11-29 00:56:52 +00005381 zLockFile = (char *)sqlite3_malloc(nFilename);
5382 if( zLockFile==0 ){
5383 rc = SQLITE_NOMEM;
5384 }else{
5385 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005386 }
drh7708e972008-11-29 00:56:52 +00005387 pNew->lockingContext = zLockFile;
5388 }
danielk1977e339d652008-06-28 11:23:00 +00005389
drh6c7d5c52008-11-21 20:32:33 +00005390#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005391 else if( pLockingStyle == &semIoMethods ){
5392 /* Named semaphore locking uses the file path so it needs to be
5393 ** included in the semLockingContext
5394 */
5395 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005396 rc = findInodeInfo(pNew, &pNew->pInode);
5397 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5398 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005399 int n;
drh2238dcc2009-08-27 17:56:20 +00005400 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005401 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005402 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005403 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005404 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5405 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005406 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005407 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005408 }
chw97185482008-11-17 08:05:31 +00005409 }
drh7708e972008-11-29 00:56:52 +00005410 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005411 }
drh7708e972008-11-29 00:56:52 +00005412#endif
aswift5b1a2562008-08-22 00:22:35 +00005413
drh4bf66fd2015-02-19 02:43:02 +00005414 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005415#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005416 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005417 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005418 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005419 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005420 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005421 }
chw97185482008-11-17 08:05:31 +00005422#endif
danielk1977e339d652008-06-28 11:23:00 +00005423 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005424 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005425 }else{
drh7708e972008-11-29 00:56:52 +00005426 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005427 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005428 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005429 }
danielk1977e339d652008-06-28 11:23:00 +00005430 return rc;
drh054889e2005-11-30 03:20:31 +00005431}
drh9c06c952005-11-26 00:25:00 +00005432
danielk1977ad94b582007-08-20 06:44:22 +00005433/*
drh8b3cf822010-06-01 21:02:51 +00005434** Return the name of a directory in which to put temporary files.
5435** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005436*/
drh7234c6d2010-06-19 15:10:09 +00005437static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005438 static const char *azDirs[] = {
5439 0,
aswiftaebf4132008-11-21 00:10:35 +00005440 0,
mistachkind95a3d32013-08-30 21:52:38 +00005441 0,
danielk197717b90b52008-06-06 11:11:25 +00005442 "/var/tmp",
5443 "/usr/tmp",
5444 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005445 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005446 };
drh8b3cf822010-06-01 21:02:51 +00005447 unsigned int i;
5448 struct stat buf;
5449 const char *zDir = 0;
5450
5451 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005452 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5453 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005454 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005455 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005456 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005457 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005458 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005459 break;
5460 }
5461 return zDir;
5462}
5463
5464/*
5465** Create a temporary file name in zBuf. zBuf must be allocated
5466** by the calling process and must be big enough to hold at least
5467** pVfs->mxPathname bytes.
5468*/
5469static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005470 static const unsigned char zChars[] =
5471 "abcdefghijklmnopqrstuvwxyz"
5472 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5473 "0123456789";
drh41022642008-11-21 00:24:42 +00005474 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005475 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005476
5477 /* It's odd to simulate an io-error here, but really this is just
5478 ** using the io-error infrastructure to test that SQLite handles this
5479 ** function failing.
5480 */
5481 SimulateIOError( return SQLITE_IOERR );
5482
drh7234c6d2010-06-19 15:10:09 +00005483 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005484 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005485
5486 /* Check that the output buffer is large enough for the temporary file
5487 ** name. If it is not, return SQLITE_ERROR.
5488 */
drhc02a43a2012-01-10 23:18:38 +00005489 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005490 return SQLITE_ERROR;
5491 }
5492
5493 do{
drhc02a43a2012-01-10 23:18:38 +00005494 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005495 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005496 sqlite3_randomness(15, &zBuf[j]);
5497 for(i=0; i<15; i++, j++){
5498 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5499 }
5500 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005501 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005502 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005503 return SQLITE_OK;
5504}
5505
drhd2cb50b2009-01-09 21:41:17 +00005506#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005507/*
5508** Routine to transform a unixFile into a proxy-locking unixFile.
5509** Implementation in the proxy-lock division, but used by unixOpen()
5510** if SQLITE_PREFER_PROXY_LOCKING is defined.
5511*/
5512static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005513#endif
drhc66d5b62008-12-03 22:48:32 +00005514
dan08da86a2009-08-21 17:18:03 +00005515/*
5516** Search for an unused file descriptor that was opened on the database
5517** file (not a journal or master-journal file) identified by pathname
5518** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5519** argument to this function.
5520**
5521** Such a file descriptor may exist if a database connection was closed
5522** but the associated file descriptor could not be closed because some
5523** other file descriptor open on the same file is holding a file-lock.
5524** Refer to comments in the unixClose() function and the lengthy comment
5525** describing "Posix Advisory Locking" at the start of this file for
5526** further details. Also, ticket #4018.
5527**
5528** If a suitable file descriptor is found, then it is returned. If no
5529** such file descriptor is located, -1 is returned.
5530*/
dane946c392009-08-22 11:39:46 +00005531static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5532 UnixUnusedFd *pUnused = 0;
5533
5534 /* Do not search for an unused file descriptor on vxworks. Not because
5535 ** vxworks would not benefit from the change (it might, we're not sure),
5536 ** but because no way to test it is currently available. It is better
5537 ** not to risk breaking vxworks support for the sake of such an obscure
5538 ** feature. */
5539#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005540 struct stat sStat; /* Results of stat() call */
5541
5542 /* A stat() call may fail for various reasons. If this happens, it is
5543 ** almost certain that an open() call on the same path will also fail.
5544 ** For this reason, if an error occurs in the stat() call here, it is
5545 ** ignored and -1 is returned. The caller will try to open a new file
5546 ** descriptor on the same path, fail, and return an error to SQLite.
5547 **
5548 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005549 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005550 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005551 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005552
5553 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005554 pInode = inodeList;
5555 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5556 || pInode->fileId.ino!=sStat.st_ino) ){
5557 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005558 }
drh8af6c222010-05-14 12:43:01 +00005559 if( pInode ){
dane946c392009-08-22 11:39:46 +00005560 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005561 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005562 pUnused = *pp;
5563 if( pUnused ){
5564 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005565 }
5566 }
5567 unixLeaveMutex();
5568 }
dane946c392009-08-22 11:39:46 +00005569#endif /* if !OS_VXWORKS */
5570 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005571}
danielk197717b90b52008-06-06 11:11:25 +00005572
5573/*
danddb0ac42010-07-14 14:48:58 +00005574** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005575** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005576** and a value suitable for passing as the third argument to open(2) is
5577** written to *pMode. If an IO error occurs, an SQLite error code is
5578** returned and the value of *pMode is not modified.
5579**
peter.d.reid60ec9142014-09-06 16:39:46 +00005580** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005581** an indication to robust_open() to create the file using
5582** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5583** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005584** this function queries the file-system for the permissions on the
5585** corresponding database file and sets *pMode to this value. Whenever
5586** possible, WAL and journal files are created using the same permissions
5587** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005588**
5589** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5590** original filename is unavailable. But 8_3_NAMES is only used for
5591** FAT filesystems and permissions do not matter there, so just use
5592** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005593*/
5594static int findCreateFileMode(
5595 const char *zPath, /* Path of file (possibly) being created */
5596 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005597 mode_t *pMode, /* OUT: Permissions to open file with */
5598 uid_t *pUid, /* OUT: uid to set on the file */
5599 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005600){
5601 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005602 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005603 *pUid = 0;
5604 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005605 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005606 char zDb[MAX_PATHNAME+1]; /* Database file path */
5607 int nDb; /* Number of valid bytes in zDb */
5608 struct stat sStat; /* Output of stat() on database file */
5609
dana0c989d2010-11-05 18:07:37 +00005610 /* zPath is a path to a WAL or journal file. The following block derives
5611 ** the path to the associated database file from zPath. This block handles
5612 ** the following naming conventions:
5613 **
5614 ** "<path to db>-journal"
5615 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005616 ** "<path to db>-journalNN"
5617 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005618 **
drhd337c5b2011-10-20 18:23:35 +00005619 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005620 ** used by the test_multiplex.c module.
5621 */
5622 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005623#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005624 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005625 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005626#else
5627 while( zPath[nDb]!='-' ){
5628 assert( nDb>0 );
5629 assert( zPath[nDb]!='\n' );
5630 nDb--;
5631 }
5632#endif
danddb0ac42010-07-14 14:48:58 +00005633 memcpy(zDb, zPath, nDb);
5634 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005635
drh58384f12011-07-28 00:14:45 +00005636 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005637 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005638 *pUid = sStat.st_uid;
5639 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005640 }else{
5641 rc = SQLITE_IOERR_FSTAT;
5642 }
5643 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5644 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005645 }
5646 return rc;
5647}
5648
5649/*
danielk1977ad94b582007-08-20 06:44:22 +00005650** Open the file zPath.
5651**
danielk1977b4b47412007-08-17 15:53:36 +00005652** Previously, the SQLite OS layer used three functions in place of this
5653** one:
5654**
5655** sqlite3OsOpenReadWrite();
5656** sqlite3OsOpenReadOnly();
5657** sqlite3OsOpenExclusive();
5658**
5659** These calls correspond to the following combinations of flags:
5660**
5661** ReadWrite() -> (READWRITE | CREATE)
5662** ReadOnly() -> (READONLY)
5663** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5664**
5665** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5666** true, the file was configured to be automatically deleted when the
5667** file handle closed. To achieve the same effect using this new
5668** interface, add the DELETEONCLOSE flag to those specified above for
5669** OpenExclusive().
5670*/
5671static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005672 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5673 const char *zPath, /* Pathname of file to be opened */
5674 sqlite3_file *pFile, /* The file descriptor to be filled in */
5675 int flags, /* Input flags to control the opening */
5676 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005677){
dan08da86a2009-08-21 17:18:03 +00005678 unixFile *p = (unixFile *)pFile;
5679 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005680 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005681 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005682 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005683 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005684 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005685
5686 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5687 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5688 int isCreate = (flags & SQLITE_OPEN_CREATE);
5689 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5690 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005691#if SQLITE_ENABLE_LOCKING_STYLE
5692 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5693#endif
drh3d4435b2011-08-26 20:55:50 +00005694#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5695 struct statfs fsInfo;
5696#endif
danielk1977b4b47412007-08-17 15:53:36 +00005697
danielk1977fee2d252007-08-18 10:59:19 +00005698 /* If creating a master or main-file journal, this function will open
5699 ** a file-descriptor on the directory too. The first time unixSync()
5700 ** is called the directory file descriptor will be fsync()ed and close()d.
5701 */
drh0059eae2011-08-08 23:48:40 +00005702 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005703 eType==SQLITE_OPEN_MASTER_JOURNAL
5704 || eType==SQLITE_OPEN_MAIN_JOURNAL
5705 || eType==SQLITE_OPEN_WAL
5706 ));
danielk1977fee2d252007-08-18 10:59:19 +00005707
danielk197717b90b52008-06-06 11:11:25 +00005708 /* If argument zPath is a NULL pointer, this function is required to open
5709 ** a temporary file. Use this buffer to store the file name in.
5710 */
drhc02a43a2012-01-10 23:18:38 +00005711 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005712 const char *zName = zPath;
5713
danielk1977fee2d252007-08-18 10:59:19 +00005714 /* Check the following statements are true:
5715 **
5716 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5717 ** (b) if CREATE is set, then READWRITE must also be set, and
5718 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005719 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005720 */
danielk1977b4b47412007-08-17 15:53:36 +00005721 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005722 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005723 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005724 assert(isDelete==0 || isCreate);
5725
danddb0ac42010-07-14 14:48:58 +00005726 /* The main DB, main journal, WAL file and master journal are never
5727 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005728 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5729 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5730 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005731 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005732
danielk1977fee2d252007-08-18 10:59:19 +00005733 /* Assert that the upper layer has set one of the "file-type" flags. */
5734 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5735 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5736 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005737 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005738 );
5739
drhb00d8622014-01-01 15:18:36 +00005740 /* Detect a pid change and reset the PRNG. There is a race condition
5741 ** here such that two or more threads all trying to open databases at
5742 ** the same instant might all reset the PRNG. But multiple resets
5743 ** are harmless.
5744 */
drh5ac93652015-03-21 20:59:43 +00005745 if( randomnessPid!=osGetpid(0) ){
5746 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005747 sqlite3_randomness(0,0);
5748 }
5749
dan08da86a2009-08-21 17:18:03 +00005750 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005751
dan08da86a2009-08-21 17:18:03 +00005752 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005753 UnixUnusedFd *pUnused;
5754 pUnused = findReusableFd(zName, flags);
5755 if( pUnused ){
5756 fd = pUnused->fd;
5757 }else{
dan6aa657f2009-08-24 18:57:58 +00005758 pUnused = sqlite3_malloc(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005759 if( !pUnused ){
5760 return SQLITE_NOMEM;
5761 }
5762 }
5763 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005764
5765 /* Database filenames are double-zero terminated if they are not
5766 ** URIs with parameters. Hence, they can always be passed into
5767 ** sqlite3_uri_parameter(). */
5768 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5769
dan08da86a2009-08-21 17:18:03 +00005770 }else if( !zName ){
5771 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005772 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005773 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005774 if( rc!=SQLITE_OK ){
5775 return rc;
5776 }
5777 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005778
5779 /* Generated temporary filenames are always double-zero terminated
5780 ** for use by sqlite3_uri_parameter(). */
5781 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005782 }
5783
dan08da86a2009-08-21 17:18:03 +00005784 /* Determine the value of the flags parameter passed to POSIX function
5785 ** open(). These must be calculated even if open() is not called, as
5786 ** they may be stored as part of the file handle and used by the
5787 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005788 if( isReadonly ) openFlags |= O_RDONLY;
5789 if( isReadWrite ) openFlags |= O_RDWR;
5790 if( isCreate ) openFlags |= O_CREAT;
5791 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5792 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005793
danielk1977b4b47412007-08-17 15:53:36 +00005794 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005795 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005796 uid_t uid; /* Userid for the file */
5797 gid_t gid; /* Groupid for the file */
5798 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005799 if( rc!=SQLITE_OK ){
5800 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005801 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005802 return rc;
5803 }
drhad4f1e52011-03-04 15:43:57 +00005804 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005805 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005806 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5807 /* Failed to open the file for read/write access. Try read-only. */
5808 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005809 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005810 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005811 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005812 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005813 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005814 }
5815 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005816 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005817 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005818 }
drhac7c3ac2012-02-11 19:23:48 +00005819
5820 /* If this process is running as root and if creating a new rollback
5821 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005822 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005823 */
5824 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005825 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005826 }
danielk1977b4b47412007-08-17 15:53:36 +00005827 }
dan08da86a2009-08-21 17:18:03 +00005828 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005829 if( pOutFlags ){
5830 *pOutFlags = flags;
5831 }
5832
dane946c392009-08-22 11:39:46 +00005833 if( p->pUnused ){
5834 p->pUnused->fd = fd;
5835 p->pUnused->flags = flags;
5836 }
5837
danielk1977b4b47412007-08-17 15:53:36 +00005838 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005839#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005840 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005841#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5842 zPath = sqlite3_mprintf("%s", zName);
5843 if( zPath==0 ){
5844 robust_close(p, fd, __LINE__);
5845 return SQLITE_NOMEM;
5846 }
chw97185482008-11-17 08:05:31 +00005847#else
drh036ac7f2011-08-08 23:18:05 +00005848 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005849#endif
danielk1977b4b47412007-08-17 15:53:36 +00005850 }
drh41022642008-11-21 00:24:42 +00005851#if SQLITE_ENABLE_LOCKING_STYLE
5852 else{
dan08da86a2009-08-21 17:18:03 +00005853 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005854 }
5855#endif
5856
drhda0e7682008-07-30 15:27:54 +00005857 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005858
drh7ed97b92010-01-20 13:07:21 +00005859
5860#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005861 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005862 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005863 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005864 return SQLITE_IOERR_ACCESS;
5865 }
5866 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5867 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5868 }
drh4bf66fd2015-02-19 02:43:02 +00005869 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5870 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5871 }
drh7ed97b92010-01-20 13:07:21 +00005872#endif
drhc02a43a2012-01-10 23:18:38 +00005873
5874 /* Set up appropriate ctrlFlags */
5875 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5876 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5877 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5878 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5879 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5880
drh7ed97b92010-01-20 13:07:21 +00005881#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005882#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005883 isAutoProxy = 1;
5884#endif
5885 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005886 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5887 int useProxy = 0;
5888
dan08da86a2009-08-21 17:18:03 +00005889 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5890 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005891 if( envforce!=NULL ){
5892 useProxy = atoi(envforce)>0;
5893 }else{
aswiftaebf4132008-11-21 00:10:35 +00005894 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5895 }
5896 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005897 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005898 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005899 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005900 if( rc!=SQLITE_OK ){
5901 /* Use unixClose to clean up the resources added in fillInUnixFile
5902 ** and clear all the structure's references. Specifically,
5903 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5904 */
5905 unixClose(pFile);
5906 return rc;
5907 }
aswiftaebf4132008-11-21 00:10:35 +00005908 }
dane946c392009-08-22 11:39:46 +00005909 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005910 }
5911 }
5912#endif
5913
drhc02a43a2012-01-10 23:18:38 +00005914 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5915
dane946c392009-08-22 11:39:46 +00005916open_finished:
5917 if( rc!=SQLITE_OK ){
5918 sqlite3_free(p->pUnused);
5919 }
5920 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005921}
5922
dane946c392009-08-22 11:39:46 +00005923
danielk1977b4b47412007-08-17 15:53:36 +00005924/*
danielk1977fee2d252007-08-18 10:59:19 +00005925** Delete the file at zPath. If the dirSync argument is true, fsync()
5926** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005927*/
drh6b9d6dd2008-12-03 19:34:47 +00005928static int unixDelete(
5929 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5930 const char *zPath, /* Name of file to be deleted */
5931 int dirSync /* If true, fsync() directory after deleting file */
5932){
danielk1977fee2d252007-08-18 10:59:19 +00005933 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005934 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005935 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005936 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005937 if( errno==ENOENT
5938#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005939 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005940#endif
5941 ){
dan9fc5b4a2012-11-09 20:17:26 +00005942 rc = SQLITE_IOERR_DELETE_NOENT;
5943 }else{
drhb4308162012-11-09 21:40:02 +00005944 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005945 }
drhb4308162012-11-09 21:40:02 +00005946 return rc;
drh5d4feff2010-07-14 01:45:22 +00005947 }
danielk1977d39fa702008-10-16 13:27:40 +00005948#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005949 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005950 int fd;
drh90315a22011-08-10 01:52:12 +00005951 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005952 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005953#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005954 if( fsync(fd)==-1 )
5955#else
5956 if( fsync(fd) )
5957#endif
5958 {
dane18d4952011-02-21 11:46:24 +00005959 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005960 }
drh0e9365c2011-03-02 02:08:13 +00005961 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005962 }else if( rc==SQLITE_CANTOPEN ){
5963 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005964 }
5965 }
danielk1977d138dd82008-10-15 16:02:48 +00005966#endif
danielk1977fee2d252007-08-18 10:59:19 +00005967 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005968}
5969
danielk197790949c22007-08-17 16:50:38 +00005970/*
mistachkin48864df2013-03-21 21:20:32 +00005971** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005972** test performed depends on the value of flags:
5973**
5974** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5975** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5976** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5977**
5978** Otherwise return 0.
5979*/
danielk1977861f7452008-06-05 11:39:11 +00005980static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005981 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5982 const char *zPath, /* Path of the file to examine */
5983 int flags, /* What do we want to learn about the zPath file? */
5984 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005985){
rse25c0d1a2007-09-20 08:38:14 +00005986 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005987 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005988 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005989 switch( flags ){
5990 case SQLITE_ACCESS_EXISTS:
5991 amode = F_OK;
5992 break;
5993 case SQLITE_ACCESS_READWRITE:
5994 amode = W_OK|R_OK;
5995 break;
drh50d3f902007-08-27 21:10:36 +00005996 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005997 amode = R_OK;
5998 break;
5999
6000 default:
6001 assert(!"Invalid flags argument");
6002 }
drh99ab3b12011-03-02 15:09:07 +00006003 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00006004 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
6005 struct stat buf;
drh58384f12011-07-28 00:14:45 +00006006 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00006007 *pResOut = 0;
6008 }
6009 }
danielk1977861f7452008-06-05 11:39:11 +00006010 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006011}
6012
danielk1977b4b47412007-08-17 15:53:36 +00006013
6014/*
6015** Turn a relative pathname into a full pathname. The relative path
6016** is stored as a nul-terminated string in the buffer pointed to by
6017** zPath.
6018**
6019** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6020** (in this case, MAX_PATHNAME bytes). The full-path is written to
6021** this buffer before returning.
6022*/
danielk1977adfb9b02007-09-17 07:02:56 +00006023static int unixFullPathname(
6024 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6025 const char *zPath, /* Possibly relative input path */
6026 int nOut, /* Size of output buffer in bytes */
6027 char *zOut /* Output buffer */
6028){
danielk1977843e65f2007-09-01 16:16:15 +00006029
6030 /* It's odd to simulate an io-error here, but really this is just
6031 ** using the io-error infrastructure to test that SQLite handles this
6032 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006033 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006034 */
6035 SimulateIOError( return SQLITE_ERROR );
6036
drh153c62c2007-08-24 03:51:33 +00006037 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006038 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006039
drh3c7f2dc2007-12-06 13:26:20 +00006040 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006041 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006042 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006043 }else{
6044 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006045 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006046 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006047 }
drhea678832008-12-10 19:26:22 +00006048 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006049 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006050 }
6051 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006052}
6053
drh0ccebe72005-06-07 22:22:50 +00006054
drh761df872006-12-21 01:29:22 +00006055#ifndef SQLITE_OMIT_LOAD_EXTENSION
6056/*
6057** Interfaces for opening a shared library, finding entry points
6058** within the shared library, and closing the shared library.
6059*/
6060#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006061static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6062 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006063 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6064}
danielk197795c8a542007-09-01 06:51:27 +00006065
6066/*
6067** SQLite calls this function immediately after a call to unixDlSym() or
6068** unixDlOpen() fails (returns a null pointer). If a more detailed error
6069** message is available, it is written to zBufOut. If no error message
6070** is available, zBufOut is left unmodified and SQLite uses a default
6071** error message.
6072*/
danielk1977397d65f2008-11-19 11:35:39 +00006073static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006074 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006075 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006076 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006077 zErr = dlerror();
6078 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006079 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006080 }
drh6c7d5c52008-11-21 20:32:33 +00006081 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006082}
drh1875f7a2008-12-08 18:19:17 +00006083static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6084 /*
6085 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6086 ** cast into a pointer to a function. And yet the library dlsym() routine
6087 ** returns a void* which is really a pointer to a function. So how do we
6088 ** use dlsym() with -pedantic-errors?
6089 **
6090 ** Variable x below is defined to be a pointer to a function taking
6091 ** parameters void* and const char* and returning a pointer to a function.
6092 ** We initialize x by assigning it a pointer to the dlsym() function.
6093 ** (That assignment requires a cast.) Then we call the function that
6094 ** x points to.
6095 **
6096 ** This work-around is unlikely to work correctly on any system where
6097 ** you really cannot cast a function pointer into void*. But then, on the
6098 ** other hand, dlsym() will not work on such a system either, so we have
6099 ** not really lost anything.
6100 */
6101 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006102 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006103 x = (void(*(*)(void*,const char*))(void))dlsym;
6104 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006105}
danielk1977397d65f2008-11-19 11:35:39 +00006106static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6107 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006108 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006109}
danielk1977b4b47412007-08-17 15:53:36 +00006110#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6111 #define unixDlOpen 0
6112 #define unixDlError 0
6113 #define unixDlSym 0
6114 #define unixDlClose 0
6115#endif
6116
6117/*
danielk197790949c22007-08-17 16:50:38 +00006118** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006119*/
danielk1977397d65f2008-11-19 11:35:39 +00006120static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6121 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006122 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006123
drhbbd42a62004-05-22 17:41:58 +00006124 /* We have to initialize zBuf to prevent valgrind from reporting
6125 ** errors. The reports issued by valgrind are incorrect - we would
6126 ** prefer that the randomness be increased by making use of the
6127 ** uninitialized space in zBuf - but valgrind errors tend to worry
6128 ** some users. Rather than argue, it seems easier just to initialize
6129 ** the whole array and silence valgrind, even if that means less randomness
6130 ** in the random seed.
6131 **
6132 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006133 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006134 ** tests repeatable.
6135 */
danielk1977b4b47412007-08-17 15:53:36 +00006136 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006137 randomnessPid = osGetpid(0);
drhbbd42a62004-05-22 17:41:58 +00006138#if !defined(SQLITE_TEST)
6139 {
drhb00d8622014-01-01 15:18:36 +00006140 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006141 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006142 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006143 time_t t;
6144 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006145 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006146 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6147 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6148 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006149 }else{
drhc18b4042012-02-10 03:10:27 +00006150 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006151 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006152 }
drhbbd42a62004-05-22 17:41:58 +00006153 }
6154#endif
drh72cbd072008-10-14 17:58:38 +00006155 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006156}
6157
danielk1977b4b47412007-08-17 15:53:36 +00006158
drhbbd42a62004-05-22 17:41:58 +00006159/*
6160** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006161** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006162** The return value is the number of microseconds of sleep actually
6163** requested from the underlying operating system, a number which
6164** might be greater than or equal to the argument, but not less
6165** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006166*/
danielk1977397d65f2008-11-19 11:35:39 +00006167static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006168#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006169 struct timespec sp;
6170
6171 sp.tv_sec = microseconds / 1000000;
6172 sp.tv_nsec = (microseconds % 1000000) * 1000;
6173 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006174 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006175 return microseconds;
6176#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006177 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006178 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006179 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006180#else
danielk1977b4b47412007-08-17 15:53:36 +00006181 int seconds = (microseconds+999999)/1000000;
6182 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006183 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006184 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006185#endif
drh88f474a2006-01-02 20:00:12 +00006186}
6187
6188/*
drh6b9d6dd2008-12-03 19:34:47 +00006189** The following variable, if set to a non-zero value, is interpreted as
6190** the number of seconds since 1970 and is used to set the result of
6191** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006192*/
6193#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006194int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006195#endif
6196
6197/*
drhb7e8ea22010-05-03 14:32:30 +00006198** Find the current time (in Universal Coordinated Time). Write into *piNow
6199** the current time and date as a Julian Day number times 86_400_000. In
6200** other words, write into *piNow the number of milliseconds since the Julian
6201** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6202** proleptic Gregorian calendar.
6203**
drh31702252011-10-12 23:13:43 +00006204** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6205** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006206*/
6207static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6208 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006209 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006210#if defined(NO_GETTOD)
6211 time_t t;
6212 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006213 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006214#elif OS_VXWORKS
6215 struct timespec sNow;
6216 clock_gettime(CLOCK_REALTIME, &sNow);
6217 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6218#else
6219 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006220 if( gettimeofday(&sNow, 0)==0 ){
6221 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6222 }else{
6223 rc = SQLITE_ERROR;
6224 }
drhb7e8ea22010-05-03 14:32:30 +00006225#endif
6226
6227#ifdef SQLITE_TEST
6228 if( sqlite3_current_time ){
6229 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6230 }
6231#endif
6232 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006233 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006234}
6235
6236/*
drhbbd42a62004-05-22 17:41:58 +00006237** Find the current time (in Universal Coordinated Time). Write the
6238** current time and date as a Julian Day number into *prNow and
6239** return 0. Return 1 if the time and date cannot be found.
6240*/
danielk1977397d65f2008-11-19 11:35:39 +00006241static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006242 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006243 int rc;
drhff828942010-06-26 21:34:06 +00006244 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006245 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006246 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006247 return rc;
drhbbd42a62004-05-22 17:41:58 +00006248}
danielk1977b4b47412007-08-17 15:53:36 +00006249
drh6b9d6dd2008-12-03 19:34:47 +00006250/*
6251** We added the xGetLastError() method with the intention of providing
6252** better low-level error messages when operating-system problems come up
6253** during SQLite operation. But so far, none of that has been implemented
6254** in the core. So this routine is never called. For now, it is merely
6255** a place-holder.
6256*/
danielk1977397d65f2008-11-19 11:35:39 +00006257static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6258 UNUSED_PARAMETER(NotUsed);
6259 UNUSED_PARAMETER(NotUsed2);
6260 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006261 return 0;
6262}
6263
drhf2424c52010-04-26 00:04:55 +00006264
6265/*
drh734c9862008-11-28 15:37:20 +00006266************************ End of sqlite3_vfs methods ***************************
6267******************************************************************************/
6268
drh715ff302008-12-03 22:32:44 +00006269/******************************************************************************
6270************************** Begin Proxy Locking ********************************
6271**
6272** Proxy locking is a "uber-locking-method" in this sense: It uses the
6273** other locking methods on secondary lock files. Proxy locking is a
6274** meta-layer over top of the primitive locking implemented above. For
6275** this reason, the division that implements of proxy locking is deferred
6276** until late in the file (here) after all of the other I/O methods have
6277** been defined - so that the primitive locking methods are available
6278** as services to help with the implementation of proxy locking.
6279**
6280****
6281**
6282** The default locking schemes in SQLite use byte-range locks on the
6283** database file to coordinate safe, concurrent access by multiple readers
6284** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6285** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6286** as POSIX read & write locks over fixed set of locations (via fsctl),
6287** on AFP and SMB only exclusive byte-range locks are available via fsctl
6288** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6289** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6290** address in the shared range is taken for a SHARED lock, the entire
6291** shared range is taken for an EXCLUSIVE lock):
6292**
drhf2f105d2012-08-20 15:53:54 +00006293** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006294** RESERVED_BYTE 0x40000001
6295** SHARED_RANGE 0x40000002 -> 0x40000200
6296**
6297** This works well on the local file system, but shows a nearly 100x
6298** slowdown in read performance on AFP because the AFP client disables
6299** the read cache when byte-range locks are present. Enabling the read
6300** cache exposes a cache coherency problem that is present on all OS X
6301** supported network file systems. NFS and AFP both observe the
6302** close-to-open semantics for ensuring cache coherency
6303** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6304** address the requirements for concurrent database access by multiple
6305** readers and writers
6306** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6307**
6308** To address the performance and cache coherency issues, proxy file locking
6309** changes the way database access is controlled by limiting access to a
6310** single host at a time and moving file locks off of the database file
6311** and onto a proxy file on the local file system.
6312**
6313**
6314** Using proxy locks
6315** -----------------
6316**
6317** C APIs
6318**
drh4bf66fd2015-02-19 02:43:02 +00006319** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006320** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006321** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6322** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006323**
6324**
6325** SQL pragmas
6326**
6327** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6328** PRAGMA [database.]lock_proxy_file
6329**
6330** Specifying ":auto:" means that if there is a conch file with a matching
6331** host ID in it, the proxy path in the conch file will be used, otherwise
6332** a proxy path based on the user's temp dir
6333** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6334** actual proxy file name is generated from the name and path of the
6335** database file. For example:
6336**
6337** For database path "/Users/me/foo.db"
6338** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6339**
6340** Once a lock proxy is configured for a database connection, it can not
6341** be removed, however it may be switched to a different proxy path via
6342** the above APIs (assuming the conch file is not being held by another
6343** connection or process).
6344**
6345**
6346** How proxy locking works
6347** -----------------------
6348**
6349** Proxy file locking relies primarily on two new supporting files:
6350**
6351** * conch file to limit access to the database file to a single host
6352** at a time
6353**
6354** * proxy file to act as a proxy for the advisory locks normally
6355** taken on the database
6356**
6357** The conch file - to use a proxy file, sqlite must first "hold the conch"
6358** by taking an sqlite-style shared lock on the conch file, reading the
6359** contents and comparing the host's unique host ID (see below) and lock
6360** proxy path against the values stored in the conch. The conch file is
6361** stored in the same directory as the database file and the file name
6362** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006363** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006364** host ID and/or proxy path, then the lock is escalated to an exclusive
6365** lock and the conch file contents is updated with the host ID and proxy
6366** path and the lock is downgraded to a shared lock again. If the conch
6367** is held by another process (with a shared lock), the exclusive lock
6368** will fail and SQLITE_BUSY is returned.
6369**
6370** The proxy file - a single-byte file used for all advisory file locks
6371** normally taken on the database file. This allows for safe sharing
6372** of the database file for multiple readers and writers on the same
6373** host (the conch ensures that they all use the same local lock file).
6374**
drh715ff302008-12-03 22:32:44 +00006375** Requesting the lock proxy does not immediately take the conch, it is
6376** only taken when the first request to lock database file is made.
6377** This matches the semantics of the traditional locking behavior, where
6378** opening a connection to a database file does not take a lock on it.
6379** The shared lock and an open file descriptor are maintained until
6380** the connection to the database is closed.
6381**
6382** The proxy file and the lock file are never deleted so they only need
6383** to be created the first time they are used.
6384**
6385** Configuration options
6386** ---------------------
6387**
6388** SQLITE_PREFER_PROXY_LOCKING
6389**
6390** Database files accessed on non-local file systems are
6391** automatically configured for proxy locking, lock files are
6392** named automatically using the same logic as
6393** PRAGMA lock_proxy_file=":auto:"
6394**
6395** SQLITE_PROXY_DEBUG
6396**
6397** Enables the logging of error messages during host id file
6398** retrieval and creation
6399**
drh715ff302008-12-03 22:32:44 +00006400** LOCKPROXYDIR
6401**
6402** Overrides the default directory used for lock proxy files that
6403** are named automatically via the ":auto:" setting
6404**
6405** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6406**
6407** Permissions to use when creating a directory for storing the
6408** lock proxy files, only used when LOCKPROXYDIR is not set.
6409**
6410**
6411** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6412** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6413** force proxy locking to be used for every database file opened, and 0
6414** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006415** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006416** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6417*/
6418
6419/*
6420** Proxy locking is only available on MacOSX
6421*/
drhd2cb50b2009-01-09 21:41:17 +00006422#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006423
drh715ff302008-12-03 22:32:44 +00006424/*
6425** The proxyLockingContext has the path and file structures for the remote
6426** and local proxy files in it
6427*/
6428typedef struct proxyLockingContext proxyLockingContext;
6429struct proxyLockingContext {
6430 unixFile *conchFile; /* Open conch file */
6431 char *conchFilePath; /* Name of the conch file */
6432 unixFile *lockProxy; /* Open proxy lock file */
6433 char *lockProxyPath; /* Name of the proxy lock file */
6434 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006435 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006436 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006437 void *oldLockingContext; /* Original lockingcontext to restore on close */
6438 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6439};
6440
drh7ed97b92010-01-20 13:07:21 +00006441/*
6442** The proxy lock file path for the database at dbPath is written into lPath,
6443** which must point to valid, writable memory large enough for a maxLen length
6444** file path.
drh715ff302008-12-03 22:32:44 +00006445*/
drh715ff302008-12-03 22:32:44 +00006446static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6447 int len;
6448 int dbLen;
6449 int i;
6450
6451#ifdef LOCKPROXYDIR
6452 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6453#else
6454# ifdef _CS_DARWIN_USER_TEMP_DIR
6455 {
drh7ed97b92010-01-20 13:07:21 +00006456 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006457 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006458 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006459 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006460 }
drh7ed97b92010-01-20 13:07:21 +00006461 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006462 }
6463# else
6464 len = strlcpy(lPath, "/tmp/", maxLen);
6465# endif
6466#endif
6467
6468 if( lPath[len-1]!='/' ){
6469 len = strlcat(lPath, "/", maxLen);
6470 }
6471
6472 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006473 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006474 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006475 char c = dbPath[i];
6476 lPath[i+len] = (c=='/')?'_':c;
6477 }
6478 lPath[i+len]='\0';
6479 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006480 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006481 return SQLITE_OK;
6482}
6483
drh7ed97b92010-01-20 13:07:21 +00006484/*
6485 ** Creates the lock file and any missing directories in lockPath
6486 */
6487static int proxyCreateLockPath(const char *lockPath){
6488 int i, len;
6489 char buf[MAXPATHLEN];
6490 int start = 0;
6491
6492 assert(lockPath!=NULL);
6493 /* try to create all the intermediate directories */
6494 len = (int)strlen(lockPath);
6495 buf[0] = lockPath[0];
6496 for( i=1; i<len; i++ ){
6497 if( lockPath[i] == '/' && (i - start > 0) ){
6498 /* only mkdir if leaf dir != "." or "/" or ".." */
6499 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6500 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6501 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006502 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006503 int err=errno;
6504 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006505 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006506 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006507 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006508 return err;
6509 }
6510 }
6511 }
6512 start=i+1;
6513 }
6514 buf[i] = lockPath[i];
6515 }
drh5ac93652015-03-21 20:59:43 +00006516 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006517 return 0;
6518}
6519
drh715ff302008-12-03 22:32:44 +00006520/*
6521** Create a new VFS file descriptor (stored in memory obtained from
6522** sqlite3_malloc) and open the file named "path" in the file descriptor.
6523**
6524** The caller is responsible not only for closing the file descriptor
6525** but also for freeing the memory associated with the file descriptor.
6526*/
drh7ed97b92010-01-20 13:07:21 +00006527static int proxyCreateUnixFile(
6528 const char *path, /* path for the new unixFile */
6529 unixFile **ppFile, /* unixFile created and returned by ref */
6530 int islockfile /* if non zero missing dirs will be created */
6531) {
6532 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006533 unixFile *pNew;
6534 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006535 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006536 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006537 int terrno = 0;
6538 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006539
drh7ed97b92010-01-20 13:07:21 +00006540 /* 1. first try to open/create the file
6541 ** 2. if that fails, and this is a lock file (not-conch), try creating
6542 ** the parent directories and then try again.
6543 ** 3. if that fails, try to open the file read-only
6544 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6545 */
6546 pUnused = findReusableFd(path, openFlags);
6547 if( pUnused ){
6548 fd = pUnused->fd;
6549 }else{
6550 pUnused = sqlite3_malloc(sizeof(*pUnused));
6551 if( !pUnused ){
6552 return SQLITE_NOMEM;
6553 }
6554 }
6555 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006556 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006557 terrno = errno;
6558 if( fd<0 && errno==ENOENT && islockfile ){
6559 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006560 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006561 }
6562 }
6563 }
6564 if( fd<0 ){
6565 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006566 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006567 terrno = errno;
6568 }
6569 if( fd<0 ){
6570 if( islockfile ){
6571 return SQLITE_BUSY;
6572 }
6573 switch (terrno) {
6574 case EACCES:
6575 return SQLITE_PERM;
6576 case EIO:
6577 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6578 default:
drh9978c972010-02-23 17:36:32 +00006579 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006580 }
6581 }
6582
6583 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
6584 if( pNew==NULL ){
6585 rc = SQLITE_NOMEM;
6586 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006587 }
6588 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006589 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006590 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006591 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006592 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006593 pUnused->fd = fd;
6594 pUnused->flags = openFlags;
6595 pNew->pUnused = pUnused;
6596
drhc02a43a2012-01-10 23:18:38 +00006597 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006598 if( rc==SQLITE_OK ){
6599 *ppFile = pNew;
6600 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006601 }
drh7ed97b92010-01-20 13:07:21 +00006602end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006603 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006604 sqlite3_free(pNew);
6605 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006606 return rc;
6607}
6608
drh7ed97b92010-01-20 13:07:21 +00006609#ifdef SQLITE_TEST
6610/* simulate multiple hosts by creating unique hostid file paths */
6611int sqlite3_hostid_num = 0;
6612#endif
6613
6614#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6615
drh6bca6512015-04-13 23:05:28 +00006616#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006617/* Not always defined in the headers as it ought to be */
6618extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006619#endif
drh0ab216a2010-07-02 17:10:40 +00006620
drh7ed97b92010-01-20 13:07:21 +00006621/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6622** bytes of writable memory.
6623*/
6624static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006625 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6626 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006627#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006628 {
drh4bf66fd2015-02-19 02:43:02 +00006629 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006630 if( gethostuuid(pHostID, &timeout) ){
6631 int err = errno;
6632 if( pError ){
6633 *pError = err;
6634 }
6635 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006636 }
drh7ed97b92010-01-20 13:07:21 +00006637 }
drh3d4435b2011-08-26 20:55:50 +00006638#else
6639 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006640#endif
drh7ed97b92010-01-20 13:07:21 +00006641#ifdef SQLITE_TEST
6642 /* simulate multiple hosts by creating unique hostid file paths */
6643 if( sqlite3_hostid_num != 0){
6644 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6645 }
6646#endif
6647
6648 return SQLITE_OK;
6649}
6650
6651/* The conch file contains the header, host id and lock file path
6652 */
6653#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6654#define PROXY_HEADERLEN 1 /* conch file header length */
6655#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6656#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6657
6658/*
6659** Takes an open conch file, copies the contents to a new path and then moves
6660** it back. The newly created file's file descriptor is assigned to the
6661** conch file structure and finally the original conch file descriptor is
6662** closed. Returns zero if successful.
6663*/
6664static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6665 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6666 unixFile *conchFile = pCtx->conchFile;
6667 char tPath[MAXPATHLEN];
6668 char buf[PROXY_MAXCONCHLEN];
6669 char *cPath = pCtx->conchFilePath;
6670 size_t readLen = 0;
6671 size_t pathLen = 0;
6672 char errmsg[64] = "";
6673 int fd = -1;
6674 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006675 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006676
6677 /* create a new path by replace the trailing '-conch' with '-break' */
6678 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6679 if( pathLen>MAXPATHLEN || pathLen<6 ||
6680 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006681 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006682 goto end_breaklock;
6683 }
6684 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006685 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006686 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006687 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006688 goto end_breaklock;
6689 }
6690 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006691 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006692 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006693 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006694 goto end_breaklock;
6695 }
drhe562be52011-03-02 18:01:10 +00006696 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006697 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006698 goto end_breaklock;
6699 }
6700 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006701 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006702 goto end_breaklock;
6703 }
6704 rc = 0;
6705 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006706 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006707 conchFile->h = fd;
6708 conchFile->openFlags = O_RDWR | O_CREAT;
6709
6710end_breaklock:
6711 if( rc ){
6712 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006713 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006714 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006715 }
6716 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6717 }
6718 return rc;
6719}
6720
6721/* Take the requested lock on the conch file and break a stale lock if the
6722** host id matches.
6723*/
6724static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6725 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6726 unixFile *conchFile = pCtx->conchFile;
6727 int rc = SQLITE_OK;
6728 int nTries = 0;
6729 struct timespec conchModTime;
6730
drh3d4435b2011-08-26 20:55:50 +00006731 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006732 do {
6733 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6734 nTries ++;
6735 if( rc==SQLITE_BUSY ){
6736 /* If the lock failed (busy):
6737 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6738 * 2nd try: fail if the mod time changed or host id is different, wait
6739 * 10 sec and try again
6740 * 3rd try: break the lock unless the mod time has changed.
6741 */
6742 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006743 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006744 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006745 return SQLITE_IOERR_LOCK;
6746 }
6747
6748 if( nTries==1 ){
6749 conchModTime = buf.st_mtimespec;
6750 usleep(500000); /* wait 0.5 sec and try the lock again*/
6751 continue;
6752 }
6753
6754 assert( nTries>1 );
6755 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6756 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6757 return SQLITE_BUSY;
6758 }
6759
6760 if( nTries==2 ){
6761 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006762 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006763 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006764 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006765 return SQLITE_IOERR_LOCK;
6766 }
6767 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6768 /* don't break the lock if the host id doesn't match */
6769 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6770 return SQLITE_BUSY;
6771 }
6772 }else{
6773 /* don't break the lock on short read or a version mismatch */
6774 return SQLITE_BUSY;
6775 }
6776 usleep(10000000); /* wait 10 sec and try the lock again */
6777 continue;
6778 }
6779
6780 assert( nTries==3 );
6781 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6782 rc = SQLITE_OK;
6783 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006784 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006785 }
6786 if( !rc ){
6787 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6788 }
6789 }
6790 }
6791 } while( rc==SQLITE_BUSY && nTries<3 );
6792
6793 return rc;
6794}
6795
6796/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006797** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6798** lockPath means that the lockPath in the conch file will be used if the
6799** host IDs match, or a new lock path will be generated automatically
6800** and written to the conch file.
6801*/
6802static int proxyTakeConch(unixFile *pFile){
6803 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6804
drh7ed97b92010-01-20 13:07:21 +00006805 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006806 return SQLITE_OK;
6807 }else{
6808 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006809 uuid_t myHostID;
6810 int pError = 0;
6811 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006812 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006813 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006814 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006815 int createConch = 0;
6816 int hostIdMatch = 0;
6817 int readLen = 0;
6818 int tryOldLockPath = 0;
6819 int forceNewLockPath = 0;
6820
drh308c2a52010-05-14 11:30:18 +00006821 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006822 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006823 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006824
drh7ed97b92010-01-20 13:07:21 +00006825 rc = proxyGetHostID(myHostID, &pError);
6826 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006827 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006828 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006829 }
drh7ed97b92010-01-20 13:07:21 +00006830 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006831 if( rc!=SQLITE_OK ){
6832 goto end_takeconch;
6833 }
drh7ed97b92010-01-20 13:07:21 +00006834 /* read the existing conch file */
6835 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6836 if( readLen<0 ){
6837 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006838 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006839 rc = SQLITE_IOERR_READ;
6840 goto end_takeconch;
6841 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6842 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6843 /* a short read or version format mismatch means we need to create a new
6844 ** conch file.
6845 */
6846 createConch = 1;
6847 }
6848 /* if the host id matches and the lock path already exists in the conch
6849 ** we'll try to use the path there, if we can't open that path, we'll
6850 ** retry with a new auto-generated path
6851 */
6852 do { /* in case we need to try again for an :auto: named lock file */
6853
6854 if( !createConch && !forceNewLockPath ){
6855 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6856 PROXY_HOSTIDLEN);
6857 /* if the conch has data compare the contents */
6858 if( !pCtx->lockProxyPath ){
6859 /* for auto-named local lock file, just check the host ID and we'll
6860 ** use the local lock file path that's already in there
6861 */
6862 if( hostIdMatch ){
6863 size_t pathLen = (readLen - PROXY_PATHINDEX);
6864
6865 if( pathLen>=MAXPATHLEN ){
6866 pathLen=MAXPATHLEN-1;
6867 }
6868 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6869 lockPath[pathLen] = 0;
6870 tempLockPath = lockPath;
6871 tryOldLockPath = 1;
6872 /* create a copy of the lock path if the conch is taken */
6873 goto end_takeconch;
6874 }
6875 }else if( hostIdMatch
6876 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6877 readLen-PROXY_PATHINDEX)
6878 ){
6879 /* conch host and lock path match */
6880 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006881 }
drh7ed97b92010-01-20 13:07:21 +00006882 }
6883
6884 /* if the conch isn't writable and doesn't match, we can't take it */
6885 if( (conchFile->openFlags&O_RDWR) == 0 ){
6886 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006887 goto end_takeconch;
6888 }
drh7ed97b92010-01-20 13:07:21 +00006889
6890 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006891 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006892 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6893 tempLockPath = lockPath;
6894 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006895 }
drh7ed97b92010-01-20 13:07:21 +00006896
6897 /* update conch with host and path (this will fail if other process
6898 ** has a shared lock already), if the host id matches, use the big
6899 ** stick.
drh715ff302008-12-03 22:32:44 +00006900 */
drh7ed97b92010-01-20 13:07:21 +00006901 futimes(conchFile->h, NULL);
6902 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006903 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006904 /* We are trying for an exclusive lock but another thread in this
6905 ** same process is still holding a shared lock. */
6906 rc = SQLITE_BUSY;
6907 } else {
6908 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006909 }
drh715ff302008-12-03 22:32:44 +00006910 }else{
drh4bf66fd2015-02-19 02:43:02 +00006911 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006912 }
drh7ed97b92010-01-20 13:07:21 +00006913 if( rc==SQLITE_OK ){
6914 char writeBuffer[PROXY_MAXCONCHLEN];
6915 int writeSize = 0;
6916
6917 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6918 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6919 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006920 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6921 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006922 }else{
6923 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6924 }
6925 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006926 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006927 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6928 fsync(conchFile->h);
6929 /* If we created a new conch file (not just updated the contents of a
6930 ** valid conch file), try to match the permissions of the database
6931 */
6932 if( rc==SQLITE_OK && createConch ){
6933 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006934 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006935 if( err==0 ){
6936 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6937 S_IROTH|S_IWOTH);
6938 /* try to match the database file R/W permissions, ignore failure */
6939#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006940 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006941#else
drhff812312011-02-23 13:33:46 +00006942 do{
drhe562be52011-03-02 18:01:10 +00006943 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006944 }while( rc==(-1) && errno==EINTR );
6945 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006946 int code = errno;
6947 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6948 cmode, code, strerror(code));
6949 } else {
6950 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6951 }
6952 }else{
6953 int code = errno;
6954 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6955 err, code, strerror(code));
6956#endif
6957 }
drh715ff302008-12-03 22:32:44 +00006958 }
6959 }
drh7ed97b92010-01-20 13:07:21 +00006960 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6961
6962 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006963 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006964 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006965 int fd;
drh7ed97b92010-01-20 13:07:21 +00006966 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006967 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006968 }
6969 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006970 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006971 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006972 if( fd>=0 ){
6973 pFile->h = fd;
6974 }else{
drh9978c972010-02-23 17:36:32 +00006975 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006976 during locking */
6977 }
6978 }
6979 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6980 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6981 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6982 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6983 /* we couldn't create the proxy lock file with the old lock file path
6984 ** so try again via auto-naming
6985 */
6986 forceNewLockPath = 1;
6987 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006988 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006989 }
6990 }
6991 if( rc==SQLITE_OK ){
6992 /* Need to make a copy of path if we extracted the value
6993 ** from the conch file or the path was allocated on the stack
6994 */
6995 if( tempLockPath ){
6996 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6997 if( !pCtx->lockProxyPath ){
6998 rc = SQLITE_NOMEM;
6999 }
7000 }
7001 }
7002 if( rc==SQLITE_OK ){
7003 pCtx->conchHeld = 1;
7004
7005 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7006 afpLockingContext *afpCtx;
7007 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7008 afpCtx->dbPath = pCtx->lockProxyPath;
7009 }
7010 } else {
7011 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7012 }
drh308c2a52010-05-14 11:30:18 +00007013 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7014 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007015 return rc;
drh308c2a52010-05-14 11:30:18 +00007016 } while (1); /* in case we need to retry the :auto: lock file -
7017 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007018 }
7019}
7020
7021/*
7022** If pFile holds a lock on a conch file, then release that lock.
7023*/
7024static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007025 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007026 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7027 unixFile *conchFile; /* Name of the conch file */
7028
7029 pCtx = (proxyLockingContext *)pFile->lockingContext;
7030 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007031 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007032 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007033 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007034 if( pCtx->conchHeld>0 ){
7035 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7036 }
drh715ff302008-12-03 22:32:44 +00007037 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007038 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7039 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007040 return rc;
7041}
7042
7043/*
7044** Given the name of a database file, compute the name of its conch file.
7045** Store the conch filename in memory obtained from sqlite3_malloc().
7046** Make *pConchPath point to the new name. Return SQLITE_OK on success
7047** or SQLITE_NOMEM if unable to obtain memory.
7048**
7049** The caller is responsible for ensuring that the allocated memory
7050** space is eventually freed.
7051**
7052** *pConchPath is set to NULL if a memory allocation error occurs.
7053*/
7054static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7055 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007056 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007057 char *conchPath; /* buffer in which to construct conch name */
7058
7059 /* Allocate space for the conch filename and initialize the name to
7060 ** the name of the original database file. */
7061 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
7062 if( conchPath==0 ){
7063 return SQLITE_NOMEM;
7064 }
7065 memcpy(conchPath, dbPath, len+1);
7066
7067 /* now insert a "." before the last / character */
7068 for( i=(len-1); i>=0; i-- ){
7069 if( conchPath[i]=='/' ){
7070 i++;
7071 break;
7072 }
7073 }
7074 conchPath[i]='.';
7075 while ( i<len ){
7076 conchPath[i+1]=dbPath[i];
7077 i++;
7078 }
7079
7080 /* append the "-conch" suffix to the file */
7081 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007082 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007083
7084 return SQLITE_OK;
7085}
7086
7087
7088/* Takes a fully configured proxy locking-style unix file and switches
7089** the local lock file path
7090*/
7091static int switchLockProxyPath(unixFile *pFile, const char *path) {
7092 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7093 char *oldPath = pCtx->lockProxyPath;
7094 int rc = SQLITE_OK;
7095
drh308c2a52010-05-14 11:30:18 +00007096 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007097 return SQLITE_BUSY;
7098 }
7099
7100 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7101 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7102 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7103 return SQLITE_OK;
7104 }else{
7105 unixFile *lockProxy = pCtx->lockProxy;
7106 pCtx->lockProxy=NULL;
7107 pCtx->conchHeld = 0;
7108 if( lockProxy!=NULL ){
7109 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7110 if( rc ) return rc;
7111 sqlite3_free(lockProxy);
7112 }
7113 sqlite3_free(oldPath);
7114 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7115 }
7116
7117 return rc;
7118}
7119
7120/*
7121** pFile is a file that has been opened by a prior xOpen call. dbPath
7122** is a string buffer at least MAXPATHLEN+1 characters in size.
7123**
7124** This routine find the filename associated with pFile and writes it
7125** int dbPath.
7126*/
7127static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007128#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007129 if( pFile->pMethod == &afpIoMethods ){
7130 /* afp style keeps a reference to the db path in the filePath field
7131 ** of the struct */
drhea678832008-12-10 19:26:22 +00007132 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007133 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7134 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007135 } else
drh715ff302008-12-03 22:32:44 +00007136#endif
7137 if( pFile->pMethod == &dotlockIoMethods ){
7138 /* dot lock style uses the locking context to store the dot lock
7139 ** file path */
7140 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7141 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7142 }else{
7143 /* all other styles use the locking context to store the db file path */
7144 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007145 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007146 }
7147 return SQLITE_OK;
7148}
7149
7150/*
7151** Takes an already filled in unix file and alters it so all file locking
7152** will be performed on the local proxy lock file. The following fields
7153** are preserved in the locking context so that they can be restored and
7154** the unix structure properly cleaned up at close time:
7155** ->lockingContext
7156** ->pMethod
7157*/
7158static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7159 proxyLockingContext *pCtx;
7160 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7161 char *lockPath=NULL;
7162 int rc = SQLITE_OK;
7163
drh308c2a52010-05-14 11:30:18 +00007164 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007165 return SQLITE_BUSY;
7166 }
7167 proxyGetDbPathForUnixFile(pFile, dbPath);
7168 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7169 lockPath=NULL;
7170 }else{
7171 lockPath=(char *)path;
7172 }
7173
drh308c2a52010-05-14 11:30:18 +00007174 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007175 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007176
7177 pCtx = sqlite3_malloc( sizeof(*pCtx) );
7178 if( pCtx==0 ){
7179 return SQLITE_NOMEM;
7180 }
7181 memset(pCtx, 0, sizeof(*pCtx));
7182
7183 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7184 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007185 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7186 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7187 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7188 ** (c) the file system is read-only, then enable no-locking access.
7189 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7190 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7191 */
7192 struct statfs fsInfo;
7193 struct stat conchInfo;
7194 int goLockless = 0;
7195
drh99ab3b12011-03-02 15:09:07 +00007196 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007197 int err = errno;
7198 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7199 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7200 }
7201 }
7202 if( goLockless ){
7203 pCtx->conchHeld = -1; /* read only FS/ lockless */
7204 rc = SQLITE_OK;
7205 }
7206 }
drh715ff302008-12-03 22:32:44 +00007207 }
7208 if( rc==SQLITE_OK && lockPath ){
7209 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7210 }
7211
7212 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007213 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7214 if( pCtx->dbPath==NULL ){
7215 rc = SQLITE_NOMEM;
7216 }
7217 }
7218 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007219 /* all memory is allocated, proxys are created and assigned,
7220 ** switch the locking context and pMethod then return.
7221 */
drh715ff302008-12-03 22:32:44 +00007222 pCtx->oldLockingContext = pFile->lockingContext;
7223 pFile->lockingContext = pCtx;
7224 pCtx->pOldMethod = pFile->pMethod;
7225 pFile->pMethod = &proxyIoMethods;
7226 }else{
7227 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007228 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007229 sqlite3_free(pCtx->conchFile);
7230 }
drhd56b1212010-08-11 06:14:15 +00007231 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007232 sqlite3_free(pCtx->conchFilePath);
7233 sqlite3_free(pCtx);
7234 }
drh308c2a52010-05-14 11:30:18 +00007235 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7236 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007237 return rc;
7238}
7239
7240
7241/*
7242** This routine handles sqlite3_file_control() calls that are specific
7243** to proxy locking.
7244*/
7245static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7246 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007247 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007248 unixFile *pFile = (unixFile*)id;
7249 if( pFile->pMethod == &proxyIoMethods ){
7250 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7251 proxyTakeConch(pFile);
7252 if( pCtx->lockProxyPath ){
7253 *(const char **)pArg = pCtx->lockProxyPath;
7254 }else{
7255 *(const char **)pArg = ":auto: (not held)";
7256 }
7257 } else {
7258 *(const char **)pArg = NULL;
7259 }
7260 return SQLITE_OK;
7261 }
drh4bf66fd2015-02-19 02:43:02 +00007262 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007263 unixFile *pFile = (unixFile*)id;
7264 int rc = SQLITE_OK;
7265 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7266 if( pArg==NULL || (const char *)pArg==0 ){
7267 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007268 /* turn off proxy locking - not supported. If support is added for
7269 ** switching proxy locking mode off then it will need to fail if
7270 ** the journal mode is WAL mode.
7271 */
drh715ff302008-12-03 22:32:44 +00007272 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7273 }else{
7274 /* turn off proxy locking - already off - NOOP */
7275 rc = SQLITE_OK;
7276 }
7277 }else{
7278 const char *proxyPath = (const char *)pArg;
7279 if( isProxyStyle ){
7280 proxyLockingContext *pCtx =
7281 (proxyLockingContext*)pFile->lockingContext;
7282 if( !strcmp(pArg, ":auto:")
7283 || (pCtx->lockProxyPath &&
7284 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7285 ){
7286 rc = SQLITE_OK;
7287 }else{
7288 rc = switchLockProxyPath(pFile, proxyPath);
7289 }
7290 }else{
7291 /* turn on proxy file locking */
7292 rc = proxyTransformUnixFile(pFile, proxyPath);
7293 }
7294 }
7295 return rc;
7296 }
7297 default: {
7298 assert( 0 ); /* The call assures that only valid opcodes are sent */
7299 }
7300 }
7301 /*NOTREACHED*/
7302 return SQLITE_ERROR;
7303}
7304
7305/*
7306** Within this division (the proxying locking implementation) the procedures
7307** above this point are all utilities. The lock-related methods of the
7308** proxy-locking sqlite3_io_method object follow.
7309*/
7310
7311
7312/*
7313** This routine checks if there is a RESERVED lock held on the specified
7314** file by this or any other process. If such a lock is held, set *pResOut
7315** to a non-zero value otherwise *pResOut is set to zero. The return value
7316** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7317*/
7318static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7319 unixFile *pFile = (unixFile*)id;
7320 int rc = proxyTakeConch(pFile);
7321 if( rc==SQLITE_OK ){
7322 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007323 if( pCtx->conchHeld>0 ){
7324 unixFile *proxy = pCtx->lockProxy;
7325 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7326 }else{ /* conchHeld < 0 is lockless */
7327 pResOut=0;
7328 }
drh715ff302008-12-03 22:32:44 +00007329 }
7330 return rc;
7331}
7332
7333/*
drh308c2a52010-05-14 11:30:18 +00007334** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007335** of the following:
7336**
7337** (1) SHARED_LOCK
7338** (2) RESERVED_LOCK
7339** (3) PENDING_LOCK
7340** (4) EXCLUSIVE_LOCK
7341**
7342** Sometimes when requesting one lock state, additional lock states
7343** are inserted in between. The locking might fail on one of the later
7344** transitions leaving the lock state different from what it started but
7345** still short of its goal. The following chart shows the allowed
7346** transitions and the inserted intermediate states:
7347**
7348** UNLOCKED -> SHARED
7349** SHARED -> RESERVED
7350** SHARED -> (PENDING) -> EXCLUSIVE
7351** RESERVED -> (PENDING) -> EXCLUSIVE
7352** PENDING -> EXCLUSIVE
7353**
7354** This routine will only increase a lock. Use the sqlite3OsUnlock()
7355** routine to lower a locking level.
7356*/
drh308c2a52010-05-14 11:30:18 +00007357static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007358 unixFile *pFile = (unixFile*)id;
7359 int rc = proxyTakeConch(pFile);
7360 if( rc==SQLITE_OK ){
7361 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007362 if( pCtx->conchHeld>0 ){
7363 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007364 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7365 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007366 }else{
7367 /* conchHeld < 0 is lockless */
7368 }
drh715ff302008-12-03 22:32:44 +00007369 }
7370 return rc;
7371}
7372
7373
7374/*
drh308c2a52010-05-14 11:30:18 +00007375** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007376** must be either NO_LOCK or SHARED_LOCK.
7377**
7378** If the locking level of the file descriptor is already at or below
7379** the requested locking level, this routine is a no-op.
7380*/
drh308c2a52010-05-14 11:30:18 +00007381static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007382 unixFile *pFile = (unixFile*)id;
7383 int rc = proxyTakeConch(pFile);
7384 if( rc==SQLITE_OK ){
7385 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007386 if( pCtx->conchHeld>0 ){
7387 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007388 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7389 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007390 }else{
7391 /* conchHeld < 0 is lockless */
7392 }
drh715ff302008-12-03 22:32:44 +00007393 }
7394 return rc;
7395}
7396
7397/*
7398** Close a file that uses proxy locks.
7399*/
7400static int proxyClose(sqlite3_file *id) {
7401 if( id ){
7402 unixFile *pFile = (unixFile*)id;
7403 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7404 unixFile *lockProxy = pCtx->lockProxy;
7405 unixFile *conchFile = pCtx->conchFile;
7406 int rc = SQLITE_OK;
7407
7408 if( lockProxy ){
7409 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7410 if( rc ) return rc;
7411 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7412 if( rc ) return rc;
7413 sqlite3_free(lockProxy);
7414 pCtx->lockProxy = 0;
7415 }
7416 if( conchFile ){
7417 if( pCtx->conchHeld ){
7418 rc = proxyReleaseConch(pFile);
7419 if( rc ) return rc;
7420 }
7421 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7422 if( rc ) return rc;
7423 sqlite3_free(conchFile);
7424 }
drhd56b1212010-08-11 06:14:15 +00007425 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007426 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007427 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007428 /* restore the original locking context and pMethod then close it */
7429 pFile->lockingContext = pCtx->oldLockingContext;
7430 pFile->pMethod = pCtx->pOldMethod;
7431 sqlite3_free(pCtx);
7432 return pFile->pMethod->xClose(id);
7433 }
7434 return SQLITE_OK;
7435}
7436
7437
7438
drhd2cb50b2009-01-09 21:41:17 +00007439#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007440/*
7441** The proxy locking style is intended for use with AFP filesystems.
7442** And since AFP is only supported on MacOSX, the proxy locking is also
7443** restricted to MacOSX.
7444**
7445**
7446******************* End of the proxy lock implementation **********************
7447******************************************************************************/
7448
drh734c9862008-11-28 15:37:20 +00007449/*
danielk1977e339d652008-06-28 11:23:00 +00007450** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007451**
7452** This routine registers all VFS implementations for unix-like operating
7453** systems. This routine, and the sqlite3_os_end() routine that follows,
7454** should be the only routines in this file that are visible from other
7455** files.
drh6b9d6dd2008-12-03 19:34:47 +00007456**
7457** This routine is called once during SQLite initialization and by a
7458** single thread. The memory allocation and mutex subsystems have not
7459** necessarily been initialized when this routine is called, and so they
7460** should not be used.
drh153c62c2007-08-24 03:51:33 +00007461*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007462int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007463 /*
7464 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007465 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7466 ** to the "finder" function. (pAppData is a pointer to a pointer because
7467 ** silly C90 rules prohibit a void* from being cast to a function pointer
7468 ** and so we have to go through the intermediate pointer to avoid problems
7469 ** when compiling with -pedantic-errors on GCC.)
7470 **
7471 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007472 ** finder-function. The finder-function returns a pointer to the
7473 ** sqlite_io_methods object that implements the desired locking
7474 ** behaviors. See the division above that contains the IOMETHODS
7475 ** macro for addition information on finder-functions.
7476 **
7477 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7478 ** object. But the "autolockIoFinder" available on MacOSX does a little
7479 ** more than that; it looks at the filesystem type that hosts the
7480 ** database file and tries to choose an locking method appropriate for
7481 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007482 */
drh7708e972008-11-29 00:56:52 +00007483 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007484 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007485 sizeof(unixFile), /* szOsFile */ \
7486 MAX_PATHNAME, /* mxPathname */ \
7487 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007488 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007489 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007490 unixOpen, /* xOpen */ \
7491 unixDelete, /* xDelete */ \
7492 unixAccess, /* xAccess */ \
7493 unixFullPathname, /* xFullPathname */ \
7494 unixDlOpen, /* xDlOpen */ \
7495 unixDlError, /* xDlError */ \
7496 unixDlSym, /* xDlSym */ \
7497 unixDlClose, /* xDlClose */ \
7498 unixRandomness, /* xRandomness */ \
7499 unixSleep, /* xSleep */ \
7500 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007501 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007502 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007503 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007504 unixGetSystemCall, /* xGetSystemCall */ \
7505 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007506 }
7507
drh6b9d6dd2008-12-03 19:34:47 +00007508 /*
7509 ** All default VFSes for unix are contained in the following array.
7510 **
7511 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7512 ** by the SQLite core when the VFS is registered. So the following
7513 ** array cannot be const.
7514 */
danielk1977e339d652008-06-28 11:23:00 +00007515 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007516#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007517 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007518#elif OS_VXWORKS
7519 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007520#else
7521 UNIXVFS("unix", posixIoFinder ),
7522#endif
7523 UNIXVFS("unix-none", nolockIoFinder ),
7524 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007525 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007526#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007527 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007528#endif
drhe89b2912015-03-03 20:42:01 +00007529#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007530 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007531#endif
drhe89b2912015-03-03 20:42:01 +00007532#if SQLITE_ENABLE_LOCKING_STYLE
7533 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007534#endif
drhd2cb50b2009-01-09 21:41:17 +00007535#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007536 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007537 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007538 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007539#endif
drh153c62c2007-08-24 03:51:33 +00007540 };
drh6b9d6dd2008-12-03 19:34:47 +00007541 unsigned int i; /* Loop counter */
7542
drh2aa5a002011-04-13 13:42:25 +00007543 /* Double-check that the aSyscall[] array has been constructed
7544 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007545 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007546
drh6b9d6dd2008-12-03 19:34:47 +00007547 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007548 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007549 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007550 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007551 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007552}
danielk1977e339d652008-06-28 11:23:00 +00007553
7554/*
drh6b9d6dd2008-12-03 19:34:47 +00007555** Shutdown the operating system interface.
7556**
7557** Some operating systems might need to do some cleanup in this routine,
7558** to release dynamically allocated objects. But not on unix.
7559** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007560*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007561int sqlite3_os_end(void){
7562 return SQLITE_OK;
7563}
drhdce8bdb2007-08-16 13:01:44 +00007564
danielk197729bafea2008-06-26 10:41:19 +00007565#endif /* SQLITE_OS_UNIX */