blob: 53a4fd31bd84960ab3da2ac455665ac992eb12cb [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){
mistachkin93de6532015-07-03 21:38:09 +0000632 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000633}
634static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000635 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000636}
dan9359c7b2009-08-21 08:29:10 +0000637#ifdef SQLITE_DEBUG
638static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000639 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000640}
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);
drhf3cdcdc2015-04-29 16:50:28 +0000907 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000908 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 ){
drhf3cdcdc2015-04-29 16:50:28 +00001311 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001312 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 );
drh58024642011-11-07 18:16:00 +00003149 do{
drh734c9862008-11-28 15:37:20 +00003150#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003151 got = osPread(id->h, pBuf, cnt, offset);
3152 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003153#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003154 got = osPread64(id->h, pBuf, cnt, offset);
3155 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003156#else
drh58024642011-11-07 18:16:00 +00003157 newOffset = lseek(id->h, offset, SEEK_SET);
3158 SimulateIOError( newOffset-- );
3159 if( newOffset!=offset ){
3160 if( newOffset == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00003161 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003162 }else{
drh4bf66fd2015-02-19 02:43:02 +00003163 storeLastErrno((unixFile*)id, 0);
drh58024642011-11-07 18:16:00 +00003164 }
3165 return -1;
drh734c9862008-11-28 15:37:20 +00003166 }
drh58024642011-11-07 18:16:00 +00003167 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003168#endif
drh58024642011-11-07 18:16:00 +00003169 if( got==cnt ) break;
3170 if( got<0 ){
3171 if( errno==EINTR ){ got = 1; continue; }
3172 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003173 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003174 break;
3175 }else if( got>0 ){
3176 cnt -= got;
3177 offset += got;
3178 prior += got;
3179 pBuf = (void*)(got + (char*)pBuf);
3180 }
3181 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003182 TIMER_END;
drh58024642011-11-07 18:16:00 +00003183 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3184 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3185 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003186}
3187
3188/*
drh734c9862008-11-28 15:37:20 +00003189** Read data from a file into a buffer. Return SQLITE_OK if all
3190** bytes were read successfully and SQLITE_IOERR if anything goes
3191** wrong.
drh339eb0b2008-03-07 15:34:11 +00003192*/
drh734c9862008-11-28 15:37:20 +00003193static int unixRead(
3194 sqlite3_file *id,
3195 void *pBuf,
3196 int amt,
3197 sqlite3_int64 offset
3198){
dan08da86a2009-08-21 17:18:03 +00003199 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003200 int got;
3201 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003202 assert( offset>=0 );
3203 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003204
dan08da86a2009-08-21 17:18:03 +00003205 /* If this is a database file (not a journal, master-journal or temp
3206 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003207#if 0
dane946c392009-08-22 11:39:46 +00003208 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003209 || offset>=PENDING_BYTE+512
3210 || offset+amt<=PENDING_BYTE
3211 );
dan7c246102010-04-12 19:00:29 +00003212#endif
drh08c6d442009-02-09 17:34:07 +00003213
drh9b4c59f2013-04-15 17:03:42 +00003214#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003215 /* Deal with as much of this read request as possible by transfering
3216 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003217 if( offset<pFile->mmapSize ){
3218 if( offset+amt <= pFile->mmapSize ){
3219 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3220 return SQLITE_OK;
3221 }else{
3222 int nCopy = pFile->mmapSize - offset;
3223 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3224 pBuf = &((u8 *)pBuf)[nCopy];
3225 amt -= nCopy;
3226 offset += nCopy;
3227 }
3228 }
drh6e0b6d52013-04-09 16:19:20 +00003229#endif
danf23da962013-03-23 21:00:41 +00003230
dan08da86a2009-08-21 17:18:03 +00003231 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003232 if( got==amt ){
3233 return SQLITE_OK;
3234 }else if( got<0 ){
3235 /* lastErrno set by seekAndRead */
3236 return SQLITE_IOERR_READ;
3237 }else{
drh4bf66fd2015-02-19 02:43:02 +00003238 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003239 /* Unread parts of the buffer must be zero-filled */
3240 memset(&((char*)pBuf)[got], 0, amt-got);
3241 return SQLITE_IOERR_SHORT_READ;
3242 }
3243}
3244
3245/*
dan47a2b4a2013-04-26 16:09:29 +00003246** Attempt to seek the file-descriptor passed as the first argument to
3247** absolute offset iOff, then attempt to write nBuf bytes of data from
3248** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3249** return the actual number of bytes written (which may be less than
3250** nBuf).
3251*/
3252static int seekAndWriteFd(
3253 int fd, /* File descriptor to write to */
3254 i64 iOff, /* File offset to begin writing at */
3255 const void *pBuf, /* Copy data from this buffer to the file */
3256 int nBuf, /* Size of buffer pBuf in bytes */
3257 int *piErrno /* OUT: Error number if error occurs */
3258){
3259 int rc = 0; /* Value returned by system call */
3260
3261 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003262 assert( fd>2 );
dan47a2b4a2013-04-26 16:09:29 +00003263 nBuf &= 0x1ffff;
3264 TIMER_START;
3265
3266#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003267 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003268#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003269 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003270#else
3271 do{
3272 i64 iSeek = lseek(fd, iOff, SEEK_SET);
3273 SimulateIOError( iSeek-- );
3274
3275 if( iSeek!=iOff ){
3276 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
3277 return -1;
3278 }
3279 rc = osWrite(fd, pBuf, nBuf);
3280 }while( rc<0 && errno==EINTR );
3281#endif
3282
3283 TIMER_END;
3284 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3285
3286 if( rc<0 && piErrno ) *piErrno = errno;
3287 return rc;
3288}
3289
3290
3291/*
drh734c9862008-11-28 15:37:20 +00003292** Seek to the offset in id->offset then read cnt bytes into pBuf.
3293** Return the number of bytes actually read. Update the offset.
3294**
3295** To avoid stomping the errno value on a failed write the lastErrno value
3296** is set before returning.
3297*/
3298static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003299 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003300}
3301
3302
3303/*
3304** Write data from a buffer into a file. Return SQLITE_OK on success
3305** or some other error code on failure.
3306*/
3307static int unixWrite(
3308 sqlite3_file *id,
3309 const void *pBuf,
3310 int amt,
3311 sqlite3_int64 offset
3312){
dan08da86a2009-08-21 17:18:03 +00003313 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003314 int wrote = 0;
3315 assert( id );
3316 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003317
dan08da86a2009-08-21 17:18:03 +00003318 /* If this is a database file (not a journal, master-journal or temp
3319 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003320#if 0
dane946c392009-08-22 11:39:46 +00003321 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003322 || offset>=PENDING_BYTE+512
3323 || offset+amt<=PENDING_BYTE
3324 );
dan7c246102010-04-12 19:00:29 +00003325#endif
drh08c6d442009-02-09 17:34:07 +00003326
drhd3d8c042012-05-29 17:02:40 +00003327#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003328 /* If we are doing a normal write to a database file (as opposed to
3329 ** doing a hot-journal rollback or a write to some file other than a
3330 ** normal database file) then record the fact that the database
3331 ** has changed. If the transaction counter is modified, record that
3332 ** fact too.
3333 */
dan08da86a2009-08-21 17:18:03 +00003334 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003335 pFile->dbUpdate = 1; /* The database has been modified */
3336 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003337 int rc;
drh8f941bc2009-01-14 23:03:40 +00003338 char oldCntr[4];
3339 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003340 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003341 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003342 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003343 pFile->transCntrChng = 1; /* The transaction counter has changed */
3344 }
3345 }
3346 }
3347#endif
3348
drh9b4c59f2013-04-15 17:03:42 +00003349#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003350 /* Deal with as much of this write request as possible by transfering
3351 ** data from the memory mapping using memcpy(). */
3352 if( offset<pFile->mmapSize ){
3353 if( offset+amt <= pFile->mmapSize ){
3354 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3355 return SQLITE_OK;
3356 }else{
3357 int nCopy = pFile->mmapSize - offset;
3358 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3359 pBuf = &((u8 *)pBuf)[nCopy];
3360 amt -= nCopy;
3361 offset += nCopy;
3362 }
3363 }
drh6e0b6d52013-04-09 16:19:20 +00003364#endif
drh02bf8b42015-09-01 23:51:53 +00003365
3366 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003367 amt -= wrote;
3368 offset += wrote;
3369 pBuf = &((char*)pBuf)[wrote];
3370 }
3371 SimulateIOError(( wrote=(-1), amt=1 ));
3372 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003373
drh02bf8b42015-09-01 23:51:53 +00003374 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003375 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003376 /* lastErrno set by seekAndWrite */
3377 return SQLITE_IOERR_WRITE;
3378 }else{
drh4bf66fd2015-02-19 02:43:02 +00003379 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003380 return SQLITE_FULL;
3381 }
3382 }
dan6e09d692010-07-27 18:34:15 +00003383
drh734c9862008-11-28 15:37:20 +00003384 return SQLITE_OK;
3385}
3386
3387#ifdef SQLITE_TEST
3388/*
3389** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003390** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003391*/
3392int sqlite3_sync_count = 0;
3393int sqlite3_fullsync_count = 0;
3394#endif
3395
3396/*
drh89240432009-03-25 01:06:01 +00003397** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003398** Others do no. To be safe, we will stick with the (slightly slower)
3399** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003400** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003401*/
drhf7a4a1b2015-01-10 18:02:45 +00003402#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003403# define fdatasync fsync
3404#endif
3405
3406/*
3407** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3408** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3409** only available on Mac OS X. But that could change.
3410*/
3411#ifdef F_FULLFSYNC
3412# define HAVE_FULLFSYNC 1
3413#else
3414# define HAVE_FULLFSYNC 0
3415#endif
3416
3417
3418/*
3419** The fsync() system call does not work as advertised on many
3420** unix systems. The following procedure is an attempt to make
3421** it work better.
3422**
3423** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3424** for testing when we want to run through the test suite quickly.
3425** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3426** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3427** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003428**
3429** SQLite sets the dataOnly flag if the size of the file is unchanged.
3430** The idea behind dataOnly is that it should only write the file content
3431** to disk, not the inode. We only set dataOnly if the file size is
3432** unchanged since the file size is part of the inode. However,
3433** Ted Ts'o tells us that fdatasync() will also write the inode if the
3434** file size has changed. The only real difference between fdatasync()
3435** and fsync(), Ted tells us, is that fdatasync() will not flush the
3436** inode if the mtime or owner or other inode attributes have changed.
3437** We only care about the file size, not the other file attributes, so
3438** as far as SQLite is concerned, an fdatasync() is always adequate.
3439** So, we always use fdatasync() if it is available, regardless of
3440** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003441*/
3442static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003443 int rc;
drh734c9862008-11-28 15:37:20 +00003444
3445 /* The following "ifdef/elif/else/" block has the same structure as
3446 ** the one below. It is replicated here solely to avoid cluttering
3447 ** up the real code with the UNUSED_PARAMETER() macros.
3448 */
3449#ifdef SQLITE_NO_SYNC
3450 UNUSED_PARAMETER(fd);
3451 UNUSED_PARAMETER(fullSync);
3452 UNUSED_PARAMETER(dataOnly);
3453#elif HAVE_FULLFSYNC
3454 UNUSED_PARAMETER(dataOnly);
3455#else
3456 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003457 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003458#endif
3459
3460 /* Record the number of times that we do a normal fsync() and
3461 ** FULLSYNC. This is used during testing to verify that this procedure
3462 ** gets called with the correct arguments.
3463 */
3464#ifdef SQLITE_TEST
3465 if( fullSync ) sqlite3_fullsync_count++;
3466 sqlite3_sync_count++;
3467#endif
3468
3469 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
3470 ** no-op
3471 */
3472#ifdef SQLITE_NO_SYNC
3473 rc = SQLITE_OK;
3474#elif HAVE_FULLFSYNC
3475 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003476 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003477 }else{
3478 rc = 1;
3479 }
3480 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003481 ** It shouldn't be possible for fullfsync to fail on the local
3482 ** file system (on OSX), so failure indicates that FULLFSYNC
3483 ** isn't supported for this file system. So, attempt an fsync
3484 ** and (for now) ignore the overhead of a superfluous fcntl call.
3485 ** It'd be better to detect fullfsync support once and avoid
3486 ** the fcntl call every time sync is called.
3487 */
drh734c9862008-11-28 15:37:20 +00003488 if( rc ) rc = fsync(fd);
3489
drh7ed97b92010-01-20 13:07:21 +00003490#elif defined(__APPLE__)
3491 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3492 ** so currently we default to the macro that redefines fdatasync to fsync
3493 */
3494 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003495#else
drh0b647ff2009-03-21 14:41:04 +00003496 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003497#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003498 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003499 rc = fsync(fd);
3500 }
drh0b647ff2009-03-21 14:41:04 +00003501#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003502#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3503
3504 if( OS_VXWORKS && rc!= -1 ){
3505 rc = 0;
3506 }
chw97185482008-11-17 08:05:31 +00003507 return rc;
drhbfe66312006-10-03 17:40:40 +00003508}
3509
drh734c9862008-11-28 15:37:20 +00003510/*
drh0059eae2011-08-08 23:48:40 +00003511** Open a file descriptor to the directory containing file zFilename.
3512** If successful, *pFd is set to the opened file descriptor and
3513** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3514** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3515** value.
3516**
drh90315a22011-08-10 01:52:12 +00003517** The directory file descriptor is used for only one thing - to
3518** fsync() a directory to make sure file creation and deletion events
3519** are flushed to disk. Such fsyncs are not needed on newer
3520** journaling filesystems, but are required on older filesystems.
3521**
3522** This routine can be overridden using the xSetSysCall interface.
3523** The ability to override this routine was added in support of the
3524** chromium sandbox. Opening a directory is a security risk (we are
3525** told) so making it overrideable allows the chromium sandbox to
3526** replace this routine with a harmless no-op. To make this routine
3527** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3528** *pFd set to a negative number.
3529**
drh0059eae2011-08-08 23:48:40 +00003530** If SQLITE_OK is returned, the caller is responsible for closing
3531** the file descriptor *pFd using close().
3532*/
3533static int openDirectory(const char *zFilename, int *pFd){
3534 int ii;
3535 int fd = -1;
3536 char zDirname[MAX_PATHNAME+1];
3537
3538 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3539 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3540 if( ii>0 ){
3541 zDirname[ii] = '\0';
3542 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3543 if( fd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003544 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3545 }
3546 }
3547 *pFd = fd;
3548 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
3549}
3550
3551/*
drh734c9862008-11-28 15:37:20 +00003552** Make sure all writes to a particular file are committed to disk.
3553**
3554** If dataOnly==0 then both the file itself and its metadata (file
3555** size, access time, etc) are synced. If dataOnly!=0 then only the
3556** file data is synced.
3557**
3558** Under Unix, also make sure that the directory entry for the file
3559** has been created by fsync-ing the directory that contains the file.
3560** If we do not do this and we encounter a power failure, the directory
3561** entry for the journal might not exist after we reboot. The next
3562** SQLite to access the file will not know that the journal exists (because
3563** the directory entry for the journal was never created) and the transaction
3564** will not roll back - possibly leading to database corruption.
3565*/
3566static int unixSync(sqlite3_file *id, int flags){
3567 int rc;
3568 unixFile *pFile = (unixFile*)id;
3569
3570 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3571 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3572
3573 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3574 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3575 || (flags&0x0F)==SQLITE_SYNC_FULL
3576 );
3577
3578 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3579 ** line is to test that doing so does not cause any problems.
3580 */
3581 SimulateDiskfullError( return SQLITE_FULL );
3582
3583 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003584 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003585 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3586 SimulateIOError( rc=1 );
3587 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003588 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003589 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003590 }
drh0059eae2011-08-08 23:48:40 +00003591
3592 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003593 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003594 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003595 */
3596 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3597 int dirfd;
3598 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003599 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003600 rc = osOpenDirectory(pFile->zPath, &dirfd);
3601 if( rc==SQLITE_OK && dirfd>=0 ){
drh0059eae2011-08-08 23:48:40 +00003602 full_fsync(dirfd, 0, 0);
3603 robust_close(pFile, dirfd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00003604 }else if( rc==SQLITE_CANTOPEN ){
3605 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003606 }
drh0059eae2011-08-08 23:48:40 +00003607 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003608 }
3609 return rc;
3610}
3611
3612/*
3613** Truncate an open file to a specified size
3614*/
3615static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003616 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003617 int rc;
dan6e09d692010-07-27 18:34:15 +00003618 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003619 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003620
3621 /* If the user has configured a chunk-size for this file, truncate the
3622 ** file so that it consists of an integer number of chunks (i.e. the
3623 ** actual file size after the operation may be larger than the requested
3624 ** size).
3625 */
drhb8af4b72012-04-05 20:04:39 +00003626 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003627 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3628 }
3629
dan2ee53412014-09-06 16:49:40 +00003630 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003631 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003632 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003633 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003634 }else{
drhd3d8c042012-05-29 17:02:40 +00003635#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003636 /* If we are doing a normal write to a database file (as opposed to
3637 ** doing a hot-journal rollback or a write to some file other than a
3638 ** normal database file) and we truncate the file to zero length,
3639 ** that effectively updates the change counter. This might happen
3640 ** when restoring a database using the backup API from a zero-length
3641 ** source.
3642 */
dan6e09d692010-07-27 18:34:15 +00003643 if( pFile->inNormalWrite && nByte==0 ){
3644 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003645 }
danf23da962013-03-23 21:00:41 +00003646#endif
danc0003312013-03-22 17:46:11 +00003647
mistachkine98844f2013-08-24 00:59:24 +00003648#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003649 /* If the file was just truncated to a size smaller than the currently
3650 ** mapped region, reduce the effective mapping size as well. SQLite will
3651 ** use read() and write() to access data beyond this point from now on.
3652 */
3653 if( nByte<pFile->mmapSize ){
3654 pFile->mmapSize = nByte;
3655 }
mistachkine98844f2013-08-24 00:59:24 +00003656#endif
drh3313b142009-11-06 04:13:18 +00003657
drh734c9862008-11-28 15:37:20 +00003658 return SQLITE_OK;
3659 }
3660}
3661
3662/*
3663** Determine the current size of a file in bytes
3664*/
3665static int unixFileSize(sqlite3_file *id, i64 *pSize){
3666 int rc;
3667 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003668 assert( id );
3669 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003670 SimulateIOError( rc=1 );
3671 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003672 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003673 return SQLITE_IOERR_FSTAT;
3674 }
3675 *pSize = buf.st_size;
3676
drh8af6c222010-05-14 12:43:01 +00003677 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003678 ** writes a single byte into that file in order to work around a bug
3679 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3680 ** layers, we need to report this file size as zero even though it is
3681 ** really 1. Ticket #3260.
3682 */
3683 if( *pSize==1 ) *pSize = 0;
3684
3685
3686 return SQLITE_OK;
3687}
3688
drhd2cb50b2009-01-09 21:41:17 +00003689#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003690/*
3691** Handler for proxy-locking file-control verbs. Defined below in the
3692** proxying locking division.
3693*/
3694static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003695#endif
drh715ff302008-12-03 22:32:44 +00003696
dan502019c2010-07-28 14:26:17 +00003697/*
3698** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003699** file-control operation. Enlarge the database to nBytes in size
3700** (rounded up to the next chunk-size). If the database is already
3701** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003702*/
3703static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003704 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003705 i64 nSize; /* Required file size */
3706 struct stat buf; /* Used to hold return values of fstat() */
3707
drh4bf66fd2015-02-19 02:43:02 +00003708 if( osFstat(pFile->h, &buf) ){
3709 return SQLITE_IOERR_FSTAT;
3710 }
dan502019c2010-07-28 14:26:17 +00003711
3712 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3713 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003714
dan502019c2010-07-28 14:26:17 +00003715#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003716 /* The code below is handling the return value of osFallocate()
3717 ** correctly. posix_fallocate() is defined to "returns zero on success,
3718 ** or an error number on failure". See the manpage for details. */
3719 int err;
drhff812312011-02-23 13:33:46 +00003720 do{
dan661d71a2011-03-30 19:08:03 +00003721 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3722 }while( err==EINTR );
3723 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003724#else
dan592bf7f2014-12-30 19:58:31 +00003725 /* If the OS does not have posix_fallocate(), fake it. Write a
3726 ** single byte to the last byte in each block that falls entirely
3727 ** within the extended region. Then, if required, a single byte
3728 ** at offset (nSize-1), to set the size of the file correctly.
3729 ** This is a similar technique to that used by glibc on systems
3730 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003731 */
3732 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003733 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003734 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003735
dan502019c2010-07-28 14:26:17 +00003736 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
dan592bf7f2014-12-30 19:58:31 +00003737 assert( iWrite>=buf.st_size );
3738 assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
3739 assert( ((iWrite+1)%nBlk)==0 );
3740 for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
danef3d66c2015-01-06 21:31:47 +00003741 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003742 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003743 }
danef3d66c2015-01-06 21:31:47 +00003744 if( nWrite==0 || (nSize%nBlk) ){
3745 nWrite = seekAndWrite(pFile, nSize-1, "", 1);
dan592bf7f2014-12-30 19:58:31 +00003746 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dand348c662014-12-30 14:40:53 +00003747 }
dan502019c2010-07-28 14:26:17 +00003748#endif
3749 }
3750 }
3751
mistachkine98844f2013-08-24 00:59:24 +00003752#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003753 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003754 int rc;
3755 if( pFile->szChunk<=0 ){
3756 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003757 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003758 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3759 }
3760 }
3761
3762 rc = unixMapfile(pFile, nByte);
3763 return rc;
3764 }
mistachkine98844f2013-08-24 00:59:24 +00003765#endif
danf23da962013-03-23 21:00:41 +00003766
dan502019c2010-07-28 14:26:17 +00003767 return SQLITE_OK;
3768}
danielk1977ad94b582007-08-20 06:44:22 +00003769
danielk1977e3026632004-06-22 11:29:02 +00003770/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003771** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003772** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3773**
3774** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3775*/
3776static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3777 if( *pArg<0 ){
3778 *pArg = (pFile->ctrlFlags & mask)!=0;
3779 }else if( (*pArg)==0 ){
3780 pFile->ctrlFlags &= ~mask;
3781 }else{
3782 pFile->ctrlFlags |= mask;
3783 }
3784}
3785
drh696b33e2012-12-06 19:01:42 +00003786/* Forward declaration */
3787static int unixGetTempname(int nBuf, char *zBuf);
3788
drhf12b3f62011-12-21 14:42:29 +00003789/*
drh9e33c2c2007-08-31 18:34:59 +00003790** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003791*/
drhcc6bb3e2007-08-31 16:11:35 +00003792static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003793 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003794 switch( op ){
drhc435cf72015-03-21 16:36:03 +00003795 case SQLITE_FCNTL_WAL_BLOCK: {
drh62ca61e2015-04-03 20:33:33 +00003796 /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
drhc435cf72015-03-21 16:36:03 +00003797 return SQLITE_OK;
3798 }
drh9e33c2c2007-08-31 18:34:59 +00003799 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003800 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003801 return SQLITE_OK;
3802 }
drh4bf66fd2015-02-19 02:43:02 +00003803 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003804 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003805 return SQLITE_OK;
3806 }
dan6e09d692010-07-27 18:34:15 +00003807 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003808 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003809 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003810 }
drh9ff27ec2010-05-19 19:26:05 +00003811 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003812 int rc;
3813 SimulateIOErrorBenign(1);
3814 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3815 SimulateIOErrorBenign(0);
3816 return rc;
drhf0b190d2011-07-26 16:03:07 +00003817 }
3818 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003819 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3820 return SQLITE_OK;
3821 }
drhcb15f352011-12-23 01:04:17 +00003822 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3823 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003824 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003825 }
drhde60fc22011-12-14 17:53:36 +00003826 case SQLITE_FCNTL_VFSNAME: {
3827 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3828 return SQLITE_OK;
3829 }
drh696b33e2012-12-06 19:01:42 +00003830 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003831 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003832 if( zTFile ){
3833 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3834 *(char**)pArg = zTFile;
3835 }
3836 return SQLITE_OK;
3837 }
drhb959a012013-12-07 12:29:22 +00003838 case SQLITE_FCNTL_HAS_MOVED: {
3839 *(int*)pArg = fileHasMoved(pFile);
3840 return SQLITE_OK;
3841 }
mistachkine98844f2013-08-24 00:59:24 +00003842#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003843 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003844 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003845 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003846 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3847 newLimit = sqlite3GlobalConfig.mxMmap;
3848 }
3849 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003850 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003851 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003852 if( pFile->mmapSize>0 ){
3853 unixUnmapfile(pFile);
3854 rc = unixMapfile(pFile, -1);
3855 }
danbcb8a862013-04-08 15:30:41 +00003856 }
drh34e258c2013-05-23 01:40:53 +00003857 return rc;
danb2d3de32013-03-14 18:34:37 +00003858 }
mistachkine98844f2013-08-24 00:59:24 +00003859#endif
drhd3d8c042012-05-29 17:02:40 +00003860#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003861 /* The pager calls this method to signal that it has done
3862 ** a rollback and that the database is therefore unchanged and
3863 ** it hence it is OK for the transaction change counter to be
3864 ** unchanged.
3865 */
3866 case SQLITE_FCNTL_DB_UNCHANGED: {
3867 ((unixFile*)id)->dbUpdate = 0;
3868 return SQLITE_OK;
3869 }
3870#endif
drhd2cb50b2009-01-09 21:41:17 +00003871#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003872 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3873 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003874 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003875 }
drhd2cb50b2009-01-09 21:41:17 +00003876#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003877 }
drh0b52b7d2011-01-26 19:46:22 +00003878 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003879}
3880
3881/*
danielk1977a3d4c882007-03-23 10:08:38 +00003882** Return the sector size in bytes of the underlying block device for
3883** the specified file. This is almost always 512 bytes, but may be
3884** larger for some devices.
3885**
3886** SQLite code assumes this function cannot fail. It also assumes that
3887** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003888** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003889** same for both.
3890*/
drh537dddf2012-10-26 13:46:24 +00003891#ifndef __QNXNTO__
3892static int unixSectorSize(sqlite3_file *NotUsed){
3893 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003894 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003895}
drh537dddf2012-10-26 13:46:24 +00003896#endif
3897
3898/*
3899** The following version of unixSectorSize() is optimized for QNX.
3900*/
3901#ifdef __QNXNTO__
3902#include <sys/dcmd_blk.h>
3903#include <sys/statvfs.h>
3904static int unixSectorSize(sqlite3_file *id){
3905 unixFile *pFile = (unixFile*)id;
3906 if( pFile->sectorSize == 0 ){
3907 struct statvfs fsInfo;
3908
3909 /* Set defaults for non-supported filesystems */
3910 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3911 pFile->deviceCharacteristics = 0;
3912 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3913 return pFile->sectorSize;
3914 }
3915
3916 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3917 pFile->sectorSize = fsInfo.f_bsize;
3918 pFile->deviceCharacteristics =
3919 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3920 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3921 ** the write succeeds */
3922 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3923 ** so it is ordered */
3924 0;
3925 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3926 pFile->sectorSize = fsInfo.f_bsize;
3927 pFile->deviceCharacteristics =
3928 /* etfs cluster size writes are atomic */
3929 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3930 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3931 ** the write succeeds */
3932 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3933 ** so it is ordered */
3934 0;
3935 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3936 pFile->sectorSize = fsInfo.f_bsize;
3937 pFile->deviceCharacteristics =
3938 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3939 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3940 ** the write succeeds */
3941 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3942 ** so it is ordered */
3943 0;
3944 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3945 pFile->sectorSize = fsInfo.f_bsize;
3946 pFile->deviceCharacteristics =
3947 /* full bitset of atomics from max sector size and smaller */
3948 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3949 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3950 ** so it is ordered */
3951 0;
3952 }else if( strstr(fsInfo.f_basetype, "dos") ){
3953 pFile->sectorSize = fsInfo.f_bsize;
3954 pFile->deviceCharacteristics =
3955 /* full bitset of atomics from max sector size and smaller */
3956 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3957 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3958 ** so it is ordered */
3959 0;
3960 }else{
3961 pFile->deviceCharacteristics =
3962 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3963 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3964 ** the write succeeds */
3965 0;
3966 }
3967 }
3968 /* Last chance verification. If the sector size isn't a multiple of 512
3969 ** then it isn't valid.*/
3970 if( pFile->sectorSize % 512 != 0 ){
3971 pFile->deviceCharacteristics = 0;
3972 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3973 }
3974 return pFile->sectorSize;
3975}
3976#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003977
danielk197790949c22007-08-17 16:50:38 +00003978/*
drhf12b3f62011-12-21 14:42:29 +00003979** Return the device characteristics for the file.
3980**
drhcb15f352011-12-23 01:04:17 +00003981** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003982** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003983** file system does not always provide powersafe overwrites. (In other
3984** words, after a power-loss event, parts of the file that were never
3985** written might end up being altered.) However, non-PSOW behavior is very,
3986** very rare. And asserting PSOW makes a large reduction in the amount
3987** of required I/O for journaling, since a lot of padding is eliminated.
3988** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3989** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003990*/
drhf12b3f62011-12-21 14:42:29 +00003991static int unixDeviceCharacteristics(sqlite3_file *id){
3992 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003993 int rc = 0;
3994#ifdef __QNXNTO__
3995 if( p->sectorSize==0 ) unixSectorSize(id);
3996 rc = p->deviceCharacteristics;
3997#endif
drhcb15f352011-12-23 01:04:17 +00003998 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003999 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00004000 }
drh537dddf2012-10-26 13:46:24 +00004001 return rc;
danielk197762079062007-08-15 17:08:46 +00004002}
4003
dan702eec12014-06-23 10:04:58 +00004004#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004005
dan702eec12014-06-23 10:04:58 +00004006/*
4007** Return the system page size.
4008**
4009** This function should not be called directly by other code in this file.
4010** Instead, it should be called via macro osGetpagesize().
4011*/
4012static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004013#if OS_VXWORKS
4014 return 1024;
4015#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004016 return getpagesize();
4017#else
4018 return (int)sysconf(_SC_PAGESIZE);
4019#endif
4020}
4021
4022#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4023
4024#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004025
4026/*
drhd91c68f2010-05-14 14:52:25 +00004027** Object used to represent an shared memory buffer.
4028**
4029** When multiple threads all reference the same wal-index, each thread
4030** has its own unixShm object, but they all point to a single instance
4031** of this unixShmNode object. In other words, each wal-index is opened
4032** only once per process.
4033**
4034** Each unixShmNode object is connected to a single unixInodeInfo object.
4035** We could coalesce this object into unixInodeInfo, but that would mean
4036** every open file that does not use shared memory (in other words, most
4037** open files) would have to carry around this extra information. So
4038** the unixInodeInfo object contains a pointer to this unixShmNode object
4039** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004040**
4041** unixMutexHeld() must be true when creating or destroying
4042** this object or while reading or writing the following fields:
4043**
4044** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004045**
4046** The following fields are read-only after the object is created:
4047**
4048** fid
4049** zFilename
4050**
drhd91c68f2010-05-14 14:52:25 +00004051** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004052** unixMutexHeld() is true when reading or writing any other field
4053** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004054*/
drhd91c68f2010-05-14 14:52:25 +00004055struct unixShmNode {
4056 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004057 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004058 char *zFilename; /* Name of the mmapped file */
4059 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004060 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004061 u16 nRegion; /* Size of array apRegion */
4062 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004063 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004064 int nRef; /* Number of unixShm objects pointing to this */
4065 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004066#ifdef SQLITE_DEBUG
4067 u8 exclMask; /* Mask of exclusive locks held */
4068 u8 sharedMask; /* Mask of shared locks held */
4069 u8 nextShmId; /* Next available unixShm.id value */
4070#endif
4071};
4072
4073/*
drhd9e5c4f2010-05-12 18:01:39 +00004074** Structure used internally by this VFS to record the state of an
4075** open shared memory connection.
4076**
drhd91c68f2010-05-14 14:52:25 +00004077** The following fields are initialized when this object is created and
4078** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004079**
drhd91c68f2010-05-14 14:52:25 +00004080** unixShm.pFile
4081** unixShm.id
4082**
4083** All other fields are read/write. The unixShm.pFile->mutex must be held
4084** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004085*/
4086struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004087 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4088 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004089 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004090 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004091 u16 sharedMask; /* Mask of shared locks held */
4092 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004093};
4094
4095/*
drhd9e5c4f2010-05-12 18:01:39 +00004096** Constants used for locking
4097*/
drhbd9676c2010-06-23 17:58:38 +00004098#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004099#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004100
drhd9e5c4f2010-05-12 18:01:39 +00004101/*
drh73b64e42010-05-30 19:55:15 +00004102** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004103**
4104** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4105** otherwise.
4106*/
4107static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004108 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004109 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004110 int ofst, /* First byte of the locking range */
4111 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004112){
drhbbf76ee2015-03-10 20:22:35 +00004113 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4114 struct flock f; /* The posix advisory locking structure */
4115 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004116
drhd91c68f2010-05-14 14:52:25 +00004117 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004118 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004119 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004120
drh73b64e42010-05-30 19:55:15 +00004121 /* Shared locks never span more than one byte */
4122 assert( n==1 || lockType!=F_RDLCK );
4123
4124 /* Locks are within range */
drhc99597c2010-05-31 01:41:15 +00004125 assert( n>=1 && n<SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004126
drh3cb93392011-03-12 18:10:44 +00004127 if( pShmNode->h>=0 ){
drhbbf76ee2015-03-10 20:22:35 +00004128 int lkType;
drh3cb93392011-03-12 18:10:44 +00004129 /* Initialize the locking parameters */
4130 memset(&f, 0, sizeof(f));
4131 f.l_type = lockType;
4132 f.l_whence = SEEK_SET;
4133 f.l_start = ofst;
4134 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004135
drhbbf76ee2015-03-10 20:22:35 +00004136 lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
4137 rc = osFcntl(pShmNode->h, lkType, &f);
drh3cb93392011-03-12 18:10:44 +00004138 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
drhbbf76ee2015-03-10 20:22:35 +00004139 pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
drh3cb93392011-03-12 18:10:44 +00004140 }
drhd9e5c4f2010-05-12 18:01:39 +00004141
4142 /* Update the global lock state and do debug tracing */
4143#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004144 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004145 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004146 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004147 if( rc==SQLITE_OK ){
4148 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004149 OSTRACE(("unlock %d ok", ofst));
4150 pShmNode->exclMask &= ~mask;
4151 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004152 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004153 OSTRACE(("read-lock %d ok", ofst));
4154 pShmNode->exclMask &= ~mask;
4155 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004156 }else{
4157 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004158 OSTRACE(("write-lock %d ok", ofst));
4159 pShmNode->exclMask |= mask;
4160 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004161 }
4162 }else{
4163 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004164 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004165 }else if( lockType==F_RDLCK ){
4166 OSTRACE(("read-lock failed"));
4167 }else{
4168 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004169 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004170 }
4171 }
drh20e1f082010-05-31 16:10:12 +00004172 OSTRACE((" - afterwards %03x,%03x\n",
4173 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004174 }
drhd9e5c4f2010-05-12 18:01:39 +00004175#endif
4176
4177 return rc;
4178}
4179
dan781e34c2014-03-20 08:59:47 +00004180/*
dan781e34c2014-03-20 08:59:47 +00004181** Return the minimum number of 32KB shm regions that should be mapped at
4182** a time, assuming that each mapping must be an integer multiple of the
4183** current system page-size.
4184**
4185** Usually, this is 1. The exception seems to be systems that are configured
4186** to use 64KB pages - in this case each mapping must cover at least two
4187** shm regions.
4188*/
4189static int unixShmRegionPerMap(void){
4190 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004191 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004192 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4193 if( pgsz<shmsz ) return 1;
4194 return pgsz/shmsz;
4195}
drhd9e5c4f2010-05-12 18:01:39 +00004196
4197/*
drhd91c68f2010-05-14 14:52:25 +00004198** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004199**
4200** This is not a VFS shared-memory method; it is a utility function called
4201** by VFS shared-memory methods.
4202*/
drhd91c68f2010-05-14 14:52:25 +00004203static void unixShmPurge(unixFile *pFd){
4204 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004205 assert( unixMutexHeld() );
drhd91c68f2010-05-14 14:52:25 +00004206 if( p && p->nRef==0 ){
dan781e34c2014-03-20 08:59:47 +00004207 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004208 int i;
drhd91c68f2010-05-14 14:52:25 +00004209 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004210 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004211 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004212 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004213 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004214 }else{
4215 sqlite3_free(p->apRegion[i]);
4216 }
dan13a3cb82010-06-11 19:04:21 +00004217 }
dan18801912010-06-14 14:07:50 +00004218 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004219 if( p->h>=0 ){
4220 robust_close(pFd, p->h, __LINE__);
4221 p->h = -1;
4222 }
drhd91c68f2010-05-14 14:52:25 +00004223 p->pInode->pShmNode = 0;
4224 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004225 }
4226}
4227
4228/*
danda9fe0c2010-07-13 18:44:03 +00004229** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004230** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004231**
drh7234c6d2010-06-19 15:10:09 +00004232** The file used to implement shared-memory is in the same directory
4233** as the open database file and has the same name as the open database
4234** file with the "-shm" suffix added. For example, if the database file
4235** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004236** for shared memory will be called "/home/user1/config.db-shm".
4237**
4238** Another approach to is to use files in /dev/shm or /dev/tmp or an
4239** some other tmpfs mount. But if a file in a different directory
4240** from the database file is used, then differing access permissions
4241** or a chroot() might cause two different processes on the same
4242** database to end up using different files for shared memory -
4243** meaning that their memory would not really be shared - resulting
4244** in database corruption. Nevertheless, this tmpfs file usage
4245** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4246** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4247** option results in an incompatible build of SQLite; builds of SQLite
4248** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4249** same database file at the same time, database corruption will likely
4250** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4251** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004252**
4253** When opening a new shared-memory file, if no other instances of that
4254** file are currently open, in this process or in other processes, then
4255** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004256**
4257** If the original database file (pDbFd) is using the "unix-excl" VFS
4258** that means that an exclusive lock is held on the database file and
4259** that no other processes are able to read or write the database. In
4260** that case, we do not really need shared memory. No shared memory
4261** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004262*/
danda9fe0c2010-07-13 18:44:03 +00004263static int unixOpenSharedMemory(unixFile *pDbFd){
4264 struct unixShm *p = 0; /* The connection to be opened */
4265 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4266 int rc; /* Result code */
4267 unixInodeInfo *pInode; /* The inode of fd */
4268 char *zShmFilename; /* Name of the file used for SHM */
4269 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004270
danda9fe0c2010-07-13 18:44:03 +00004271 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004272 p = sqlite3_malloc64( sizeof(*p) );
drhd9e5c4f2010-05-12 18:01:39 +00004273 if( p==0 ) return SQLITE_NOMEM;
4274 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004275 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004276
danda9fe0c2010-07-13 18:44:03 +00004277 /* Check to see if a unixShmNode object already exists. Reuse an existing
4278 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004279 */
4280 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004281 pInode = pDbFd->pInode;
4282 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004283 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004284 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004285#ifndef SQLITE_SHM_DIRECTORY
4286 const char *zBasePath = pDbFd->zPath;
4287#endif
danddb0ac42010-07-14 14:48:58 +00004288
4289 /* Call fstat() to figure out the permissions on the database file. If
4290 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004291 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004292 */
drh3cb93392011-03-12 18:10:44 +00004293 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
danddb0ac42010-07-14 14:48:58 +00004294 rc = SQLITE_IOERR_FSTAT;
4295 goto shm_open_err;
4296 }
4297
drha4ced192010-07-15 18:32:40 +00004298#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004299 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004300#else
drh4bf66fd2015-02-19 02:43:02 +00004301 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004302#endif
drhf3cdcdc2015-04-29 16:50:28 +00004303 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004304 if( pShmNode==0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004305 rc = SQLITE_NOMEM;
4306 goto shm_open_err;
4307 }
drh9cb5a0d2012-01-05 21:19:54 +00004308 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004309 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004310#ifdef SQLITE_SHM_DIRECTORY
4311 sqlite3_snprintf(nShmFilename, zShmFilename,
4312 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4313 (u32)sStat.st_ino, (u32)sStat.st_dev);
4314#else
drh4bf66fd2015-02-19 02:43:02 +00004315 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004316 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004317#endif
drhd91c68f2010-05-14 14:52:25 +00004318 pShmNode->h = -1;
4319 pDbFd->pInode->pShmNode = pShmNode;
4320 pShmNode->pInode = pDbFd->pInode;
4321 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4322 if( pShmNode->mutex==0 ){
4323 rc = SQLITE_NOMEM;
4324 goto shm_open_err;
4325 }
drhd9e5c4f2010-05-12 18:01:39 +00004326
drh3cb93392011-03-12 18:10:44 +00004327 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004328 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004329 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004330 openFlags = O_RDONLY;
4331 pShmNode->isReadonly = 1;
4332 }
4333 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004334 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004335 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4336 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004337 }
drhac7c3ac2012-02-11 19:23:48 +00004338
4339 /* If this process is running as root, make sure that the SHM file
4340 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004341 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004342 */
drhed466822012-05-31 13:10:49 +00004343 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004344
4345 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004346 ** If not, truncate the file to zero length.
4347 */
4348 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004349 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004350 if( robust_ftruncate(pShmNode->h, 0) ){
4351 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004352 }
4353 }
drh66dfec8b2011-06-01 20:01:49 +00004354 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004355 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004356 }
4357 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004358 }
drhd9e5c4f2010-05-12 18:01:39 +00004359 }
4360
drhd91c68f2010-05-14 14:52:25 +00004361 /* Make the new connection a child of the unixShmNode */
4362 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004363#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004364 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004365#endif
drhd91c68f2010-05-14 14:52:25 +00004366 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004367 pDbFd->pShm = p;
4368 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004369
4370 /* The reference count on pShmNode has already been incremented under
4371 ** the cover of the unixEnterMutex() mutex and the pointer from the
4372 ** new (struct unixShm) object to the pShmNode has been set. All that is
4373 ** left to do is to link the new object into the linked list starting
4374 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4375 ** mutex.
4376 */
4377 sqlite3_mutex_enter(pShmNode->mutex);
4378 p->pNext = pShmNode->pFirst;
4379 pShmNode->pFirst = p;
4380 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004381 return SQLITE_OK;
4382
4383 /* Jump here on any error */
4384shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004385 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004386 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004387 unixLeaveMutex();
4388 return rc;
4389}
4390
4391/*
danda9fe0c2010-07-13 18:44:03 +00004392** This function is called to obtain a pointer to region iRegion of the
4393** shared-memory associated with the database file fd. Shared-memory regions
4394** are numbered starting from zero. Each shared-memory region is szRegion
4395** bytes in size.
4396**
4397** If an error occurs, an error code is returned and *pp is set to NULL.
4398**
4399** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4400** region has not been allocated (by any client, including one running in a
4401** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4402** bExtend is non-zero and the requested shared-memory region has not yet
4403** been allocated, it is allocated by this function.
4404**
4405** If the shared-memory region has already been allocated or is allocated by
4406** this call as described above, then it is mapped into this processes
4407** address space (if it is not already), *pp is set to point to the mapped
4408** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004409*/
danda9fe0c2010-07-13 18:44:03 +00004410static int unixShmMap(
4411 sqlite3_file *fd, /* Handle open on database file */
4412 int iRegion, /* Region to retrieve */
4413 int szRegion, /* Size of regions */
4414 int bExtend, /* True to extend file if necessary */
4415 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004416){
danda9fe0c2010-07-13 18:44:03 +00004417 unixFile *pDbFd = (unixFile*)fd;
4418 unixShm *p;
4419 unixShmNode *pShmNode;
4420 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004421 int nShmPerMap = unixShmRegionPerMap();
4422 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004423
danda9fe0c2010-07-13 18:44:03 +00004424 /* If the shared-memory file has not yet been opened, open it now. */
4425 if( pDbFd->pShm==0 ){
4426 rc = unixOpenSharedMemory(pDbFd);
4427 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004428 }
drhd9e5c4f2010-05-12 18:01:39 +00004429
danda9fe0c2010-07-13 18:44:03 +00004430 p = pDbFd->pShm;
4431 pShmNode = p->pShmNode;
4432 sqlite3_mutex_enter(pShmNode->mutex);
4433 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004434 assert( pShmNode->pInode==pDbFd->pInode );
4435 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4436 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004437
dan781e34c2014-03-20 08:59:47 +00004438 /* Minimum number of regions required to be mapped. */
4439 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4440
4441 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004442 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004443 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004444 struct stat sStat; /* Used by fstat() */
4445
4446 pShmNode->szRegion = szRegion;
4447
drh3cb93392011-03-12 18:10:44 +00004448 if( pShmNode->h>=0 ){
4449 /* The requested region is not mapped into this processes address space.
4450 ** Check to see if it has been allocated (i.e. if the wal-index file is
4451 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004452 */
drh3cb93392011-03-12 18:10:44 +00004453 if( osFstat(pShmNode->h, &sStat) ){
4454 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004455 goto shmpage_out;
4456 }
drh3cb93392011-03-12 18:10:44 +00004457
4458 if( sStat.st_size<nByte ){
4459 /* The requested memory region does not exist. If bExtend is set to
4460 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004461 */
dan47a2b4a2013-04-26 16:09:29 +00004462 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004463 goto shmpage_out;
4464 }
dan47a2b4a2013-04-26 16:09:29 +00004465
4466 /* Alternatively, if bExtend is true, extend the file. Do this by
4467 ** writing a single byte to the end of each (OS) page being
4468 ** allocated or extended. Technically, we need only write to the
4469 ** last page in order to extend the file. But writing to all new
4470 ** pages forces the OS to allocate them immediately, which reduces
4471 ** the chances of SIGBUS while accessing the mapped region later on.
4472 */
4473 else{
4474 static const int pgsz = 4096;
4475 int iPg;
4476
4477 /* Write to the last byte of each newly allocated or extended page */
4478 assert( (nByte % pgsz)==0 );
4479 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
4480 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
4481 const char *zFile = pShmNode->zFilename;
4482 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4483 goto shmpage_out;
4484 }
4485 }
drh3cb93392011-03-12 18:10:44 +00004486 }
4487 }
danda9fe0c2010-07-13 18:44:03 +00004488 }
4489
4490 /* Map the requested memory region into this processes address space. */
4491 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004492 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004493 );
4494 if( !apNew ){
4495 rc = SQLITE_IOERR_NOMEM;
4496 goto shmpage_out;
4497 }
4498 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004499 while( pShmNode->nRegion<nReqRegion ){
4500 int nMap = szRegion*nShmPerMap;
4501 int i;
drh3cb93392011-03-12 18:10:44 +00004502 void *pMem;
4503 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004504 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004505 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004506 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004507 );
4508 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004509 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004510 goto shmpage_out;
4511 }
4512 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004513 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004514 if( pMem==0 ){
4515 rc = SQLITE_NOMEM;
4516 goto shmpage_out;
4517 }
4518 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004519 }
dan781e34c2014-03-20 08:59:47 +00004520
4521 for(i=0; i<nShmPerMap; i++){
4522 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4523 }
4524 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004525 }
4526 }
4527
4528shmpage_out:
4529 if( pShmNode->nRegion>iRegion ){
4530 *pp = pShmNode->apRegion[iRegion];
4531 }else{
4532 *pp = 0;
4533 }
drh66dfec8b2011-06-01 20:01:49 +00004534 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004535 sqlite3_mutex_leave(pShmNode->mutex);
4536 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004537}
4538
4539/*
drhd9e5c4f2010-05-12 18:01:39 +00004540** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004541**
4542** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4543** different here than in posix. In xShmLock(), one can go from unlocked
4544** to shared and back or from unlocked to exclusive and back. But one may
4545** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004546*/
4547static int unixShmLock(
4548 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004549 int ofst, /* First lock to acquire or release */
4550 int n, /* Number of locks to acquire or release */
4551 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004552){
drh73b64e42010-05-30 19:55:15 +00004553 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4554 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4555 unixShm *pX; /* For looping over all siblings */
4556 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4557 int rc = SQLITE_OK; /* Result code */
4558 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004559
drhd91c68f2010-05-14 14:52:25 +00004560 assert( pShmNode==pDbFd->pInode->pShmNode );
4561 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004562 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004563 assert( n>=1 );
4564 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4565 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4566 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4567 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4568 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004569 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4570 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004571
drhc99597c2010-05-31 01:41:15 +00004572 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004573 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004574 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004575 if( flags & SQLITE_SHM_UNLOCK ){
4576 u16 allMask = 0; /* Mask of locks held by siblings */
4577
4578 /* See if any siblings hold this same lock */
4579 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4580 if( pX==p ) continue;
4581 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4582 allMask |= pX->sharedMask;
4583 }
4584
4585 /* Unlock the system-level locks */
4586 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004587 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004588 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004589 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004590 }
drh73b64e42010-05-30 19:55:15 +00004591
4592 /* Undo the local locks */
4593 if( rc==SQLITE_OK ){
4594 p->exclMask &= ~mask;
4595 p->sharedMask &= ~mask;
4596 }
4597 }else if( flags & SQLITE_SHM_SHARED ){
4598 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4599
4600 /* Find out which shared locks are already held by sibling connections.
4601 ** If any sibling already holds an exclusive lock, go ahead and return
4602 ** SQLITE_BUSY.
4603 */
4604 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004605 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004606 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004607 break;
4608 }
4609 allShared |= pX->sharedMask;
4610 }
4611
4612 /* Get shared locks at the system level, if necessary */
4613 if( rc==SQLITE_OK ){
4614 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004615 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004616 }else{
drh73b64e42010-05-30 19:55:15 +00004617 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004618 }
drhd9e5c4f2010-05-12 18:01:39 +00004619 }
drh73b64e42010-05-30 19:55:15 +00004620
4621 /* Get the local shared locks */
4622 if( rc==SQLITE_OK ){
4623 p->sharedMask |= mask;
4624 }
4625 }else{
4626 /* Make sure no sibling connections hold locks that will block this
4627 ** lock. If any do, return SQLITE_BUSY right away.
4628 */
4629 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004630 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4631 rc = SQLITE_BUSY;
4632 break;
4633 }
4634 }
4635
4636 /* Get the exclusive locks at the system level. Then if successful
4637 ** also mark the local connection as being locked.
4638 */
4639 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004640 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004641 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004642 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004643 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004644 }
drhd9e5c4f2010-05-12 18:01:39 +00004645 }
4646 }
drhd91c68f2010-05-14 14:52:25 +00004647 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004648 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004649 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004650 return rc;
4651}
4652
drh286a2882010-05-20 23:51:06 +00004653/*
4654** Implement a memory barrier or memory fence on shared memory.
4655**
4656** All loads and stores begun before the barrier must complete before
4657** any load or store begun after the barrier.
4658*/
4659static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004660 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004661){
drhff828942010-06-26 21:34:06 +00004662 UNUSED_PARAMETER(fd);
drhb29ad852010-06-01 00:03:57 +00004663 unixEnterMutex();
4664 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004665}
4666
dan18801912010-06-14 14:07:50 +00004667/*
danda9fe0c2010-07-13 18:44:03 +00004668** Close a connection to shared-memory. Delete the underlying
4669** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004670**
4671** If there is no shared memory associated with the connection then this
4672** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004673*/
danda9fe0c2010-07-13 18:44:03 +00004674static int unixShmUnmap(
4675 sqlite3_file *fd, /* The underlying database file */
4676 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004677){
danda9fe0c2010-07-13 18:44:03 +00004678 unixShm *p; /* The connection to be closed */
4679 unixShmNode *pShmNode; /* The underlying shared-memory file */
4680 unixShm **pp; /* For looping over sibling connections */
4681 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004682
danda9fe0c2010-07-13 18:44:03 +00004683 pDbFd = (unixFile*)fd;
4684 p = pDbFd->pShm;
4685 if( p==0 ) return SQLITE_OK;
4686 pShmNode = p->pShmNode;
4687
4688 assert( pShmNode==pDbFd->pInode->pShmNode );
4689 assert( pShmNode->pInode==pDbFd->pInode );
4690
4691 /* Remove connection p from the set of connections associated
4692 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004693 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004694 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4695 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004696
danda9fe0c2010-07-13 18:44:03 +00004697 /* Free the connection p */
4698 sqlite3_free(p);
4699 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004700 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004701
4702 /* If pShmNode->nRef has reached 0, then close the underlying
4703 ** shared-memory file, too */
4704 unixEnterMutex();
4705 assert( pShmNode->nRef>0 );
4706 pShmNode->nRef--;
4707 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004708 if( deleteFlag && pShmNode->h>=0 ){
4709 osUnlink(pShmNode->zFilename);
4710 }
danda9fe0c2010-07-13 18:44:03 +00004711 unixShmPurge(pDbFd);
4712 }
4713 unixLeaveMutex();
4714
4715 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004716}
drh286a2882010-05-20 23:51:06 +00004717
danda9fe0c2010-07-13 18:44:03 +00004718
drhd9e5c4f2010-05-12 18:01:39 +00004719#else
drh6b017cc2010-06-14 18:01:46 +00004720# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004721# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004722# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004723# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004724#endif /* #ifndef SQLITE_OMIT_WAL */
4725
mistachkine98844f2013-08-24 00:59:24 +00004726#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004727/*
danaef49d72013-03-25 16:28:54 +00004728** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004729*/
danf23da962013-03-23 21:00:41 +00004730static void unixUnmapfile(unixFile *pFd){
4731 assert( pFd->nFetchOut==0 );
4732 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004733 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004734 pFd->pMapRegion = 0;
4735 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004736 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004737 }
4738}
dan5d8a1372013-03-19 19:28:06 +00004739
danaef49d72013-03-25 16:28:54 +00004740/*
dane6ecd662013-04-01 17:56:59 +00004741** Attempt to set the size of the memory mapping maintained by file
4742** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4743**
4744** If successful, this function sets the following variables:
4745**
4746** unixFile.pMapRegion
4747** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004748** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004749**
4750** If unsuccessful, an error message is logged via sqlite3_log() and
4751** the three variables above are zeroed. In this case SQLite should
4752** continue accessing the database using the xRead() and xWrite()
4753** methods.
4754*/
4755static void unixRemapfile(
4756 unixFile *pFd, /* File descriptor object */
4757 i64 nNew /* Required mapping size */
4758){
dan4ff7bc42013-04-02 12:04:09 +00004759 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004760 int h = pFd->h; /* File descriptor open on db file */
4761 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004762 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004763 u8 *pNew = 0; /* Location of new mapping */
4764 int flags = PROT_READ; /* Flags to pass to mmap() */
4765
4766 assert( pFd->nFetchOut==0 );
4767 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004768 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004769 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004770 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004771 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004772
4773 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
4774
4775 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004776#if HAVE_MREMAP
4777 i64 nReuse = pFd->mmapSize;
4778#else
danbc760632014-03-20 09:42:09 +00004779 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004780 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004781#endif
dane6ecd662013-04-01 17:56:59 +00004782 u8 *pReq = &pOrig[nReuse];
4783
4784 /* Unmap any pages of the existing mapping that cannot be reused. */
4785 if( nReuse!=nOrig ){
4786 osMunmap(pReq, nOrig-nReuse);
4787 }
4788
4789#if HAVE_MREMAP
4790 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004791 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004792#else
4793 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4794 if( pNew!=MAP_FAILED ){
4795 if( pNew!=pReq ){
4796 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004797 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004798 }else{
4799 pNew = pOrig;
4800 }
4801 }
4802#endif
4803
dan48ccef82013-04-02 20:55:01 +00004804 /* The attempt to extend the existing mapping failed. Free it. */
4805 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004806 osMunmap(pOrig, nReuse);
4807 }
4808 }
4809
4810 /* If pNew is still NULL, try to create an entirely new mapping. */
4811 if( pNew==0 ){
4812 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004813 }
4814
dan4ff7bc42013-04-02 12:04:09 +00004815 if( pNew==MAP_FAILED ){
4816 pNew = 0;
4817 nNew = 0;
4818 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4819
4820 /* If the mmap() above failed, assume that all subsequent mmap() calls
4821 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4822 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004823 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004824 }
dane6ecd662013-04-01 17:56:59 +00004825 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004826 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004827}
4828
4829/*
danaef49d72013-03-25 16:28:54 +00004830** Memory map or remap the file opened by file-descriptor pFd (if the file
4831** is already mapped, the existing mapping is replaced by the new). Or, if
4832** there already exists a mapping for this file, and there are still
4833** outstanding xFetch() references to it, this function is a no-op.
4834**
4835** If parameter nByte is non-negative, then it is the requested size of
4836** the mapping to create. Otherwise, if nByte is less than zero, then the
4837** requested size is the size of the file on disk. The actual size of the
4838** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004839** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004840**
4841** SQLITE_OK is returned if no error occurs (even if the mapping is not
4842** recreated as a result of outstanding references) or an SQLite error
4843** code otherwise.
4844*/
danf23da962013-03-23 21:00:41 +00004845static int unixMapfile(unixFile *pFd, i64 nByte){
4846 i64 nMap = nByte;
4847 int rc;
daneb97b292013-03-20 14:26:59 +00004848
danf23da962013-03-23 21:00:41 +00004849 assert( nMap>=0 || pFd->nFetchOut==0 );
4850 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4851
4852 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004853 struct stat statbuf; /* Low-level file information */
4854 rc = osFstat(pFd->h, &statbuf);
danf23da962013-03-23 21:00:41 +00004855 if( rc!=SQLITE_OK ){
4856 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004857 }
drh3044b512014-06-16 16:41:52 +00004858 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004859 }
drh9b4c59f2013-04-15 17:03:42 +00004860 if( nMap>pFd->mmapSizeMax ){
4861 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004862 }
4863
danf23da962013-03-23 21:00:41 +00004864 if( nMap!=pFd->mmapSize ){
dane6ecd662013-04-01 17:56:59 +00004865 if( nMap>0 ){
4866 unixRemapfile(pFd, nMap);
4867 }else{
danb7e3a322013-03-25 20:30:13 +00004868 unixUnmapfile(pFd);
dan5d8a1372013-03-19 19:28:06 +00004869 }
4870 }
4871
danf23da962013-03-23 21:00:41 +00004872 return SQLITE_OK;
4873}
mistachkine98844f2013-08-24 00:59:24 +00004874#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004875
danaef49d72013-03-25 16:28:54 +00004876/*
4877** If possible, return a pointer to a mapping of file fd starting at offset
4878** iOff. The mapping must be valid for at least nAmt bytes.
4879**
4880** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4881** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4882** Finally, if an error does occur, return an SQLite error code. The final
4883** value of *pp is undefined in this case.
4884**
4885** If this function does return a pointer, the caller must eventually
4886** release the reference by calling unixUnfetch().
4887*/
danf23da962013-03-23 21:00:41 +00004888static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004889#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004890 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004891#endif
danf23da962013-03-23 21:00:41 +00004892 *pp = 0;
4893
drh9b4c59f2013-04-15 17:03:42 +00004894#if SQLITE_MAX_MMAP_SIZE>0
4895 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004896 if( pFd->pMapRegion==0 ){
4897 int rc = unixMapfile(pFd, -1);
4898 if( rc!=SQLITE_OK ) return rc;
4899 }
4900 if( pFd->mmapSize >= iOff+nAmt ){
4901 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4902 pFd->nFetchOut++;
4903 }
4904 }
drh6e0b6d52013-04-09 16:19:20 +00004905#endif
danf23da962013-03-23 21:00:41 +00004906 return SQLITE_OK;
4907}
4908
danaef49d72013-03-25 16:28:54 +00004909/*
dandf737fe2013-03-25 17:00:24 +00004910** If the third argument is non-NULL, then this function releases a
4911** reference obtained by an earlier call to unixFetch(). The second
4912** argument passed to this function must be the same as the corresponding
4913** argument that was passed to the unixFetch() invocation.
4914**
4915** Or, if the third argument is NULL, then this function is being called
4916** to inform the VFS layer that, according to POSIX, any existing mapping
4917** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004918*/
dandf737fe2013-03-25 17:00:24 +00004919static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004920#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004921 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004922 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004923
danaef49d72013-03-25 16:28:54 +00004924 /* If p==0 (unmap the entire file) then there must be no outstanding
4925 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4926 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004927 assert( (p==0)==(pFd->nFetchOut==0) );
4928
dandf737fe2013-03-25 17:00:24 +00004929 /* If p!=0, it must match the iOff value. */
4930 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4931
danf23da962013-03-23 21:00:41 +00004932 if( p ){
4933 pFd->nFetchOut--;
4934 }else{
4935 unixUnmapfile(pFd);
4936 }
4937
4938 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004939#else
4940 UNUSED_PARAMETER(fd);
4941 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004942 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004943#endif
danf23da962013-03-23 21:00:41 +00004944 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004945}
4946
4947/*
drh734c9862008-11-28 15:37:20 +00004948** Here ends the implementation of all sqlite3_file methods.
4949**
4950********************** End sqlite3_file Methods *******************************
4951******************************************************************************/
4952
4953/*
drh6b9d6dd2008-12-03 19:34:47 +00004954** This division contains definitions of sqlite3_io_methods objects that
4955** implement various file locking strategies. It also contains definitions
4956** of "finder" functions. A finder-function is used to locate the appropriate
4957** sqlite3_io_methods object for a particular database file. The pAppData
4958** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4959** the correct finder-function for that VFS.
4960**
4961** Most finder functions return a pointer to a fixed sqlite3_io_methods
4962** object. The only interesting finder-function is autolockIoFinder, which
4963** looks at the filesystem type and tries to guess the best locking
4964** strategy from that.
4965**
peter.d.reid60ec9142014-09-06 16:39:46 +00004966** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004967**
4968** (1) The real finder-function named "FImpt()".
4969**
dane946c392009-08-22 11:39:46 +00004970** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004971**
4972**
4973** A pointer to the F pointer is used as the pAppData value for VFS
4974** objects. We have to do this instead of letting pAppData point
4975** directly at the finder-function since C90 rules prevent a void*
4976** from be cast into a function pointer.
4977**
drh6b9d6dd2008-12-03 19:34:47 +00004978**
drh7708e972008-11-29 00:56:52 +00004979** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004980**
drh7708e972008-11-29 00:56:52 +00004981** * A constant sqlite3_io_methods object call METHOD that has locking
4982** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4983**
4984** * An I/O method finder function called FINDER that returns a pointer
4985** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004986*/
drhe6d41732015-02-21 00:49:00 +00004987#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004988static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004989 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004990 CLOSE, /* xClose */ \
4991 unixRead, /* xRead */ \
4992 unixWrite, /* xWrite */ \
4993 unixTruncate, /* xTruncate */ \
4994 unixSync, /* xSync */ \
4995 unixFileSize, /* xFileSize */ \
4996 LOCK, /* xLock */ \
4997 UNLOCK, /* xUnlock */ \
4998 CKLOCK, /* xCheckReservedLock */ \
4999 unixFileControl, /* xFileControl */ \
5000 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005001 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005002 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005003 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005004 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005005 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005006 unixFetch, /* xFetch */ \
5007 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005008}; \
drh0c2694b2009-09-03 16:23:44 +00005009static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5010 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005011 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005012} \
drh0c2694b2009-09-03 16:23:44 +00005013static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005014 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005015
5016/*
5017** Here are all of the sqlite3_io_methods objects for each of the
5018** locking strategies. Functions that return pointers to these methods
5019** are also created.
5020*/
5021IOMETHODS(
5022 posixIoFinder, /* Finder function name */
5023 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005024 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005025 unixClose, /* xClose method */
5026 unixLock, /* xLock method */
5027 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005028 unixCheckReservedLock, /* xCheckReservedLock method */
5029 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005030)
drh7708e972008-11-29 00:56:52 +00005031IOMETHODS(
5032 nolockIoFinder, /* Finder function name */
5033 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005034 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005035 nolockClose, /* xClose method */
5036 nolockLock, /* xLock method */
5037 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005038 nolockCheckReservedLock, /* xCheckReservedLock method */
5039 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005040)
drh7708e972008-11-29 00:56:52 +00005041IOMETHODS(
5042 dotlockIoFinder, /* Finder function name */
5043 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005044 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005045 dotlockClose, /* xClose method */
5046 dotlockLock, /* xLock method */
5047 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005048 dotlockCheckReservedLock, /* xCheckReservedLock method */
5049 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005050)
drh7708e972008-11-29 00:56:52 +00005051
drhe89b2912015-03-03 20:42:01 +00005052#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005053IOMETHODS(
5054 flockIoFinder, /* Finder function name */
5055 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005056 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005057 flockClose, /* xClose method */
5058 flockLock, /* xLock method */
5059 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005060 flockCheckReservedLock, /* xCheckReservedLock method */
5061 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005062)
drh7708e972008-11-29 00:56:52 +00005063#endif
5064
drh6c7d5c52008-11-21 20:32:33 +00005065#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005066IOMETHODS(
5067 semIoFinder, /* Finder function name */
5068 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005069 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005070 semXClose, /* xClose method */
5071 semXLock, /* xLock method */
5072 semXUnlock, /* xUnlock method */
5073 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005074 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005075)
aswiftaebf4132008-11-21 00:10:35 +00005076#endif
drh7708e972008-11-29 00:56:52 +00005077
drhd2cb50b2009-01-09 21:41:17 +00005078#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005079IOMETHODS(
5080 afpIoFinder, /* Finder function name */
5081 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005082 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005083 afpClose, /* xClose method */
5084 afpLock, /* xLock method */
5085 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005086 afpCheckReservedLock, /* xCheckReservedLock method */
5087 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005088)
drh715ff302008-12-03 22:32:44 +00005089#endif
5090
5091/*
5092** The proxy locking method is a "super-method" in the sense that it
5093** opens secondary file descriptors for the conch and lock files and
5094** it uses proxy, dot-file, AFP, and flock() locking methods on those
5095** secondary files. For this reason, the division that implements
5096** proxy locking is located much further down in the file. But we need
5097** to go ahead and define the sqlite3_io_methods and finder function
5098** for proxy locking here. So we forward declare the I/O methods.
5099*/
drhd2cb50b2009-01-09 21:41:17 +00005100#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005101static int proxyClose(sqlite3_file*);
5102static int proxyLock(sqlite3_file*, int);
5103static int proxyUnlock(sqlite3_file*, int);
5104static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005105IOMETHODS(
5106 proxyIoFinder, /* Finder function name */
5107 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005108 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005109 proxyClose, /* xClose method */
5110 proxyLock, /* xLock method */
5111 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005112 proxyCheckReservedLock, /* xCheckReservedLock method */
5113 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005114)
aswiftaebf4132008-11-21 00:10:35 +00005115#endif
drh7708e972008-11-29 00:56:52 +00005116
drh7ed97b92010-01-20 13:07:21 +00005117/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5118#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5119IOMETHODS(
5120 nfsIoFinder, /* Finder function name */
5121 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005122 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005123 unixClose, /* xClose method */
5124 unixLock, /* xLock method */
5125 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005126 unixCheckReservedLock, /* xCheckReservedLock method */
5127 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005128)
5129#endif
drh7708e972008-11-29 00:56:52 +00005130
drhd2cb50b2009-01-09 21:41:17 +00005131#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005132/*
drh6b9d6dd2008-12-03 19:34:47 +00005133** This "finder" function attempts to determine the best locking strategy
5134** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005135** object that implements that strategy.
5136**
5137** This is for MacOSX only.
5138*/
drh1875f7a2008-12-08 18:19:17 +00005139static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005140 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005141 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005142){
5143 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005144 const char *zFilesystem; /* Filesystem type name */
5145 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005146 } aMap[] = {
5147 { "hfs", &posixIoMethods },
5148 { "ufs", &posixIoMethods },
5149 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005150 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005151 { "webdav", &nolockIoMethods },
5152 { 0, 0 }
5153 };
5154 int i;
5155 struct statfs fsInfo;
5156 struct flock lockInfo;
5157
5158 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005159 /* If filePath==NULL that means we are dealing with a transient file
5160 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005161 return &nolockIoMethods;
5162 }
5163 if( statfs(filePath, &fsInfo) != -1 ){
5164 if( fsInfo.f_flags & MNT_RDONLY ){
5165 return &nolockIoMethods;
5166 }
5167 for(i=0; aMap[i].zFilesystem; i++){
5168 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5169 return aMap[i].pMethods;
5170 }
5171 }
5172 }
5173
5174 /* Default case. Handles, amongst others, "nfs".
5175 ** Test byte-range lock using fcntl(). If the call succeeds,
5176 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005177 */
drh7708e972008-11-29 00:56:52 +00005178 lockInfo.l_len = 1;
5179 lockInfo.l_start = 0;
5180 lockInfo.l_whence = SEEK_SET;
5181 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005182 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005183 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5184 return &nfsIoMethods;
5185 } else {
5186 return &posixIoMethods;
5187 }
drh7708e972008-11-29 00:56:52 +00005188 }else{
5189 return &dotlockIoMethods;
5190 }
5191}
drh0c2694b2009-09-03 16:23:44 +00005192static const sqlite3_io_methods
5193 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005194
drhd2cb50b2009-01-09 21:41:17 +00005195#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005196
drhe89b2912015-03-03 20:42:01 +00005197#if OS_VXWORKS
5198/*
5199** This "finder" function for VxWorks checks to see if posix advisory
5200** locking works. If it does, then that is what is used. If it does not
5201** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005202*/
drhe89b2912015-03-03 20:42:01 +00005203static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005204 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005205 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005206){
5207 struct flock lockInfo;
5208
5209 if( !filePath ){
5210 /* If filePath==NULL that means we are dealing with a transient file
5211 ** that does not need to be locked. */
5212 return &nolockIoMethods;
5213 }
5214
5215 /* Test if fcntl() is supported and use POSIX style locks.
5216 ** Otherwise fall back to the named semaphore method.
5217 */
5218 lockInfo.l_len = 1;
5219 lockInfo.l_start = 0;
5220 lockInfo.l_whence = SEEK_SET;
5221 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005222 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005223 return &posixIoMethods;
5224 }else{
5225 return &semIoMethods;
5226 }
5227}
drh0c2694b2009-09-03 16:23:44 +00005228static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005229 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005230
drhe89b2912015-03-03 20:42:01 +00005231#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005232
drh7708e972008-11-29 00:56:52 +00005233/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005234** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005235*/
drh0c2694b2009-09-03 16:23:44 +00005236typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005237
aswiftaebf4132008-11-21 00:10:35 +00005238
drh734c9862008-11-28 15:37:20 +00005239/****************************************************************************
5240**************************** sqlite3_vfs methods ****************************
5241**
5242** This division contains the implementation of methods on the
5243** sqlite3_vfs object.
5244*/
5245
danielk1977a3d4c882007-03-23 10:08:38 +00005246/*
danielk1977e339d652008-06-28 11:23:00 +00005247** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005248*/
5249static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005250 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005251 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005252 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005253 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005254 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005255){
drh7708e972008-11-29 00:56:52 +00005256 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005257 unixFile *pNew = (unixFile *)pId;
5258 int rc = SQLITE_OK;
5259
drh8af6c222010-05-14 12:43:01 +00005260 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005261
dan00157392010-10-05 11:33:15 +00005262 /* Usually the path zFilename should not be a relative pathname. The
5263 ** exception is when opening the proxy "conch" file in builds that
5264 ** include the special Apple locking styles.
5265 */
dan00157392010-10-05 11:33:15 +00005266#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005267 assert( zFilename==0 || zFilename[0]=='/'
5268 || pVfs->pAppData==(void*)&autolockIoFinder );
5269#else
5270 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005271#endif
dan00157392010-10-05 11:33:15 +00005272
drhb07028f2011-10-14 21:49:18 +00005273 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005274 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005275
drh308c2a52010-05-14 11:30:18 +00005276 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005277 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005278 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005279 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005280 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005281#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005282 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005283#endif
drhc02a43a2012-01-10 23:18:38 +00005284 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5285 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005286 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005287 }
drh503a6862013-03-01 01:07:17 +00005288 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005289 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005290 }
drh339eb0b2008-03-07 15:34:11 +00005291
drh6c7d5c52008-11-21 20:32:33 +00005292#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005293 pNew->pId = vxworksFindFileId(zFilename);
5294 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005295 ctrlFlags |= UNIXFILE_NOLOCK;
drh107886a2008-11-21 22:21:50 +00005296 rc = SQLITE_NOMEM;
chw97185482008-11-17 08:05:31 +00005297 }
5298#endif
5299
drhc02a43a2012-01-10 23:18:38 +00005300 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005301 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005302 }else{
drh0c2694b2009-09-03 16:23:44 +00005303 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005304#if SQLITE_ENABLE_LOCKING_STYLE
5305 /* Cache zFilename in the locking context (AFP and dotlock override) for
5306 ** proxyLock activation is possible (remote proxy is based on db name)
5307 ** zFilename remains valid until file is closed, to support */
5308 pNew->lockingContext = (void*)zFilename;
5309#endif
drhda0e7682008-07-30 15:27:54 +00005310 }
danielk1977e339d652008-06-28 11:23:00 +00005311
drh7ed97b92010-01-20 13:07:21 +00005312 if( pLockingStyle == &posixIoMethods
5313#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5314 || pLockingStyle == &nfsIoMethods
5315#endif
5316 ){
drh7708e972008-11-29 00:56:52 +00005317 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005318 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005319 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005320 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005321 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005322 ** in two scenarios:
5323 **
5324 ** (a) A call to fstat() failed.
5325 ** (b) A malloc failed.
5326 **
5327 ** Scenario (b) may only occur if the process is holding no other
5328 ** file descriptors open on the same file. If there were other file
5329 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005330 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005331 ** handle h - as it is guaranteed that no posix locks will be released
5332 ** by doing so.
5333 **
5334 ** If scenario (a) caused the error then things are not so safe. The
5335 ** implicit assumption here is that if fstat() fails, things are in
5336 ** such bad shape that dropping a lock or two doesn't matter much.
5337 */
drh0e9365c2011-03-02 02:08:13 +00005338 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005339 h = -1;
5340 }
drh7708e972008-11-29 00:56:52 +00005341 unixLeaveMutex();
5342 }
danielk1977e339d652008-06-28 11:23:00 +00005343
drhd2cb50b2009-01-09 21:41:17 +00005344#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005345 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005346 /* AFP locking uses the file path so it needs to be included in
5347 ** the afpLockingContext.
5348 */
5349 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005350 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005351 if( pCtx==0 ){
5352 rc = SQLITE_NOMEM;
5353 }else{
5354 /* NB: zFilename exists and remains valid until the file is closed
5355 ** according to requirement F11141. So we do not need to make a
5356 ** copy of the filename. */
5357 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005358 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005359 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005360 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005361 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005362 if( rc!=SQLITE_OK ){
5363 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005364 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005365 h = -1;
5366 }
drh7708e972008-11-29 00:56:52 +00005367 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005368 }
drh7708e972008-11-29 00:56:52 +00005369 }
5370#endif
danielk1977e339d652008-06-28 11:23:00 +00005371
drh7708e972008-11-29 00:56:52 +00005372 else if( pLockingStyle == &dotlockIoMethods ){
5373 /* Dotfile locking uses the file path so it needs to be included in
5374 ** the dotlockLockingContext
5375 */
5376 char *zLockFile;
5377 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005378 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005379 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005380 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005381 if( zLockFile==0 ){
5382 rc = SQLITE_NOMEM;
5383 }else{
5384 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005385 }
drh7708e972008-11-29 00:56:52 +00005386 pNew->lockingContext = zLockFile;
5387 }
danielk1977e339d652008-06-28 11:23:00 +00005388
drh6c7d5c52008-11-21 20:32:33 +00005389#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005390 else if( pLockingStyle == &semIoMethods ){
5391 /* Named semaphore locking uses the file path so it needs to be
5392 ** included in the semLockingContext
5393 */
5394 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005395 rc = findInodeInfo(pNew, &pNew->pInode);
5396 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5397 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005398 int n;
drh2238dcc2009-08-27 17:56:20 +00005399 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005400 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005401 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005402 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005403 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5404 if( pNew->pInode->pSem == SEM_FAILED ){
drh7708e972008-11-29 00:56:52 +00005405 rc = SQLITE_NOMEM;
drh8af6c222010-05-14 12:43:01 +00005406 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005407 }
chw97185482008-11-17 08:05:31 +00005408 }
drh7708e972008-11-29 00:56:52 +00005409 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005410 }
drh7708e972008-11-29 00:56:52 +00005411#endif
aswift5b1a2562008-08-22 00:22:35 +00005412
drh4bf66fd2015-02-19 02:43:02 +00005413 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005414#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005415 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005416 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005417 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005418 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005419 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005420 }
chw97185482008-11-17 08:05:31 +00005421#endif
danielk1977e339d652008-06-28 11:23:00 +00005422 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005423 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005424 }else{
drh7708e972008-11-29 00:56:52 +00005425 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005426 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005427 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005428 }
danielk1977e339d652008-06-28 11:23:00 +00005429 return rc;
drh054889e2005-11-30 03:20:31 +00005430}
drh9c06c952005-11-26 00:25:00 +00005431
danielk1977ad94b582007-08-20 06:44:22 +00005432/*
drh8b3cf822010-06-01 21:02:51 +00005433** Return the name of a directory in which to put temporary files.
5434** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005435*/
drh7234c6d2010-06-19 15:10:09 +00005436static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005437 static const char *azDirs[] = {
5438 0,
aswiftaebf4132008-11-21 00:10:35 +00005439 0,
mistachkind95a3d32013-08-30 21:52:38 +00005440 0,
danielk197717b90b52008-06-06 11:11:25 +00005441 "/var/tmp",
5442 "/usr/tmp",
5443 "/tmp",
drh8b3cf822010-06-01 21:02:51 +00005444 0 /* List terminator */
danielk197717b90b52008-06-06 11:11:25 +00005445 };
drh8b3cf822010-06-01 21:02:51 +00005446 unsigned int i;
5447 struct stat buf;
5448 const char *zDir = 0;
5449
5450 azDirs[0] = sqlite3_temp_directory;
mistachkind95a3d32013-08-30 21:52:38 +00005451 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
5452 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005453 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005454 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005455 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005456 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005457 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005458 break;
5459 }
5460 return zDir;
5461}
5462
5463/*
5464** Create a temporary file name in zBuf. zBuf must be allocated
5465** by the calling process and must be big enough to hold at least
5466** pVfs->mxPathname bytes.
5467*/
5468static int unixGetTempname(int nBuf, char *zBuf){
danielk197717b90b52008-06-06 11:11:25 +00005469 static const unsigned char zChars[] =
5470 "abcdefghijklmnopqrstuvwxyz"
5471 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5472 "0123456789";
drh41022642008-11-21 00:24:42 +00005473 unsigned int i, j;
drh8b3cf822010-06-01 21:02:51 +00005474 const char *zDir;
danielk197717b90b52008-06-06 11:11:25 +00005475
5476 /* It's odd to simulate an io-error here, but really this is just
5477 ** using the io-error infrastructure to test that SQLite handles this
5478 ** function failing.
5479 */
5480 SimulateIOError( return SQLITE_IOERR );
5481
drh7234c6d2010-06-19 15:10:09 +00005482 zDir = unixTempFileDir();
drh8b3cf822010-06-01 21:02:51 +00005483 if( zDir==0 ) zDir = ".";
danielk197717b90b52008-06-06 11:11:25 +00005484
5485 /* Check that the output buffer is large enough for the temporary file
5486 ** name. If it is not, return SQLITE_ERROR.
5487 */
drhc02a43a2012-01-10 23:18:38 +00005488 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
danielk197717b90b52008-06-06 11:11:25 +00005489 return SQLITE_ERROR;
5490 }
5491
5492 do{
drhc02a43a2012-01-10 23:18:38 +00005493 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
drhea678832008-12-10 19:26:22 +00005494 j = (int)strlen(zBuf);
danielk197717b90b52008-06-06 11:11:25 +00005495 sqlite3_randomness(15, &zBuf[j]);
5496 for(i=0; i<15; i++, j++){
5497 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
5498 }
5499 zBuf[j] = 0;
drhc02a43a2012-01-10 23:18:38 +00005500 zBuf[j+1] = 0;
drh99ab3b12011-03-02 15:09:07 +00005501 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005502 return SQLITE_OK;
5503}
5504
drhd2cb50b2009-01-09 21:41:17 +00005505#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005506/*
5507** Routine to transform a unixFile into a proxy-locking unixFile.
5508** Implementation in the proxy-lock division, but used by unixOpen()
5509** if SQLITE_PREFER_PROXY_LOCKING is defined.
5510*/
5511static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005512#endif
drhc66d5b62008-12-03 22:48:32 +00005513
dan08da86a2009-08-21 17:18:03 +00005514/*
5515** Search for an unused file descriptor that was opened on the database
5516** file (not a journal or master-journal file) identified by pathname
5517** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5518** argument to this function.
5519**
5520** Such a file descriptor may exist if a database connection was closed
5521** but the associated file descriptor could not be closed because some
5522** other file descriptor open on the same file is holding a file-lock.
5523** Refer to comments in the unixClose() function and the lengthy comment
5524** describing "Posix Advisory Locking" at the start of this file for
5525** further details. Also, ticket #4018.
5526**
5527** If a suitable file descriptor is found, then it is returned. If no
5528** such file descriptor is located, -1 is returned.
5529*/
dane946c392009-08-22 11:39:46 +00005530static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5531 UnixUnusedFd *pUnused = 0;
5532
5533 /* Do not search for an unused file descriptor on vxworks. Not because
5534 ** vxworks would not benefit from the change (it might, we're not sure),
5535 ** but because no way to test it is currently available. It is better
5536 ** not to risk breaking vxworks support for the sake of such an obscure
5537 ** feature. */
5538#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005539 struct stat sStat; /* Results of stat() call */
5540
5541 /* A stat() call may fail for various reasons. If this happens, it is
5542 ** almost certain that an open() call on the same path will also fail.
5543 ** For this reason, if an error occurs in the stat() call here, it is
5544 ** ignored and -1 is returned. The caller will try to open a new file
5545 ** descriptor on the same path, fail, and return an error to SQLite.
5546 **
5547 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005548 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005549 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005550 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005551
5552 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005553 pInode = inodeList;
5554 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5555 || pInode->fileId.ino!=sStat.st_ino) ){
5556 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005557 }
drh8af6c222010-05-14 12:43:01 +00005558 if( pInode ){
dane946c392009-08-22 11:39:46 +00005559 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005560 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005561 pUnused = *pp;
5562 if( pUnused ){
5563 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005564 }
5565 }
5566 unixLeaveMutex();
5567 }
dane946c392009-08-22 11:39:46 +00005568#endif /* if !OS_VXWORKS */
5569 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005570}
danielk197717b90b52008-06-06 11:11:25 +00005571
5572/*
danddb0ac42010-07-14 14:48:58 +00005573** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005574** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005575** and a value suitable for passing as the third argument to open(2) is
5576** written to *pMode. If an IO error occurs, an SQLite error code is
5577** returned and the value of *pMode is not modified.
5578**
peter.d.reid60ec9142014-09-06 16:39:46 +00005579** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005580** an indication to robust_open() to create the file using
5581** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5582** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005583** this function queries the file-system for the permissions on the
5584** corresponding database file and sets *pMode to this value. Whenever
5585** possible, WAL and journal files are created using the same permissions
5586** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005587**
5588** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5589** original filename is unavailable. But 8_3_NAMES is only used for
5590** FAT filesystems and permissions do not matter there, so just use
5591** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005592*/
5593static int findCreateFileMode(
5594 const char *zPath, /* Path of file (possibly) being created */
5595 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005596 mode_t *pMode, /* OUT: Permissions to open file with */
5597 uid_t *pUid, /* OUT: uid to set on the file */
5598 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005599){
5600 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005601 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005602 *pUid = 0;
5603 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005604 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005605 char zDb[MAX_PATHNAME+1]; /* Database file path */
5606 int nDb; /* Number of valid bytes in zDb */
5607 struct stat sStat; /* Output of stat() on database file */
5608
dana0c989d2010-11-05 18:07:37 +00005609 /* zPath is a path to a WAL or journal file. The following block derives
5610 ** the path to the associated database file from zPath. This block handles
5611 ** the following naming conventions:
5612 **
5613 ** "<path to db>-journal"
5614 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005615 ** "<path to db>-journalNN"
5616 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005617 **
drhd337c5b2011-10-20 18:23:35 +00005618 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005619 ** used by the test_multiplex.c module.
5620 */
5621 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005622#ifdef SQLITE_ENABLE_8_3_NAMES
dan28a67fd2011-12-12 19:48:43 +00005623 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
drhd337c5b2011-10-20 18:23:35 +00005624 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005625#else
5626 while( zPath[nDb]!='-' ){
5627 assert( nDb>0 );
5628 assert( zPath[nDb]!='\n' );
5629 nDb--;
5630 }
5631#endif
danddb0ac42010-07-14 14:48:58 +00005632 memcpy(zDb, zPath, nDb);
5633 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005634
drh58384f12011-07-28 00:14:45 +00005635 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005636 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005637 *pUid = sStat.st_uid;
5638 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005639 }else{
5640 rc = SQLITE_IOERR_FSTAT;
5641 }
5642 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5643 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005644 }
5645 return rc;
5646}
5647
5648/*
danielk1977ad94b582007-08-20 06:44:22 +00005649** Open the file zPath.
5650**
danielk1977b4b47412007-08-17 15:53:36 +00005651** Previously, the SQLite OS layer used three functions in place of this
5652** one:
5653**
5654** sqlite3OsOpenReadWrite();
5655** sqlite3OsOpenReadOnly();
5656** sqlite3OsOpenExclusive();
5657**
5658** These calls correspond to the following combinations of flags:
5659**
5660** ReadWrite() -> (READWRITE | CREATE)
5661** ReadOnly() -> (READONLY)
5662** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5663**
5664** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5665** true, the file was configured to be automatically deleted when the
5666** file handle closed. To achieve the same effect using this new
5667** interface, add the DELETEONCLOSE flag to those specified above for
5668** OpenExclusive().
5669*/
5670static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005671 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5672 const char *zPath, /* Pathname of file to be opened */
5673 sqlite3_file *pFile, /* The file descriptor to be filled in */
5674 int flags, /* Input flags to control the opening */
5675 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005676){
dan08da86a2009-08-21 17:18:03 +00005677 unixFile *p = (unixFile *)pFile;
5678 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005679 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005680 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005681 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005682 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005683 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005684
5685 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5686 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5687 int isCreate = (flags & SQLITE_OPEN_CREATE);
5688 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5689 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005690#if SQLITE_ENABLE_LOCKING_STYLE
5691 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5692#endif
drh3d4435b2011-08-26 20:55:50 +00005693#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5694 struct statfs fsInfo;
5695#endif
danielk1977b4b47412007-08-17 15:53:36 +00005696
danielk1977fee2d252007-08-18 10:59:19 +00005697 /* If creating a master or main-file journal, this function will open
5698 ** a file-descriptor on the directory too. The first time unixSync()
5699 ** is called the directory file descriptor will be fsync()ed and close()d.
5700 */
drh0059eae2011-08-08 23:48:40 +00005701 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005702 eType==SQLITE_OPEN_MASTER_JOURNAL
5703 || eType==SQLITE_OPEN_MAIN_JOURNAL
5704 || eType==SQLITE_OPEN_WAL
5705 ));
danielk1977fee2d252007-08-18 10:59:19 +00005706
danielk197717b90b52008-06-06 11:11:25 +00005707 /* If argument zPath is a NULL pointer, this function is required to open
5708 ** a temporary file. Use this buffer to store the file name in.
5709 */
drhc02a43a2012-01-10 23:18:38 +00005710 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005711 const char *zName = zPath;
5712
danielk1977fee2d252007-08-18 10:59:19 +00005713 /* Check the following statements are true:
5714 **
5715 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5716 ** (b) if CREATE is set, then READWRITE must also be set, and
5717 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005718 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005719 */
danielk1977b4b47412007-08-17 15:53:36 +00005720 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005721 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005722 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005723 assert(isDelete==0 || isCreate);
5724
danddb0ac42010-07-14 14:48:58 +00005725 /* The main DB, main journal, WAL file and master journal are never
5726 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005727 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5728 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5729 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005730 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005731
danielk1977fee2d252007-08-18 10:59:19 +00005732 /* Assert that the upper layer has set one of the "file-type" flags. */
5733 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5734 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5735 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005736 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005737 );
5738
drhb00d8622014-01-01 15:18:36 +00005739 /* Detect a pid change and reset the PRNG. There is a race condition
5740 ** here such that two or more threads all trying to open databases at
5741 ** the same instant might all reset the PRNG. But multiple resets
5742 ** are harmless.
5743 */
drh5ac93652015-03-21 20:59:43 +00005744 if( randomnessPid!=osGetpid(0) ){
5745 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005746 sqlite3_randomness(0,0);
5747 }
5748
dan08da86a2009-08-21 17:18:03 +00005749 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005750
dan08da86a2009-08-21 17:18:03 +00005751 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005752 UnixUnusedFd *pUnused;
5753 pUnused = findReusableFd(zName, flags);
5754 if( pUnused ){
5755 fd = pUnused->fd;
5756 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005757 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005758 if( !pUnused ){
5759 return SQLITE_NOMEM;
5760 }
5761 }
5762 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005763
5764 /* Database filenames are double-zero terminated if they are not
5765 ** URIs with parameters. Hence, they can always be passed into
5766 ** sqlite3_uri_parameter(). */
5767 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5768
dan08da86a2009-08-21 17:18:03 +00005769 }else if( !zName ){
5770 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005771 assert(isDelete && !syncDir);
drhc02a43a2012-01-10 23:18:38 +00005772 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005773 if( rc!=SQLITE_OK ){
5774 return rc;
5775 }
5776 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005777
5778 /* Generated temporary filenames are always double-zero terminated
5779 ** for use by sqlite3_uri_parameter(). */
5780 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005781 }
5782
dan08da86a2009-08-21 17:18:03 +00005783 /* Determine the value of the flags parameter passed to POSIX function
5784 ** open(). These must be calculated even if open() is not called, as
5785 ** they may be stored as part of the file handle and used by the
5786 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005787 if( isReadonly ) openFlags |= O_RDONLY;
5788 if( isReadWrite ) openFlags |= O_RDWR;
5789 if( isCreate ) openFlags |= O_CREAT;
5790 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5791 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005792
danielk1977b4b47412007-08-17 15:53:36 +00005793 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005794 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005795 uid_t uid; /* Userid for the file */
5796 gid_t gid; /* Groupid for the file */
5797 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005798 if( rc!=SQLITE_OK ){
5799 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005800 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005801 return rc;
5802 }
drhad4f1e52011-03-04 15:43:57 +00005803 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005804 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
dan08da86a2009-08-21 17:18:03 +00005805 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
5806 /* Failed to open the file for read/write access. Try read-only. */
5807 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005808 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005809 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005810 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005811 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005812 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005813 }
5814 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005815 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005816 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005817 }
drhac7c3ac2012-02-11 19:23:48 +00005818
5819 /* If this process is running as root and if creating a new rollback
5820 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005821 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005822 */
5823 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drhed466822012-05-31 13:10:49 +00005824 osFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005825 }
danielk1977b4b47412007-08-17 15:53:36 +00005826 }
dan08da86a2009-08-21 17:18:03 +00005827 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005828 if( pOutFlags ){
5829 *pOutFlags = flags;
5830 }
5831
dane946c392009-08-22 11:39:46 +00005832 if( p->pUnused ){
5833 p->pUnused->fd = fd;
5834 p->pUnused->flags = flags;
5835 }
5836
danielk1977b4b47412007-08-17 15:53:36 +00005837 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005838#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005839 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005840#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5841 zPath = sqlite3_mprintf("%s", zName);
5842 if( zPath==0 ){
5843 robust_close(p, fd, __LINE__);
5844 return SQLITE_NOMEM;
5845 }
chw97185482008-11-17 08:05:31 +00005846#else
drh036ac7f2011-08-08 23:18:05 +00005847 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005848#endif
danielk1977b4b47412007-08-17 15:53:36 +00005849 }
drh41022642008-11-21 00:24:42 +00005850#if SQLITE_ENABLE_LOCKING_STYLE
5851 else{
dan08da86a2009-08-21 17:18:03 +00005852 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005853 }
5854#endif
5855
drhda0e7682008-07-30 15:27:54 +00005856 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005857
drh7ed97b92010-01-20 13:07:21 +00005858
5859#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005860 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005861 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005862 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005863 return SQLITE_IOERR_ACCESS;
5864 }
5865 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5866 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5867 }
drh4bf66fd2015-02-19 02:43:02 +00005868 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5869 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5870 }
drh7ed97b92010-01-20 13:07:21 +00005871#endif
drhc02a43a2012-01-10 23:18:38 +00005872
5873 /* Set up appropriate ctrlFlags */
5874 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5875 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5876 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5877 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5878 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5879
drh7ed97b92010-01-20 13:07:21 +00005880#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005881#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005882 isAutoProxy = 1;
5883#endif
5884 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005885 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5886 int useProxy = 0;
5887
dan08da86a2009-08-21 17:18:03 +00005888 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5889 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005890 if( envforce!=NULL ){
5891 useProxy = atoi(envforce)>0;
5892 }else{
aswiftaebf4132008-11-21 00:10:35 +00005893 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5894 }
5895 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005896 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005897 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005898 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005899 if( rc!=SQLITE_OK ){
5900 /* Use unixClose to clean up the resources added in fillInUnixFile
5901 ** and clear all the structure's references. Specifically,
5902 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5903 */
5904 unixClose(pFile);
5905 return rc;
5906 }
aswiftaebf4132008-11-21 00:10:35 +00005907 }
dane946c392009-08-22 11:39:46 +00005908 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005909 }
5910 }
5911#endif
5912
drhc02a43a2012-01-10 23:18:38 +00005913 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5914
dane946c392009-08-22 11:39:46 +00005915open_finished:
5916 if( rc!=SQLITE_OK ){
5917 sqlite3_free(p->pUnused);
5918 }
5919 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005920}
5921
dane946c392009-08-22 11:39:46 +00005922
danielk1977b4b47412007-08-17 15:53:36 +00005923/*
danielk1977fee2d252007-08-18 10:59:19 +00005924** Delete the file at zPath. If the dirSync argument is true, fsync()
5925** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005926*/
drh6b9d6dd2008-12-03 19:34:47 +00005927static int unixDelete(
5928 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5929 const char *zPath, /* Name of file to be deleted */
5930 int dirSync /* If true, fsync() directory after deleting file */
5931){
danielk1977fee2d252007-08-18 10:59:19 +00005932 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005933 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005934 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005935 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005936 if( errno==ENOENT
5937#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005938 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005939#endif
5940 ){
dan9fc5b4a2012-11-09 20:17:26 +00005941 rc = SQLITE_IOERR_DELETE_NOENT;
5942 }else{
drhb4308162012-11-09 21:40:02 +00005943 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005944 }
drhb4308162012-11-09 21:40:02 +00005945 return rc;
drh5d4feff2010-07-14 01:45:22 +00005946 }
danielk1977d39fa702008-10-16 13:27:40 +00005947#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005948 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005949 int fd;
drh90315a22011-08-10 01:52:12 +00005950 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005951 if( rc==SQLITE_OK ){
drh6c7d5c52008-11-21 20:32:33 +00005952#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005953 if( fsync(fd)==-1 )
5954#else
5955 if( fsync(fd) )
5956#endif
5957 {
dane18d4952011-02-21 11:46:24 +00005958 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005959 }
drh0e9365c2011-03-02 02:08:13 +00005960 robust_close(0, fd, __LINE__);
drh1ee6f742011-08-23 20:11:32 +00005961 }else if( rc==SQLITE_CANTOPEN ){
5962 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005963 }
5964 }
danielk1977d138dd82008-10-15 16:02:48 +00005965#endif
danielk1977fee2d252007-08-18 10:59:19 +00005966 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005967}
5968
danielk197790949c22007-08-17 16:50:38 +00005969/*
mistachkin48864df2013-03-21 21:20:32 +00005970** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005971** test performed depends on the value of flags:
5972**
5973** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5974** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5975** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5976**
5977** Otherwise return 0.
5978*/
danielk1977861f7452008-06-05 11:39:11 +00005979static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005980 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5981 const char *zPath, /* Path of the file to examine */
5982 int flags, /* What do we want to learn about the zPath file? */
5983 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005984){
rse25c0d1a2007-09-20 08:38:14 +00005985 int amode = 0;
danielk1977397d65f2008-11-19 11:35:39 +00005986 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005987 SimulateIOError( return SQLITE_IOERR_ACCESS; );
danielk1977b4b47412007-08-17 15:53:36 +00005988 switch( flags ){
5989 case SQLITE_ACCESS_EXISTS:
5990 amode = F_OK;
5991 break;
5992 case SQLITE_ACCESS_READWRITE:
5993 amode = W_OK|R_OK;
5994 break;
drh50d3f902007-08-27 21:10:36 +00005995 case SQLITE_ACCESS_READ:
danielk1977b4b47412007-08-17 15:53:36 +00005996 amode = R_OK;
5997 break;
5998
5999 default:
6000 assert(!"Invalid flags argument");
6001 }
drh99ab3b12011-03-02 15:09:07 +00006002 *pResOut = (osAccess(zPath, amode)==0);
dan83acd422010-06-18 11:10:06 +00006003 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
6004 struct stat buf;
drh58384f12011-07-28 00:14:45 +00006005 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
dan83acd422010-06-18 11:10:06 +00006006 *pResOut = 0;
6007 }
6008 }
danielk1977861f7452008-06-05 11:39:11 +00006009 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006010}
6011
danielk1977b4b47412007-08-17 15:53:36 +00006012
6013/*
6014** Turn a relative pathname into a full pathname. The relative path
6015** is stored as a nul-terminated string in the buffer pointed to by
6016** zPath.
6017**
6018** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6019** (in this case, MAX_PATHNAME bytes). The full-path is written to
6020** this buffer before returning.
6021*/
danielk1977adfb9b02007-09-17 07:02:56 +00006022static int unixFullPathname(
6023 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6024 const char *zPath, /* Possibly relative input path */
6025 int nOut, /* Size of output buffer in bytes */
6026 char *zOut /* Output buffer */
6027){
danielk1977843e65f2007-09-01 16:16:15 +00006028
6029 /* It's odd to simulate an io-error here, but really this is just
6030 ** using the io-error infrastructure to test that SQLite handles this
6031 ** function failing. This function could fail if, for example, the
drh6b9d6dd2008-12-03 19:34:47 +00006032 ** current working directory has been unlinked.
danielk1977843e65f2007-09-01 16:16:15 +00006033 */
6034 SimulateIOError( return SQLITE_ERROR );
6035
drh153c62c2007-08-24 03:51:33 +00006036 assert( pVfs->mxPathname==MAX_PATHNAME );
danielk1977f3d3c272008-11-19 16:52:44 +00006037 UNUSED_PARAMETER(pVfs);
chw97185482008-11-17 08:05:31 +00006038
drh3c7f2dc2007-12-06 13:26:20 +00006039 zOut[nOut-1] = '\0';
danielk1977b4b47412007-08-17 15:53:36 +00006040 if( zPath[0]=='/' ){
drh3c7f2dc2007-12-06 13:26:20 +00006041 sqlite3_snprintf(nOut, zOut, "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006042 }else{
6043 int nCwd;
drh99ab3b12011-03-02 15:09:07 +00006044 if( osGetcwd(zOut, nOut-1)==0 ){
dane18d4952011-02-21 11:46:24 +00006045 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006046 }
drhea678832008-12-10 19:26:22 +00006047 nCwd = (int)strlen(zOut);
drh3c7f2dc2007-12-06 13:26:20 +00006048 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006049 }
6050 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006051}
6052
drh0ccebe72005-06-07 22:22:50 +00006053
drh761df872006-12-21 01:29:22 +00006054#ifndef SQLITE_OMIT_LOAD_EXTENSION
6055/*
6056** Interfaces for opening a shared library, finding entry points
6057** within the shared library, and closing the shared library.
6058*/
6059#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006060static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6061 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006062 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6063}
danielk197795c8a542007-09-01 06:51:27 +00006064
6065/*
6066** SQLite calls this function immediately after a call to unixDlSym() or
6067** unixDlOpen() fails (returns a null pointer). If a more detailed error
6068** message is available, it is written to zBufOut. If no error message
6069** is available, zBufOut is left unmodified and SQLite uses a default
6070** error message.
6071*/
danielk1977397d65f2008-11-19 11:35:39 +00006072static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006073 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006074 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006075 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006076 zErr = dlerror();
6077 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006078 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006079 }
drh6c7d5c52008-11-21 20:32:33 +00006080 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006081}
drh1875f7a2008-12-08 18:19:17 +00006082static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6083 /*
6084 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6085 ** cast into a pointer to a function. And yet the library dlsym() routine
6086 ** returns a void* which is really a pointer to a function. So how do we
6087 ** use dlsym() with -pedantic-errors?
6088 **
6089 ** Variable x below is defined to be a pointer to a function taking
6090 ** parameters void* and const char* and returning a pointer to a function.
6091 ** We initialize x by assigning it a pointer to the dlsym() function.
6092 ** (That assignment requires a cast.) Then we call the function that
6093 ** x points to.
6094 **
6095 ** This work-around is unlikely to work correctly on any system where
6096 ** you really cannot cast a function pointer into void*. But then, on the
6097 ** other hand, dlsym() will not work on such a system either, so we have
6098 ** not really lost anything.
6099 */
6100 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006101 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006102 x = (void(*(*)(void*,const char*))(void))dlsym;
6103 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006104}
danielk1977397d65f2008-11-19 11:35:39 +00006105static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6106 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006107 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006108}
danielk1977b4b47412007-08-17 15:53:36 +00006109#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6110 #define unixDlOpen 0
6111 #define unixDlError 0
6112 #define unixDlSym 0
6113 #define unixDlClose 0
6114#endif
6115
6116/*
danielk197790949c22007-08-17 16:50:38 +00006117** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006118*/
danielk1977397d65f2008-11-19 11:35:39 +00006119static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6120 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006121 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006122
drhbbd42a62004-05-22 17:41:58 +00006123 /* We have to initialize zBuf to prevent valgrind from reporting
6124 ** errors. The reports issued by valgrind are incorrect - we would
6125 ** prefer that the randomness be increased by making use of the
6126 ** uninitialized space in zBuf - but valgrind errors tend to worry
6127 ** some users. Rather than argue, it seems easier just to initialize
6128 ** the whole array and silence valgrind, even if that means less randomness
6129 ** in the random seed.
6130 **
6131 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006132 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006133 ** tests repeatable.
6134 */
danielk1977b4b47412007-08-17 15:53:36 +00006135 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006136 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006137#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006138 {
drhb00d8622014-01-01 15:18:36 +00006139 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006140 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006141 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006142 time_t t;
6143 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006144 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006145 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6146 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6147 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006148 }else{
drhc18b4042012-02-10 03:10:27 +00006149 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006150 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006151 }
drhbbd42a62004-05-22 17:41:58 +00006152 }
6153#endif
drh72cbd072008-10-14 17:58:38 +00006154 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006155}
6156
danielk1977b4b47412007-08-17 15:53:36 +00006157
drhbbd42a62004-05-22 17:41:58 +00006158/*
6159** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006160** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006161** The return value is the number of microseconds of sleep actually
6162** requested from the underlying operating system, a number which
6163** might be greater than or equal to the argument, but not less
6164** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006165*/
danielk1977397d65f2008-11-19 11:35:39 +00006166static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006167#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006168 struct timespec sp;
6169
6170 sp.tv_sec = microseconds / 1000000;
6171 sp.tv_nsec = (microseconds % 1000000) * 1000;
6172 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006173 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006174 return microseconds;
6175#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006176 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006177 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006178 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006179#else
danielk1977b4b47412007-08-17 15:53:36 +00006180 int seconds = (microseconds+999999)/1000000;
6181 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006182 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006183 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006184#endif
drh88f474a2006-01-02 20:00:12 +00006185}
6186
6187/*
drh6b9d6dd2008-12-03 19:34:47 +00006188** The following variable, if set to a non-zero value, is interpreted as
6189** the number of seconds since 1970 and is used to set the result of
6190** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006191*/
6192#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006193int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006194#endif
6195
6196/*
drhb7e8ea22010-05-03 14:32:30 +00006197** Find the current time (in Universal Coordinated Time). Write into *piNow
6198** the current time and date as a Julian Day number times 86_400_000. In
6199** other words, write into *piNow the number of milliseconds since the Julian
6200** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6201** proleptic Gregorian calendar.
6202**
drh31702252011-10-12 23:13:43 +00006203** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6204** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006205*/
6206static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6207 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006208 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006209#if defined(NO_GETTOD)
6210 time_t t;
6211 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006212 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006213#elif OS_VXWORKS
6214 struct timespec sNow;
6215 clock_gettime(CLOCK_REALTIME, &sNow);
6216 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6217#else
6218 struct timeval sNow;
drh31702252011-10-12 23:13:43 +00006219 if( gettimeofday(&sNow, 0)==0 ){
6220 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
6221 }else{
6222 rc = SQLITE_ERROR;
6223 }
drhb7e8ea22010-05-03 14:32:30 +00006224#endif
6225
6226#ifdef SQLITE_TEST
6227 if( sqlite3_current_time ){
6228 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6229 }
6230#endif
6231 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006232 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006233}
6234
6235/*
drhbbd42a62004-05-22 17:41:58 +00006236** Find the current time (in Universal Coordinated Time). Write the
6237** current time and date as a Julian Day number into *prNow and
6238** return 0. Return 1 if the time and date cannot be found.
6239*/
danielk1977397d65f2008-11-19 11:35:39 +00006240static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006241 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006242 int rc;
drhff828942010-06-26 21:34:06 +00006243 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006244 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006245 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006246 return rc;
drhbbd42a62004-05-22 17:41:58 +00006247}
danielk1977b4b47412007-08-17 15:53:36 +00006248
drh6b9d6dd2008-12-03 19:34:47 +00006249/*
6250** We added the xGetLastError() method with the intention of providing
6251** better low-level error messages when operating-system problems come up
6252** during SQLite operation. But so far, none of that has been implemented
6253** in the core. So this routine is never called. For now, it is merely
6254** a place-holder.
6255*/
danielk1977397d65f2008-11-19 11:35:39 +00006256static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6257 UNUSED_PARAMETER(NotUsed);
6258 UNUSED_PARAMETER(NotUsed2);
6259 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006260 return 0;
6261}
6262
drhf2424c52010-04-26 00:04:55 +00006263
6264/*
drh734c9862008-11-28 15:37:20 +00006265************************ End of sqlite3_vfs methods ***************************
6266******************************************************************************/
6267
drh715ff302008-12-03 22:32:44 +00006268/******************************************************************************
6269************************** Begin Proxy Locking ********************************
6270**
6271** Proxy locking is a "uber-locking-method" in this sense: It uses the
6272** other locking methods on secondary lock files. Proxy locking is a
6273** meta-layer over top of the primitive locking implemented above. For
6274** this reason, the division that implements of proxy locking is deferred
6275** until late in the file (here) after all of the other I/O methods have
6276** been defined - so that the primitive locking methods are available
6277** as services to help with the implementation of proxy locking.
6278**
6279****
6280**
6281** The default locking schemes in SQLite use byte-range locks on the
6282** database file to coordinate safe, concurrent access by multiple readers
6283** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6284** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6285** as POSIX read & write locks over fixed set of locations (via fsctl),
6286** on AFP and SMB only exclusive byte-range locks are available via fsctl
6287** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6288** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6289** address in the shared range is taken for a SHARED lock, the entire
6290** shared range is taken for an EXCLUSIVE lock):
6291**
drhf2f105d2012-08-20 15:53:54 +00006292** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006293** RESERVED_BYTE 0x40000001
6294** SHARED_RANGE 0x40000002 -> 0x40000200
6295**
6296** This works well on the local file system, but shows a nearly 100x
6297** slowdown in read performance on AFP because the AFP client disables
6298** the read cache when byte-range locks are present. Enabling the read
6299** cache exposes a cache coherency problem that is present on all OS X
6300** supported network file systems. NFS and AFP both observe the
6301** close-to-open semantics for ensuring cache coherency
6302** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6303** address the requirements for concurrent database access by multiple
6304** readers and writers
6305** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6306**
6307** To address the performance and cache coherency issues, proxy file locking
6308** changes the way database access is controlled by limiting access to a
6309** single host at a time and moving file locks off of the database file
6310** and onto a proxy file on the local file system.
6311**
6312**
6313** Using proxy locks
6314** -----------------
6315**
6316** C APIs
6317**
drh4bf66fd2015-02-19 02:43:02 +00006318** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006319** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006320** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6321** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006322**
6323**
6324** SQL pragmas
6325**
6326** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6327** PRAGMA [database.]lock_proxy_file
6328**
6329** Specifying ":auto:" means that if there is a conch file with a matching
6330** host ID in it, the proxy path in the conch file will be used, otherwise
6331** a proxy path based on the user's temp dir
6332** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6333** actual proxy file name is generated from the name and path of the
6334** database file. For example:
6335**
6336** For database path "/Users/me/foo.db"
6337** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6338**
6339** Once a lock proxy is configured for a database connection, it can not
6340** be removed, however it may be switched to a different proxy path via
6341** the above APIs (assuming the conch file is not being held by another
6342** connection or process).
6343**
6344**
6345** How proxy locking works
6346** -----------------------
6347**
6348** Proxy file locking relies primarily on two new supporting files:
6349**
6350** * conch file to limit access to the database file to a single host
6351** at a time
6352**
6353** * proxy file to act as a proxy for the advisory locks normally
6354** taken on the database
6355**
6356** The conch file - to use a proxy file, sqlite must first "hold the conch"
6357** by taking an sqlite-style shared lock on the conch file, reading the
6358** contents and comparing the host's unique host ID (see below) and lock
6359** proxy path against the values stored in the conch. The conch file is
6360** stored in the same directory as the database file and the file name
6361** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006362** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006363** host ID and/or proxy path, then the lock is escalated to an exclusive
6364** lock and the conch file contents is updated with the host ID and proxy
6365** path and the lock is downgraded to a shared lock again. If the conch
6366** is held by another process (with a shared lock), the exclusive lock
6367** will fail and SQLITE_BUSY is returned.
6368**
6369** The proxy file - a single-byte file used for all advisory file locks
6370** normally taken on the database file. This allows for safe sharing
6371** of the database file for multiple readers and writers on the same
6372** host (the conch ensures that they all use the same local lock file).
6373**
drh715ff302008-12-03 22:32:44 +00006374** Requesting the lock proxy does not immediately take the conch, it is
6375** only taken when the first request to lock database file is made.
6376** This matches the semantics of the traditional locking behavior, where
6377** opening a connection to a database file does not take a lock on it.
6378** The shared lock and an open file descriptor are maintained until
6379** the connection to the database is closed.
6380**
6381** The proxy file and the lock file are never deleted so they only need
6382** to be created the first time they are used.
6383**
6384** Configuration options
6385** ---------------------
6386**
6387** SQLITE_PREFER_PROXY_LOCKING
6388**
6389** Database files accessed on non-local file systems are
6390** automatically configured for proxy locking, lock files are
6391** named automatically using the same logic as
6392** PRAGMA lock_proxy_file=":auto:"
6393**
6394** SQLITE_PROXY_DEBUG
6395**
6396** Enables the logging of error messages during host id file
6397** retrieval and creation
6398**
drh715ff302008-12-03 22:32:44 +00006399** LOCKPROXYDIR
6400**
6401** Overrides the default directory used for lock proxy files that
6402** are named automatically via the ":auto:" setting
6403**
6404** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6405**
6406** Permissions to use when creating a directory for storing the
6407** lock proxy files, only used when LOCKPROXYDIR is not set.
6408**
6409**
6410** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6411** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6412** force proxy locking to be used for every database file opened, and 0
6413** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006414** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006415** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6416*/
6417
6418/*
6419** Proxy locking is only available on MacOSX
6420*/
drhd2cb50b2009-01-09 21:41:17 +00006421#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006422
drh715ff302008-12-03 22:32:44 +00006423/*
6424** The proxyLockingContext has the path and file structures for the remote
6425** and local proxy files in it
6426*/
6427typedef struct proxyLockingContext proxyLockingContext;
6428struct proxyLockingContext {
6429 unixFile *conchFile; /* Open conch file */
6430 char *conchFilePath; /* Name of the conch file */
6431 unixFile *lockProxy; /* Open proxy lock file */
6432 char *lockProxyPath; /* Name of the proxy lock file */
6433 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006434 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006435 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006436 void *oldLockingContext; /* Original lockingcontext to restore on close */
6437 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6438};
6439
drh7ed97b92010-01-20 13:07:21 +00006440/*
6441** The proxy lock file path for the database at dbPath is written into lPath,
6442** which must point to valid, writable memory large enough for a maxLen length
6443** file path.
drh715ff302008-12-03 22:32:44 +00006444*/
drh715ff302008-12-03 22:32:44 +00006445static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6446 int len;
6447 int dbLen;
6448 int i;
6449
6450#ifdef LOCKPROXYDIR
6451 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6452#else
6453# ifdef _CS_DARWIN_USER_TEMP_DIR
6454 {
drh7ed97b92010-01-20 13:07:21 +00006455 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006456 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006457 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006458 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006459 }
drh7ed97b92010-01-20 13:07:21 +00006460 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006461 }
6462# else
6463 len = strlcpy(lPath, "/tmp/", maxLen);
6464# endif
6465#endif
6466
6467 if( lPath[len-1]!='/' ){
6468 len = strlcat(lPath, "/", maxLen);
6469 }
6470
6471 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006472 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006473 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006474 char c = dbPath[i];
6475 lPath[i+len] = (c=='/')?'_':c;
6476 }
6477 lPath[i+len]='\0';
6478 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006479 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006480 return SQLITE_OK;
6481}
6482
drh7ed97b92010-01-20 13:07:21 +00006483/*
6484 ** Creates the lock file and any missing directories in lockPath
6485 */
6486static int proxyCreateLockPath(const char *lockPath){
6487 int i, len;
6488 char buf[MAXPATHLEN];
6489 int start = 0;
6490
6491 assert(lockPath!=NULL);
6492 /* try to create all the intermediate directories */
6493 len = (int)strlen(lockPath);
6494 buf[0] = lockPath[0];
6495 for( i=1; i<len; i++ ){
6496 if( lockPath[i] == '/' && (i - start > 0) ){
6497 /* only mkdir if leaf dir != "." or "/" or ".." */
6498 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6499 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6500 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006501 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006502 int err=errno;
6503 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006504 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006505 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006506 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006507 return err;
6508 }
6509 }
6510 }
6511 start=i+1;
6512 }
6513 buf[i] = lockPath[i];
6514 }
drh5ac93652015-03-21 20:59:43 +00006515 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006516 return 0;
6517}
6518
drh715ff302008-12-03 22:32:44 +00006519/*
6520** Create a new VFS file descriptor (stored in memory obtained from
6521** sqlite3_malloc) and open the file named "path" in the file descriptor.
6522**
6523** The caller is responsible not only for closing the file descriptor
6524** but also for freeing the memory associated with the file descriptor.
6525*/
drh7ed97b92010-01-20 13:07:21 +00006526static int proxyCreateUnixFile(
6527 const char *path, /* path for the new unixFile */
6528 unixFile **ppFile, /* unixFile created and returned by ref */
6529 int islockfile /* if non zero missing dirs will be created */
6530) {
6531 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006532 unixFile *pNew;
6533 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006534 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006535 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006536 int terrno = 0;
6537 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006538
drh7ed97b92010-01-20 13:07:21 +00006539 /* 1. first try to open/create the file
6540 ** 2. if that fails, and this is a lock file (not-conch), try creating
6541 ** the parent directories and then try again.
6542 ** 3. if that fails, try to open the file read-only
6543 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6544 */
6545 pUnused = findReusableFd(path, openFlags);
6546 if( pUnused ){
6547 fd = pUnused->fd;
6548 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006549 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006550 if( !pUnused ){
6551 return SQLITE_NOMEM;
6552 }
6553 }
6554 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006555 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006556 terrno = errno;
6557 if( fd<0 && errno==ENOENT && islockfile ){
6558 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006559 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006560 }
6561 }
6562 }
6563 if( fd<0 ){
6564 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006565 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006566 terrno = errno;
6567 }
6568 if( fd<0 ){
6569 if( islockfile ){
6570 return SQLITE_BUSY;
6571 }
6572 switch (terrno) {
6573 case EACCES:
6574 return SQLITE_PERM;
6575 case EIO:
6576 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6577 default:
drh9978c972010-02-23 17:36:32 +00006578 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006579 }
6580 }
6581
drhf3cdcdc2015-04-29 16:50:28 +00006582 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006583 if( pNew==NULL ){
6584 rc = SQLITE_NOMEM;
6585 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006586 }
6587 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006588 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006589 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006590 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006591 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006592 pUnused->fd = fd;
6593 pUnused->flags = openFlags;
6594 pNew->pUnused = pUnused;
6595
drhc02a43a2012-01-10 23:18:38 +00006596 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006597 if( rc==SQLITE_OK ){
6598 *ppFile = pNew;
6599 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006600 }
drh7ed97b92010-01-20 13:07:21 +00006601end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006602 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006603 sqlite3_free(pNew);
6604 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006605 return rc;
6606}
6607
drh7ed97b92010-01-20 13:07:21 +00006608#ifdef SQLITE_TEST
6609/* simulate multiple hosts by creating unique hostid file paths */
6610int sqlite3_hostid_num = 0;
6611#endif
6612
6613#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6614
drh6bca6512015-04-13 23:05:28 +00006615#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006616/* Not always defined in the headers as it ought to be */
6617extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006618#endif
drh0ab216a2010-07-02 17:10:40 +00006619
drh7ed97b92010-01-20 13:07:21 +00006620/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6621** bytes of writable memory.
6622*/
6623static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006624 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6625 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006626#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006627 {
drh4bf66fd2015-02-19 02:43:02 +00006628 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006629 if( gethostuuid(pHostID, &timeout) ){
6630 int err = errno;
6631 if( pError ){
6632 *pError = err;
6633 }
6634 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006635 }
drh7ed97b92010-01-20 13:07:21 +00006636 }
drh3d4435b2011-08-26 20:55:50 +00006637#else
6638 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006639#endif
drh7ed97b92010-01-20 13:07:21 +00006640#ifdef SQLITE_TEST
6641 /* simulate multiple hosts by creating unique hostid file paths */
6642 if( sqlite3_hostid_num != 0){
6643 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6644 }
6645#endif
6646
6647 return SQLITE_OK;
6648}
6649
6650/* The conch file contains the header, host id and lock file path
6651 */
6652#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6653#define PROXY_HEADERLEN 1 /* conch file header length */
6654#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6655#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6656
6657/*
6658** Takes an open conch file, copies the contents to a new path and then moves
6659** it back. The newly created file's file descriptor is assigned to the
6660** conch file structure and finally the original conch file descriptor is
6661** closed. Returns zero if successful.
6662*/
6663static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6664 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6665 unixFile *conchFile = pCtx->conchFile;
6666 char tPath[MAXPATHLEN];
6667 char buf[PROXY_MAXCONCHLEN];
6668 char *cPath = pCtx->conchFilePath;
6669 size_t readLen = 0;
6670 size_t pathLen = 0;
6671 char errmsg[64] = "";
6672 int fd = -1;
6673 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006674 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006675
6676 /* create a new path by replace the trailing '-conch' with '-break' */
6677 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6678 if( pathLen>MAXPATHLEN || pathLen<6 ||
6679 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006680 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006681 goto end_breaklock;
6682 }
6683 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006684 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006685 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006686 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006687 goto end_breaklock;
6688 }
6689 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006690 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006691 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006692 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006693 goto end_breaklock;
6694 }
drhe562be52011-03-02 18:01:10 +00006695 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006696 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006697 goto end_breaklock;
6698 }
6699 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006700 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006701 goto end_breaklock;
6702 }
6703 rc = 0;
6704 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006705 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006706 conchFile->h = fd;
6707 conchFile->openFlags = O_RDWR | O_CREAT;
6708
6709end_breaklock:
6710 if( rc ){
6711 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006712 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006713 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006714 }
6715 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6716 }
6717 return rc;
6718}
6719
6720/* Take the requested lock on the conch file and break a stale lock if the
6721** host id matches.
6722*/
6723static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6724 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6725 unixFile *conchFile = pCtx->conchFile;
6726 int rc = SQLITE_OK;
6727 int nTries = 0;
6728 struct timespec conchModTime;
6729
drh3d4435b2011-08-26 20:55:50 +00006730 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006731 do {
6732 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6733 nTries ++;
6734 if( rc==SQLITE_BUSY ){
6735 /* If the lock failed (busy):
6736 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6737 * 2nd try: fail if the mod time changed or host id is different, wait
6738 * 10 sec and try again
6739 * 3rd try: break the lock unless the mod time has changed.
6740 */
6741 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006742 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006743 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006744 return SQLITE_IOERR_LOCK;
6745 }
6746
6747 if( nTries==1 ){
6748 conchModTime = buf.st_mtimespec;
6749 usleep(500000); /* wait 0.5 sec and try the lock again*/
6750 continue;
6751 }
6752
6753 assert( nTries>1 );
6754 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6755 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6756 return SQLITE_BUSY;
6757 }
6758
6759 if( nTries==2 ){
6760 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006761 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006762 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006763 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006764 return SQLITE_IOERR_LOCK;
6765 }
6766 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6767 /* don't break the lock if the host id doesn't match */
6768 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6769 return SQLITE_BUSY;
6770 }
6771 }else{
6772 /* don't break the lock on short read or a version mismatch */
6773 return SQLITE_BUSY;
6774 }
6775 usleep(10000000); /* wait 10 sec and try the lock again */
6776 continue;
6777 }
6778
6779 assert( nTries==3 );
6780 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6781 rc = SQLITE_OK;
6782 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006783 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006784 }
6785 if( !rc ){
6786 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6787 }
6788 }
6789 }
6790 } while( rc==SQLITE_BUSY && nTries<3 );
6791
6792 return rc;
6793}
6794
6795/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006796** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6797** lockPath means that the lockPath in the conch file will be used if the
6798** host IDs match, or a new lock path will be generated automatically
6799** and written to the conch file.
6800*/
6801static int proxyTakeConch(unixFile *pFile){
6802 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6803
drh7ed97b92010-01-20 13:07:21 +00006804 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006805 return SQLITE_OK;
6806 }else{
6807 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006808 uuid_t myHostID;
6809 int pError = 0;
6810 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006811 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006812 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006813 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006814 int createConch = 0;
6815 int hostIdMatch = 0;
6816 int readLen = 0;
6817 int tryOldLockPath = 0;
6818 int forceNewLockPath = 0;
6819
drh308c2a52010-05-14 11:30:18 +00006820 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006821 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006822 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006823
drh7ed97b92010-01-20 13:07:21 +00006824 rc = proxyGetHostID(myHostID, &pError);
6825 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006826 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006827 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006828 }
drh7ed97b92010-01-20 13:07:21 +00006829 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006830 if( rc!=SQLITE_OK ){
6831 goto end_takeconch;
6832 }
drh7ed97b92010-01-20 13:07:21 +00006833 /* read the existing conch file */
6834 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6835 if( readLen<0 ){
6836 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006837 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006838 rc = SQLITE_IOERR_READ;
6839 goto end_takeconch;
6840 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6841 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6842 /* a short read or version format mismatch means we need to create a new
6843 ** conch file.
6844 */
6845 createConch = 1;
6846 }
6847 /* if the host id matches and the lock path already exists in the conch
6848 ** we'll try to use the path there, if we can't open that path, we'll
6849 ** retry with a new auto-generated path
6850 */
6851 do { /* in case we need to try again for an :auto: named lock file */
6852
6853 if( !createConch && !forceNewLockPath ){
6854 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6855 PROXY_HOSTIDLEN);
6856 /* if the conch has data compare the contents */
6857 if( !pCtx->lockProxyPath ){
6858 /* for auto-named local lock file, just check the host ID and we'll
6859 ** use the local lock file path that's already in there
6860 */
6861 if( hostIdMatch ){
6862 size_t pathLen = (readLen - PROXY_PATHINDEX);
6863
6864 if( pathLen>=MAXPATHLEN ){
6865 pathLen=MAXPATHLEN-1;
6866 }
6867 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6868 lockPath[pathLen] = 0;
6869 tempLockPath = lockPath;
6870 tryOldLockPath = 1;
6871 /* create a copy of the lock path if the conch is taken */
6872 goto end_takeconch;
6873 }
6874 }else if( hostIdMatch
6875 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6876 readLen-PROXY_PATHINDEX)
6877 ){
6878 /* conch host and lock path match */
6879 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006880 }
drh7ed97b92010-01-20 13:07:21 +00006881 }
6882
6883 /* if the conch isn't writable and doesn't match, we can't take it */
6884 if( (conchFile->openFlags&O_RDWR) == 0 ){
6885 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006886 goto end_takeconch;
6887 }
drh7ed97b92010-01-20 13:07:21 +00006888
6889 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006890 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006891 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6892 tempLockPath = lockPath;
6893 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006894 }
drh7ed97b92010-01-20 13:07:21 +00006895
6896 /* update conch with host and path (this will fail if other process
6897 ** has a shared lock already), if the host id matches, use the big
6898 ** stick.
drh715ff302008-12-03 22:32:44 +00006899 */
drh7ed97b92010-01-20 13:07:21 +00006900 futimes(conchFile->h, NULL);
6901 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006902 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006903 /* We are trying for an exclusive lock but another thread in this
6904 ** same process is still holding a shared lock. */
6905 rc = SQLITE_BUSY;
6906 } else {
6907 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006908 }
drh715ff302008-12-03 22:32:44 +00006909 }else{
drh4bf66fd2015-02-19 02:43:02 +00006910 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006911 }
drh7ed97b92010-01-20 13:07:21 +00006912 if( rc==SQLITE_OK ){
6913 char writeBuffer[PROXY_MAXCONCHLEN];
6914 int writeSize = 0;
6915
6916 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6917 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6918 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006919 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6920 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006921 }else{
6922 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6923 }
6924 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006925 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006926 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
6927 fsync(conchFile->h);
6928 /* If we created a new conch file (not just updated the contents of a
6929 ** valid conch file), try to match the permissions of the database
6930 */
6931 if( rc==SQLITE_OK && createConch ){
6932 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006933 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006934 if( err==0 ){
6935 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6936 S_IROTH|S_IWOTH);
6937 /* try to match the database file R/W permissions, ignore failure */
6938#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006939 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006940#else
drhff812312011-02-23 13:33:46 +00006941 do{
drhe562be52011-03-02 18:01:10 +00006942 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006943 }while( rc==(-1) && errno==EINTR );
6944 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006945 int code = errno;
6946 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6947 cmode, code, strerror(code));
6948 } else {
6949 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6950 }
6951 }else{
6952 int code = errno;
6953 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6954 err, code, strerror(code));
6955#endif
6956 }
drh715ff302008-12-03 22:32:44 +00006957 }
6958 }
drh7ed97b92010-01-20 13:07:21 +00006959 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6960
6961 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006962 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006963 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006964 int fd;
drh7ed97b92010-01-20 13:07:21 +00006965 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006966 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006967 }
6968 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006969 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006970 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006971 if( fd>=0 ){
6972 pFile->h = fd;
6973 }else{
drh9978c972010-02-23 17:36:32 +00006974 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006975 during locking */
6976 }
6977 }
6978 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6979 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
6980 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
6981 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
6982 /* we couldn't create the proxy lock file with the old lock file path
6983 ** so try again via auto-naming
6984 */
6985 forceNewLockPath = 1;
6986 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00006987 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00006988 }
6989 }
6990 if( rc==SQLITE_OK ){
6991 /* Need to make a copy of path if we extracted the value
6992 ** from the conch file or the path was allocated on the stack
6993 */
6994 if( tempLockPath ){
6995 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
6996 if( !pCtx->lockProxyPath ){
6997 rc = SQLITE_NOMEM;
6998 }
6999 }
7000 }
7001 if( rc==SQLITE_OK ){
7002 pCtx->conchHeld = 1;
7003
7004 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7005 afpLockingContext *afpCtx;
7006 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7007 afpCtx->dbPath = pCtx->lockProxyPath;
7008 }
7009 } else {
7010 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7011 }
drh308c2a52010-05-14 11:30:18 +00007012 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7013 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007014 return rc;
drh308c2a52010-05-14 11:30:18 +00007015 } while (1); /* in case we need to retry the :auto: lock file -
7016 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007017 }
7018}
7019
7020/*
7021** If pFile holds a lock on a conch file, then release that lock.
7022*/
7023static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007024 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007025 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7026 unixFile *conchFile; /* Name of the conch file */
7027
7028 pCtx = (proxyLockingContext *)pFile->lockingContext;
7029 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007030 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007031 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007032 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007033 if( pCtx->conchHeld>0 ){
7034 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7035 }
drh715ff302008-12-03 22:32:44 +00007036 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007037 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7038 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007039 return rc;
7040}
7041
7042/*
7043** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007044** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007045** Make *pConchPath point to the new name. Return SQLITE_OK on success
7046** or SQLITE_NOMEM if unable to obtain memory.
7047**
7048** The caller is responsible for ensuring that the allocated memory
7049** space is eventually freed.
7050**
7051** *pConchPath is set to NULL if a memory allocation error occurs.
7052*/
7053static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7054 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007055 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007056 char *conchPath; /* buffer in which to construct conch name */
7057
7058 /* Allocate space for the conch filename and initialize the name to
7059 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007060 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007061 if( conchPath==0 ){
7062 return SQLITE_NOMEM;
7063 }
7064 memcpy(conchPath, dbPath, len+1);
7065
7066 /* now insert a "." before the last / character */
7067 for( i=(len-1); i>=0; i-- ){
7068 if( conchPath[i]=='/' ){
7069 i++;
7070 break;
7071 }
7072 }
7073 conchPath[i]='.';
7074 while ( i<len ){
7075 conchPath[i+1]=dbPath[i];
7076 i++;
7077 }
7078
7079 /* append the "-conch" suffix to the file */
7080 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007081 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007082
7083 return SQLITE_OK;
7084}
7085
7086
7087/* Takes a fully configured proxy locking-style unix file and switches
7088** the local lock file path
7089*/
7090static int switchLockProxyPath(unixFile *pFile, const char *path) {
7091 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7092 char *oldPath = pCtx->lockProxyPath;
7093 int rc = SQLITE_OK;
7094
drh308c2a52010-05-14 11:30:18 +00007095 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007096 return SQLITE_BUSY;
7097 }
7098
7099 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7100 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7101 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7102 return SQLITE_OK;
7103 }else{
7104 unixFile *lockProxy = pCtx->lockProxy;
7105 pCtx->lockProxy=NULL;
7106 pCtx->conchHeld = 0;
7107 if( lockProxy!=NULL ){
7108 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7109 if( rc ) return rc;
7110 sqlite3_free(lockProxy);
7111 }
7112 sqlite3_free(oldPath);
7113 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7114 }
7115
7116 return rc;
7117}
7118
7119/*
7120** pFile is a file that has been opened by a prior xOpen call. dbPath
7121** is a string buffer at least MAXPATHLEN+1 characters in size.
7122**
7123** This routine find the filename associated with pFile and writes it
7124** int dbPath.
7125*/
7126static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007127#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007128 if( pFile->pMethod == &afpIoMethods ){
7129 /* afp style keeps a reference to the db path in the filePath field
7130 ** of the struct */
drhea678832008-12-10 19:26:22 +00007131 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007132 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7133 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007134 } else
drh715ff302008-12-03 22:32:44 +00007135#endif
7136 if( pFile->pMethod == &dotlockIoMethods ){
7137 /* dot lock style uses the locking context to store the dot lock
7138 ** file path */
7139 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7140 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7141 }else{
7142 /* all other styles use the locking context to store the db file path */
7143 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007144 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007145 }
7146 return SQLITE_OK;
7147}
7148
7149/*
7150** Takes an already filled in unix file and alters it so all file locking
7151** will be performed on the local proxy lock file. The following fields
7152** are preserved in the locking context so that they can be restored and
7153** the unix structure properly cleaned up at close time:
7154** ->lockingContext
7155** ->pMethod
7156*/
7157static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7158 proxyLockingContext *pCtx;
7159 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7160 char *lockPath=NULL;
7161 int rc = SQLITE_OK;
7162
drh308c2a52010-05-14 11:30:18 +00007163 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007164 return SQLITE_BUSY;
7165 }
7166 proxyGetDbPathForUnixFile(pFile, dbPath);
7167 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7168 lockPath=NULL;
7169 }else{
7170 lockPath=(char *)path;
7171 }
7172
drh308c2a52010-05-14 11:30:18 +00007173 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007174 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007175
drhf3cdcdc2015-04-29 16:50:28 +00007176 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007177 if( pCtx==0 ){
7178 return SQLITE_NOMEM;
7179 }
7180 memset(pCtx, 0, sizeof(*pCtx));
7181
7182 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7183 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007184 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7185 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7186 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7187 ** (c) the file system is read-only, then enable no-locking access.
7188 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7189 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7190 */
7191 struct statfs fsInfo;
7192 struct stat conchInfo;
7193 int goLockless = 0;
7194
drh99ab3b12011-03-02 15:09:07 +00007195 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007196 int err = errno;
7197 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7198 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7199 }
7200 }
7201 if( goLockless ){
7202 pCtx->conchHeld = -1; /* read only FS/ lockless */
7203 rc = SQLITE_OK;
7204 }
7205 }
drh715ff302008-12-03 22:32:44 +00007206 }
7207 if( rc==SQLITE_OK && lockPath ){
7208 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7209 }
7210
7211 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007212 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7213 if( pCtx->dbPath==NULL ){
7214 rc = SQLITE_NOMEM;
7215 }
7216 }
7217 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007218 /* all memory is allocated, proxys are created and assigned,
7219 ** switch the locking context and pMethod then return.
7220 */
drh715ff302008-12-03 22:32:44 +00007221 pCtx->oldLockingContext = pFile->lockingContext;
7222 pFile->lockingContext = pCtx;
7223 pCtx->pOldMethod = pFile->pMethod;
7224 pFile->pMethod = &proxyIoMethods;
7225 }else{
7226 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007227 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007228 sqlite3_free(pCtx->conchFile);
7229 }
drhd56b1212010-08-11 06:14:15 +00007230 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007231 sqlite3_free(pCtx->conchFilePath);
7232 sqlite3_free(pCtx);
7233 }
drh308c2a52010-05-14 11:30:18 +00007234 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7235 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007236 return rc;
7237}
7238
7239
7240/*
7241** This routine handles sqlite3_file_control() calls that are specific
7242** to proxy locking.
7243*/
7244static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7245 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007246 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007247 unixFile *pFile = (unixFile*)id;
7248 if( pFile->pMethod == &proxyIoMethods ){
7249 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7250 proxyTakeConch(pFile);
7251 if( pCtx->lockProxyPath ){
7252 *(const char **)pArg = pCtx->lockProxyPath;
7253 }else{
7254 *(const char **)pArg = ":auto: (not held)";
7255 }
7256 } else {
7257 *(const char **)pArg = NULL;
7258 }
7259 return SQLITE_OK;
7260 }
drh4bf66fd2015-02-19 02:43:02 +00007261 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007262 unixFile *pFile = (unixFile*)id;
7263 int rc = SQLITE_OK;
7264 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7265 if( pArg==NULL || (const char *)pArg==0 ){
7266 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007267 /* turn off proxy locking - not supported. If support is added for
7268 ** switching proxy locking mode off then it will need to fail if
7269 ** the journal mode is WAL mode.
7270 */
drh715ff302008-12-03 22:32:44 +00007271 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7272 }else{
7273 /* turn off proxy locking - already off - NOOP */
7274 rc = SQLITE_OK;
7275 }
7276 }else{
7277 const char *proxyPath = (const char *)pArg;
7278 if( isProxyStyle ){
7279 proxyLockingContext *pCtx =
7280 (proxyLockingContext*)pFile->lockingContext;
7281 if( !strcmp(pArg, ":auto:")
7282 || (pCtx->lockProxyPath &&
7283 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7284 ){
7285 rc = SQLITE_OK;
7286 }else{
7287 rc = switchLockProxyPath(pFile, proxyPath);
7288 }
7289 }else{
7290 /* turn on proxy file locking */
7291 rc = proxyTransformUnixFile(pFile, proxyPath);
7292 }
7293 }
7294 return rc;
7295 }
7296 default: {
7297 assert( 0 ); /* The call assures that only valid opcodes are sent */
7298 }
7299 }
7300 /*NOTREACHED*/
7301 return SQLITE_ERROR;
7302}
7303
7304/*
7305** Within this division (the proxying locking implementation) the procedures
7306** above this point are all utilities. The lock-related methods of the
7307** proxy-locking sqlite3_io_method object follow.
7308*/
7309
7310
7311/*
7312** This routine checks if there is a RESERVED lock held on the specified
7313** file by this or any other process. If such a lock is held, set *pResOut
7314** to a non-zero value otherwise *pResOut is set to zero. The return value
7315** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7316*/
7317static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7318 unixFile *pFile = (unixFile*)id;
7319 int rc = proxyTakeConch(pFile);
7320 if( rc==SQLITE_OK ){
7321 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007322 if( pCtx->conchHeld>0 ){
7323 unixFile *proxy = pCtx->lockProxy;
7324 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7325 }else{ /* conchHeld < 0 is lockless */
7326 pResOut=0;
7327 }
drh715ff302008-12-03 22:32:44 +00007328 }
7329 return rc;
7330}
7331
7332/*
drh308c2a52010-05-14 11:30:18 +00007333** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007334** of the following:
7335**
7336** (1) SHARED_LOCK
7337** (2) RESERVED_LOCK
7338** (3) PENDING_LOCK
7339** (4) EXCLUSIVE_LOCK
7340**
7341** Sometimes when requesting one lock state, additional lock states
7342** are inserted in between. The locking might fail on one of the later
7343** transitions leaving the lock state different from what it started but
7344** still short of its goal. The following chart shows the allowed
7345** transitions and the inserted intermediate states:
7346**
7347** UNLOCKED -> SHARED
7348** SHARED -> RESERVED
7349** SHARED -> (PENDING) -> EXCLUSIVE
7350** RESERVED -> (PENDING) -> EXCLUSIVE
7351** PENDING -> EXCLUSIVE
7352**
7353** This routine will only increase a lock. Use the sqlite3OsUnlock()
7354** routine to lower a locking level.
7355*/
drh308c2a52010-05-14 11:30:18 +00007356static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007357 unixFile *pFile = (unixFile*)id;
7358 int rc = proxyTakeConch(pFile);
7359 if( rc==SQLITE_OK ){
7360 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007361 if( pCtx->conchHeld>0 ){
7362 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007363 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7364 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007365 }else{
7366 /* conchHeld < 0 is lockless */
7367 }
drh715ff302008-12-03 22:32:44 +00007368 }
7369 return rc;
7370}
7371
7372
7373/*
drh308c2a52010-05-14 11:30:18 +00007374** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007375** must be either NO_LOCK or SHARED_LOCK.
7376**
7377** If the locking level of the file descriptor is already at or below
7378** the requested locking level, this routine is a no-op.
7379*/
drh308c2a52010-05-14 11:30:18 +00007380static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007381 unixFile *pFile = (unixFile*)id;
7382 int rc = proxyTakeConch(pFile);
7383 if( rc==SQLITE_OK ){
7384 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007385 if( pCtx->conchHeld>0 ){
7386 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007387 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7388 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007389 }else{
7390 /* conchHeld < 0 is lockless */
7391 }
drh715ff302008-12-03 22:32:44 +00007392 }
7393 return rc;
7394}
7395
7396/*
7397** Close a file that uses proxy locks.
7398*/
7399static int proxyClose(sqlite3_file *id) {
7400 if( id ){
7401 unixFile *pFile = (unixFile*)id;
7402 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7403 unixFile *lockProxy = pCtx->lockProxy;
7404 unixFile *conchFile = pCtx->conchFile;
7405 int rc = SQLITE_OK;
7406
7407 if( lockProxy ){
7408 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7409 if( rc ) return rc;
7410 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7411 if( rc ) return rc;
7412 sqlite3_free(lockProxy);
7413 pCtx->lockProxy = 0;
7414 }
7415 if( conchFile ){
7416 if( pCtx->conchHeld ){
7417 rc = proxyReleaseConch(pFile);
7418 if( rc ) return rc;
7419 }
7420 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7421 if( rc ) return rc;
7422 sqlite3_free(conchFile);
7423 }
drhd56b1212010-08-11 06:14:15 +00007424 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007425 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007426 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007427 /* restore the original locking context and pMethod then close it */
7428 pFile->lockingContext = pCtx->oldLockingContext;
7429 pFile->pMethod = pCtx->pOldMethod;
7430 sqlite3_free(pCtx);
7431 return pFile->pMethod->xClose(id);
7432 }
7433 return SQLITE_OK;
7434}
7435
7436
7437
drhd2cb50b2009-01-09 21:41:17 +00007438#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007439/*
7440** The proxy locking style is intended for use with AFP filesystems.
7441** And since AFP is only supported on MacOSX, the proxy locking is also
7442** restricted to MacOSX.
7443**
7444**
7445******************* End of the proxy lock implementation **********************
7446******************************************************************************/
7447
drh734c9862008-11-28 15:37:20 +00007448/*
danielk1977e339d652008-06-28 11:23:00 +00007449** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007450**
7451** This routine registers all VFS implementations for unix-like operating
7452** systems. This routine, and the sqlite3_os_end() routine that follows,
7453** should be the only routines in this file that are visible from other
7454** files.
drh6b9d6dd2008-12-03 19:34:47 +00007455**
7456** This routine is called once during SQLite initialization and by a
7457** single thread. The memory allocation and mutex subsystems have not
7458** necessarily been initialized when this routine is called, and so they
7459** should not be used.
drh153c62c2007-08-24 03:51:33 +00007460*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007461int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007462 /*
7463 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007464 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7465 ** to the "finder" function. (pAppData is a pointer to a pointer because
7466 ** silly C90 rules prohibit a void* from being cast to a function pointer
7467 ** and so we have to go through the intermediate pointer to avoid problems
7468 ** when compiling with -pedantic-errors on GCC.)
7469 **
7470 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007471 ** finder-function. The finder-function returns a pointer to the
7472 ** sqlite_io_methods object that implements the desired locking
7473 ** behaviors. See the division above that contains the IOMETHODS
7474 ** macro for addition information on finder-functions.
7475 **
7476 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7477 ** object. But the "autolockIoFinder" available on MacOSX does a little
7478 ** more than that; it looks at the filesystem type that hosts the
7479 ** database file and tries to choose an locking method appropriate for
7480 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007481 */
drh7708e972008-11-29 00:56:52 +00007482 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007483 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007484 sizeof(unixFile), /* szOsFile */ \
7485 MAX_PATHNAME, /* mxPathname */ \
7486 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007487 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007488 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007489 unixOpen, /* xOpen */ \
7490 unixDelete, /* xDelete */ \
7491 unixAccess, /* xAccess */ \
7492 unixFullPathname, /* xFullPathname */ \
7493 unixDlOpen, /* xDlOpen */ \
7494 unixDlError, /* xDlError */ \
7495 unixDlSym, /* xDlSym */ \
7496 unixDlClose, /* xDlClose */ \
7497 unixRandomness, /* xRandomness */ \
7498 unixSleep, /* xSleep */ \
7499 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007500 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007501 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007502 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007503 unixGetSystemCall, /* xGetSystemCall */ \
7504 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007505 }
7506
drh6b9d6dd2008-12-03 19:34:47 +00007507 /*
7508 ** All default VFSes for unix are contained in the following array.
7509 **
7510 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7511 ** by the SQLite core when the VFS is registered. So the following
7512 ** array cannot be const.
7513 */
danielk1977e339d652008-06-28 11:23:00 +00007514 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007515#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007516 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007517#elif OS_VXWORKS
7518 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007519#else
7520 UNIXVFS("unix", posixIoFinder ),
7521#endif
7522 UNIXVFS("unix-none", nolockIoFinder ),
7523 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007524 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007525#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007526 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007527#endif
drhe89b2912015-03-03 20:42:01 +00007528#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007529 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007530#endif
drhe89b2912015-03-03 20:42:01 +00007531#if SQLITE_ENABLE_LOCKING_STYLE
7532 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007533#endif
drhd2cb50b2009-01-09 21:41:17 +00007534#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007535 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007536 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007537 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007538#endif
drh153c62c2007-08-24 03:51:33 +00007539 };
drh6b9d6dd2008-12-03 19:34:47 +00007540 unsigned int i; /* Loop counter */
7541
drh2aa5a002011-04-13 13:42:25 +00007542 /* Double-check that the aSyscall[] array has been constructed
7543 ** correctly. See ticket [bb3a86e890c8e96ab] */
danbc760632014-03-20 09:42:09 +00007544 assert( ArraySize(aSyscall)==25 );
drh2aa5a002011-04-13 13:42:25 +00007545
drh6b9d6dd2008-12-03 19:34:47 +00007546 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007547 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007548 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007549 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007550 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007551}
danielk1977e339d652008-06-28 11:23:00 +00007552
7553/*
drh6b9d6dd2008-12-03 19:34:47 +00007554** Shutdown the operating system interface.
7555**
7556** Some operating systems might need to do some cleanup in this routine,
7557** to release dynamically allocated objects. But not on unix.
7558** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007559*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007560int sqlite3_os_end(void){
7561 return SQLITE_OK;
7562}
drhdce8bdb2007-08-16 13:01:44 +00007563
danielk197729bafea2008-06-26 10:41:19 +00007564#endif /* SQLITE_OS_UNIX */