blob: 844a1c46e179a747c0578f68286275a7d4d36109 [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
drhe32a2562016-03-04 02:38:00 +000074/* Use pread() and pwrite() if they are available */
75#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
76# undef USE_PREAD
77# undef USE_PWRITE
78# define USE_PREAD64 1
79# define USE_PWRITE64 1
80#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
81# undef USE_PREAD
82# undef USE_PWRITE
83# define USE_PREAD64 1
84# define USE_PWRITE64 1
85#endif
86
drh9cbe6352005-11-29 03:13:21 +000087/*
drh9cbe6352005-11-29 03:13:21 +000088** standard include files.
89*/
90#include <sys/types.h>
91#include <sys/stat.h>
92#include <fcntl.h>
93#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000094#include <time.h>
drh19e2d372005-08-29 23:00:03 +000095#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000096#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000097#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000098# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +000099#endif
drh1da88f02011-12-17 16:09:16 +0000100
drhe89b2912015-03-03 20:42:01 +0000101#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000102# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +0000103# include <sys/file.h>
104# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +0000105#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000106
drh6bca6512015-04-13 23:05:28 +0000107#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
108 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
109# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
110 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
111# define HAVE_GETHOSTUUID 1
112# else
113# warning "gethostuuid() is disabled."
114# endif
115#endif
116
117
drhe89b2912015-03-03 20:42:01 +0000118#if OS_VXWORKS
119# include <sys/ioctl.h>
120# include <semaphore.h>
121# include <limits.h>
122#endif /* OS_VXWORKS */
123
124#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000125# include <sys/mount.h>
126#endif
127
drhdbe4b882011-06-20 18:00:17 +0000128#ifdef HAVE_UTIME
129# include <utime.h>
130#endif
131
drh9cbe6352005-11-29 03:13:21 +0000132/*
drh7ed97b92010-01-20 13:07:21 +0000133** Allowed values of unixFile.fsFlags
134*/
135#define SQLITE_FSFLAGS_IS_MSDOS 0x1
136
137/*
drhf1a221e2006-01-15 17:27:17 +0000138** If we are to be thread-safe, include the pthreads header and define
139** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000140*/
drhd677b3d2007-08-20 22:48:41 +0000141#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000142# include <pthread.h>
143# define SQLITE_UNIX_THREADS 1
144#endif
145
146/*
147** Default permissions when creating a new file
148*/
149#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
150# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
151#endif
152
danielk1977b4b47412007-08-17 15:53:36 +0000153/*
drh5adc60b2012-04-14 13:25:11 +0000154** Default permissions when creating auto proxy dir
155*/
aswiftaebf4132008-11-21 00:10:35 +0000156#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
157# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
158#endif
159
160/*
danielk1977b4b47412007-08-17 15:53:36 +0000161** Maximum supported path-length.
162*/
163#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000164
dane88ec182016-01-25 17:04:48 +0000165/*
166** Maximum supported symbolic links
167*/
168#define SQLITE_MAX_SYMLINKS 100
169
drh91eb93c2015-03-03 19:56:20 +0000170/* Always cast the getpid() return type for compatibility with
171** kernel modules in VxWorks. */
172#define osGetpid(X) (pid_t)getpid()
173
drh734c9862008-11-28 15:37:20 +0000174/*
drh734c9862008-11-28 15:37:20 +0000175** Only set the lastErrno if the error code is a real error and not
176** a normal expected return code of SQLITE_BUSY or SQLITE_OK
177*/
178#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
179
drhd91c68f2010-05-14 14:52:25 +0000180/* Forward references */
181typedef struct unixShm unixShm; /* Connection shared memory */
182typedef struct unixShmNode unixShmNode; /* Shared memory instance */
183typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
184typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000185
186/*
dane946c392009-08-22 11:39:46 +0000187** Sometimes, after a file handle is closed by SQLite, the file descriptor
188** cannot be closed immediately. In these cases, instances of the following
189** structure are used to store the file descriptor while waiting for an
190** opportunity to either close or reuse it.
191*/
dane946c392009-08-22 11:39:46 +0000192struct UnixUnusedFd {
193 int fd; /* File descriptor to close */
194 int flags; /* Flags this file descriptor was opened with */
195 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
196};
197
198/*
drh9b35ea62008-11-29 02:20:26 +0000199** The unixFile structure is subclass of sqlite3_file specific to the unix
200** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000201*/
drh054889e2005-11-30 03:20:31 +0000202typedef struct unixFile unixFile;
203struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000204 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000205 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000206 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000207 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000208 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000209 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000210 int lastErrno; /* The unix errno from last I/O error */
211 void *lockingContext; /* Locking style specific state */
212 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000213 const char *zPath; /* Name of the file */
214 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000215 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000216#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000217 int nFetchOut; /* Number of outstanding xFetch refs */
218 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000219 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
220 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000221 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000222#endif
drh537dddf2012-10-26 13:46:24 +0000223#ifdef __QNXNTO__
224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
226#endif
drh08c6d442009-02-09 17:34:07 +0000227#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000228 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000229#endif
drh7ed97b92010-01-20 13:07:21 +0000230#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000231 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000232#endif
233#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000234 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000235#endif
drhd3d8c042012-05-29 17:02:40 +0000236#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000237 /* The next group of variables are used to track whether or not the
238 ** transaction counter in bytes 24-27 of database files are updated
239 ** whenever any part of the database changes. An assertion fault will
240 ** occur if a file is updated without also updating the transaction
241 ** counter. This test is made to avoid new problems similar to the
242 ** one described by ticket #3584.
243 */
244 unsigned char transCntrChng; /* True if the transaction counter changed */
245 unsigned char dbUpdate; /* True if any part of database file changed */
246 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000247
drh8f941bc2009-01-14 23:03:40 +0000248#endif
danf23da962013-03-23 21:00:41 +0000249
danielk1977967a4a12007-08-20 14:23:44 +0000250#ifdef SQLITE_TEST
251 /* In test mode, increase the size of this structure a bit so that
252 ** it is larger than the struct CrashFile defined in test6.c.
253 */
254 char aPadding[32];
255#endif
drh9cbe6352005-11-29 03:13:21 +0000256};
257
drhb00d8622014-01-01 15:18:36 +0000258/* This variable holds the process id (pid) from when the xRandomness()
259** method was called. If xOpen() is called from a different process id,
260** indicating that a fork() has occurred, the PRNG will be reset.
261*/
drh8cd5b252015-03-02 22:06:43 +0000262static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000263
drh0ccebe72005-06-07 22:22:50 +0000264/*
drha7e61d82011-03-12 17:02:57 +0000265** Allowed values for the unixFile.ctrlFlags bitmask:
266*/
drhf0b190d2011-07-26 16:03:07 +0000267#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
268#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
269#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000270#ifndef SQLITE_DISABLE_DIRSYNC
271# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
272#else
273# define UNIXFILE_DIRSYNC 0x00
274#endif
drhcb15f352011-12-23 01:04:17 +0000275#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000276#define UNIXFILE_DELETE 0x20 /* Delete on close */
277#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
278#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000279
280/*
drh198bf392006-01-06 21:52:49 +0000281** Include code that is common to all os_*.c files
282*/
283#include "os_common.h"
284
285/*
drh0ccebe72005-06-07 22:22:50 +0000286** Define various macros that are missing from some systems.
287*/
drhbbd42a62004-05-22 17:41:58 +0000288#ifndef O_LARGEFILE
289# define O_LARGEFILE 0
290#endif
291#ifdef SQLITE_DISABLE_LFS
292# undef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifndef O_NOFOLLOW
296# define O_NOFOLLOW 0
297#endif
298#ifndef O_BINARY
299# define O_BINARY 0
300#endif
301
302/*
drh2b4b5962005-06-15 17:47:55 +0000303** The threadid macro resolves to the thread-id or to 0. Used for
304** testing and debugging only.
305*/
drhd677b3d2007-08-20 22:48:41 +0000306#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000307#define threadid pthread_self()
308#else
309#define threadid 0
310#endif
311
drh99ab3b12011-03-02 15:09:07 +0000312/*
dane6ecd662013-04-01 17:56:59 +0000313** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314*/
315#if !defined(HAVE_MREMAP)
316# if defined(__linux__) && defined(_GNU_SOURCE)
317# define HAVE_MREMAP 1
318# else
319# define HAVE_MREMAP 0
320# endif
321#endif
322
323/*
dan2ee53412014-09-06 16:49:40 +0000324** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
325** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
326*/
327#ifdef __ANDROID__
328# define lseek lseek64
329#endif
330
331/*
drh9a3baf12011-04-25 18:01:27 +0000332** Different Unix systems declare open() in different ways. Same use
333** open(const char*,int,mode_t). Others use open(const char*,int,...).
334** The difference is important when using a pointer to the function.
335**
336** The safest way to deal with the problem is to always use this wrapper
337** which always has the same well-defined interface.
338*/
339static int posixOpen(const char *zFile, int flags, int mode){
340 return open(zFile, flags, mode);
341}
342
drh90315a22011-08-10 01:52:12 +0000343/* Forward reference */
344static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000345static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000346
drh9a3baf12011-04-25 18:01:27 +0000347/*
drh99ab3b12011-03-02 15:09:07 +0000348** Many system calls are accessed through pointer-to-functions so that
349** they may be overridden at runtime to facilitate fault injection during
350** testing and sandboxing. The following array holds the names and pointers
351** to all overrideable system calls.
352*/
353static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000354 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000355 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
356 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000357} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000358 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
359#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000360
drh58ad5802011-03-23 22:02:23 +0000361 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000362#define osClose ((int(*)(int))aSyscall[1].pCurrent)
363
drh58ad5802011-03-23 22:02:23 +0000364 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000365#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
366
drh58ad5802011-03-23 22:02:23 +0000367 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
372
373/*
374** The DJGPP compiler environment looks mostly like Unix, but it
375** lacks the fcntl() system call. So redefine fcntl() to be something
376** that always succeeds. This means that locking does not occur under
377** DJGPP. But it is DOS - what did you expect?
378*/
379#ifdef __DJGPP__
380 { "fstat", 0, 0 },
381#define osFstat(a,b,c) 0
382#else
drh58ad5802011-03-23 22:02:23 +0000383 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000384#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
385#endif
386
drh58ad5802011-03-23 22:02:23 +0000387 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000388#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
389
drh58ad5802011-03-23 22:02:23 +0000390 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000391#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000392
drh58ad5802011-03-23 22:02:23 +0000393 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000394#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
395
drhe89b2912015-03-03 20:42:01 +0000396#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000397 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000398#else
drh58ad5802011-03-23 22:02:23 +0000399 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000400#endif
401#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
402
403#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000404 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000405#else
drh58ad5802011-03-23 22:02:23 +0000406 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000407#endif
408#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
409
drh58ad5802011-03-23 22:02:23 +0000410 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000411#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
412
drhe89b2912015-03-03 20:42:01 +0000413#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000414 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000415#else
drh58ad5802011-03-23 22:02:23 +0000416 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000417#endif
418#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
419 aSyscall[12].pCurrent)
420
421#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000423#else
drh58ad5802011-03-23 22:02:23 +0000424 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000425#endif
426#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
427 aSyscall[13].pCurrent)
428
drh6226ca22015-11-24 15:06:28 +0000429 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000430#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000431
432#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000433 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000434#else
drh58ad5802011-03-23 22:02:23 +0000435 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000436#endif
dan0fd7d862011-03-29 10:04:23 +0000437#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000438
drh036ac7f2011-08-08 23:18:05 +0000439 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
440#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
441
drh90315a22011-08-10 01:52:12 +0000442 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
443#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
444
drh9ef6bc42011-11-04 02:24:02 +0000445 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
446#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
447
448 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
449#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
450
drhe2258a22016-01-12 00:37:55 +0000451#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000452 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000453#else
454 { "fchown", (sqlite3_syscall_ptr)0, 0 },
455#endif
dand3eaebd2012-02-13 08:50:23 +0000456#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000457
drh6226ca22015-11-24 15:06:28 +0000458 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
459#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
460
dan4dd51442013-08-26 14:30:25 +0000461#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000462 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
463#else
464 { "mmap", (sqlite3_syscall_ptr)0, 0 },
465#endif
drh6226ca22015-11-24 15:06:28 +0000466#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000467
drhe4a08f92016-01-08 19:17:30 +0000468#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000469 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000470#else
drha8299922016-01-08 22:31:00 +0000471 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000472#endif
drh6226ca22015-11-24 15:06:28 +0000473#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000474
drhe4a08f92016-01-08 19:17:30 +0000475#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000476 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
477#else
478 { "mremap", (sqlite3_syscall_ptr)0, 0 },
479#endif
drh6226ca22015-11-24 15:06:28 +0000480#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
481
drh24dbeae2016-01-08 22:18:00 +0000482#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000483 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000484#else
485 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
486#endif
drh6226ca22015-11-24 15:06:28 +0000487#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000488
drhe2258a22016-01-12 00:37:55 +0000489#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000490 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000491#else
492 { "readlink", (sqlite3_syscall_ptr)0, 0 },
493#endif
drh6226ca22015-11-24 15:06:28 +0000494#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000495
danaf1b36b2016-01-25 18:43:05 +0000496#if defined(HAVE_LSTAT)
497 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
498#else
499 { "lstat", (sqlite3_syscall_ptr)0, 0 },
500#endif
dancaf6b152016-01-25 18:05:49 +0000501#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000502
drhe562be52011-03-02 18:01:10 +0000503}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000504
drh6226ca22015-11-24 15:06:28 +0000505
506/*
507** On some systems, calls to fchown() will trigger a message in a security
508** log if they come from non-root processes. So avoid calling fchown() if
509** we are not running as root.
510*/
511static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000512#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000513 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000514#else
515 return 0;
drh6226ca22015-11-24 15:06:28 +0000516#endif
517}
518
drh99ab3b12011-03-02 15:09:07 +0000519/*
520** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000521** "unix" VFSes. Return SQLITE_OK opon successfully updating the
522** system call pointer, or SQLITE_NOTFOUND if there is no configurable
523** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000524*/
525static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000526 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
527 const char *zName, /* Name of system call to override */
528 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000529){
drh58ad5802011-03-23 22:02:23 +0000530 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000531 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000532
533 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000534 if( zName==0 ){
535 /* If no zName is given, restore all system calls to their default
536 ** settings and return NULL
537 */
dan51438a72011-04-02 17:00:47 +0000538 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000539 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
540 if( aSyscall[i].pDefault ){
541 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000542 }
543 }
544 }else{
545 /* If zName is specified, operate on only the one system call
546 ** specified.
547 */
548 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
549 if( strcmp(zName, aSyscall[i].zName)==0 ){
550 if( aSyscall[i].pDefault==0 ){
551 aSyscall[i].pDefault = aSyscall[i].pCurrent;
552 }
drh1df30962011-03-02 19:06:42 +0000553 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000554 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
555 aSyscall[i].pCurrent = pNewFunc;
556 break;
557 }
558 }
559 }
560 return rc;
561}
562
drh1df30962011-03-02 19:06:42 +0000563/*
564** Return the value of a system call. Return NULL if zName is not a
565** recognized system call name. NULL is also returned if the system call
566** is currently undefined.
567*/
drh58ad5802011-03-23 22:02:23 +0000568static sqlite3_syscall_ptr unixGetSystemCall(
569 sqlite3_vfs *pNotUsed,
570 const char *zName
571){
572 unsigned int i;
573
574 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000575 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
576 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
577 }
578 return 0;
579}
580
581/*
582** Return the name of the first system call after zName. If zName==NULL
583** then return the name of the first system call. Return NULL if zName
584** is the last system call or if zName is not the name of a valid
585** system call.
586*/
587static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000588 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000589
590 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000591 if( zName ){
592 for(i=0; i<ArraySize(aSyscall)-1; i++){
593 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000594 }
595 }
dan0fd7d862011-03-29 10:04:23 +0000596 for(i++; i<ArraySize(aSyscall); i++){
597 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000598 }
599 return 0;
600}
601
drhad4f1e52011-03-04 15:43:57 +0000602/*
drh77a3fdc2013-08-30 14:24:12 +0000603** Do not accept any file descriptor less than this value, in order to avoid
604** opening database file using file descriptors that are commonly used for
605** standard input, output, and error.
606*/
607#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
608# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
609#endif
610
611/*
drh8c815d12012-02-13 20:16:37 +0000612** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000613** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000614**
615** If the file creation mode "m" is 0 then set it to the default for
616** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
617** 0644) as modified by the system umask. If m is not 0, then
618** make the file creation mode be exactly m ignoring the umask.
619**
620** The m parameter will be non-zero only when creating -wal, -journal,
621** and -shm files. We want those files to have *exactly* the same
622** permissions as their original database, unadulterated by the umask.
623** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
624** transaction crashes and leaves behind hot journals, then any
625** process that is able to write to the database will also be able to
626** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000627*/
drh8c815d12012-02-13 20:16:37 +0000628static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000629 int fd;
drhe1186ab2013-01-04 20:45:13 +0000630 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000631 while(1){
drh5adc60b2012-04-14 13:25:11 +0000632#if defined(O_CLOEXEC)
633 fd = osOpen(z,f|O_CLOEXEC,m2);
634#else
635 fd = osOpen(z,f,m2);
636#endif
drh5128d002013-08-30 06:20:23 +0000637 if( fd<0 ){
638 if( errno==EINTR ) continue;
639 break;
640 }
drh77a3fdc2013-08-30 14:24:12 +0000641 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000642 osClose(fd);
643 sqlite3_log(SQLITE_WARNING,
644 "attempt to open \"%s\" as file descriptor %d", z, fd);
645 fd = -1;
646 if( osOpen("/dev/null", f, m)<0 ) break;
647 }
drhe1186ab2013-01-04 20:45:13 +0000648 if( fd>=0 ){
649 if( m!=0 ){
650 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000651 if( osFstat(fd, &statbuf)==0
652 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000653 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000654 ){
drhe1186ab2013-01-04 20:45:13 +0000655 osFchmod(fd, m);
656 }
657 }
drh5adc60b2012-04-14 13:25:11 +0000658#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000659 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000660#endif
drhe1186ab2013-01-04 20:45:13 +0000661 }
drh5adc60b2012-04-14 13:25:11 +0000662 return fd;
drhad4f1e52011-03-04 15:43:57 +0000663}
danielk197713adf8a2004-06-03 16:08:41 +0000664
drh107886a2008-11-21 22:21:50 +0000665/*
dan9359c7b2009-08-21 08:29:10 +0000666** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000667** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000668** vxworksFileId objects used by this file, all of which may be
669** shared by multiple threads.
670**
671** Function unixMutexHeld() is used to assert() that the global mutex
672** is held when required. This function is only used as part of assert()
673** statements. e.g.
674**
675** unixEnterMutex()
676** assert( unixMutexHeld() );
677** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000678*/
679static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000680 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000681}
682static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000683 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000684}
dan9359c7b2009-08-21 08:29:10 +0000685#ifdef SQLITE_DEBUG
686static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000687 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000688}
689#endif
drh107886a2008-11-21 22:21:50 +0000690
drh734c9862008-11-28 15:37:20 +0000691
mistachkinfb383e92015-04-16 03:24:38 +0000692#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000693/*
694** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000695** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000696** integer lock-type.
697*/
drh308c2a52010-05-14 11:30:18 +0000698static const char *azFileLock(int eFileLock){
699 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000700 case NO_LOCK: return "NONE";
701 case SHARED_LOCK: return "SHARED";
702 case RESERVED_LOCK: return "RESERVED";
703 case PENDING_LOCK: return "PENDING";
704 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000705 }
706 return "ERROR";
707}
708#endif
709
710#ifdef SQLITE_LOCK_TRACE
711/*
712** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000713**
drh734c9862008-11-28 15:37:20 +0000714** This routine is used for troubleshooting locks on multithreaded
715** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
716** command-line option on the compiler. This code is normally
717** turned off.
718*/
719static int lockTrace(int fd, int op, struct flock *p){
720 char *zOpName, *zType;
721 int s;
722 int savedErrno;
723 if( op==F_GETLK ){
724 zOpName = "GETLK";
725 }else if( op==F_SETLK ){
726 zOpName = "SETLK";
727 }else{
drh99ab3b12011-03-02 15:09:07 +0000728 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000729 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
730 return s;
731 }
732 if( p->l_type==F_RDLCK ){
733 zType = "RDLCK";
734 }else if( p->l_type==F_WRLCK ){
735 zType = "WRLCK";
736 }else if( p->l_type==F_UNLCK ){
737 zType = "UNLCK";
738 }else{
739 assert( 0 );
740 }
741 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000742 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000743 savedErrno = errno;
744 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
745 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
746 (int)p->l_pid, s);
747 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
748 struct flock l2;
749 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000750 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000751 if( l2.l_type==F_RDLCK ){
752 zType = "RDLCK";
753 }else if( l2.l_type==F_WRLCK ){
754 zType = "WRLCK";
755 }else if( l2.l_type==F_UNLCK ){
756 zType = "UNLCK";
757 }else{
758 assert( 0 );
759 }
760 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
761 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
762 }
763 errno = savedErrno;
764 return s;
765}
drh99ab3b12011-03-02 15:09:07 +0000766#undef osFcntl
767#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000768#endif /* SQLITE_LOCK_TRACE */
769
drhff812312011-02-23 13:33:46 +0000770/*
771** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000772**
drhe6d41732015-02-21 00:49:00 +0000773** All calls to ftruncate() within this file should be made through
774** this wrapper. On the Android platform, bypassing the logic below
775** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000776*/
drhff812312011-02-23 13:33:46 +0000777static int robust_ftruncate(int h, sqlite3_int64 sz){
778 int rc;
dan2ee53412014-09-06 16:49:40 +0000779#ifdef __ANDROID__
780 /* On Android, ftruncate() always uses 32-bit offsets, even if
781 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000782 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000783 ** such attempts. */
784 if( sz>(sqlite3_int64)0x7FFFFFFF ){
785 rc = SQLITE_OK;
786 }else
787#endif
drh99ab3b12011-03-02 15:09:07 +0000788 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000789 return rc;
790}
drh734c9862008-11-28 15:37:20 +0000791
792/*
793** This routine translates a standard POSIX errno code into something
794** useful to the clients of the sqlite3 functions. Specifically, it is
795** intended to translate a variety of "try again" errors into SQLITE_BUSY
796** and a variety of "please close the file descriptor NOW" errors into
797** SQLITE_IOERR
798**
799** Errors during initialization of locks, or file system support for locks,
800** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
801*/
802static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000803 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
804 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
805 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
806 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000807 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000808 case EACCES:
drh734c9862008-11-28 15:37:20 +0000809 case EAGAIN:
810 case ETIMEDOUT:
811 case EBUSY:
812 case EINTR:
813 case ENOLCK:
814 /* random NFS retry error, unless during file system support
815 * introspection, in which it actually means what it says */
816 return SQLITE_BUSY;
817
drh734c9862008-11-28 15:37:20 +0000818 case EPERM:
819 return SQLITE_PERM;
820
drh734c9862008-11-28 15:37:20 +0000821 default:
822 return sqliteIOErr;
823 }
824}
825
826
drh734c9862008-11-28 15:37:20 +0000827/******************************************************************************
828****************** Begin Unique File ID Utility Used By VxWorks ***************
829**
830** On most versions of unix, we can get a unique ID for a file by concatenating
831** the device number and the inode number. But this does not work on VxWorks.
832** On VxWorks, a unique file id must be based on the canonical filename.
833**
834** A pointer to an instance of the following structure can be used as a
835** unique file ID in VxWorks. Each instance of this structure contains
836** a copy of the canonical filename. There is also a reference count.
837** The structure is reclaimed when the number of pointers to it drops to
838** zero.
839**
840** There are never very many files open at one time and lookups are not
841** a performance-critical path, so it is sufficient to put these
842** structures on a linked list.
843*/
844struct vxworksFileId {
845 struct vxworksFileId *pNext; /* Next in a list of them all */
846 int nRef; /* Number of references to this one */
847 int nName; /* Length of the zCanonicalName[] string */
848 char *zCanonicalName; /* Canonical filename */
849};
850
851#if OS_VXWORKS
852/*
drh9b35ea62008-11-29 02:20:26 +0000853** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000854** variable:
855*/
856static struct vxworksFileId *vxworksFileList = 0;
857
858/*
859** Simplify a filename into its canonical form
860** by making the following changes:
861**
862** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000863** * convert /./ into just /
864** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000865**
866** Changes are made in-place. Return the new name length.
867**
868** The original filename is in z[0..n-1]. Return the number of
869** characters in the simplified name.
870*/
871static int vxworksSimplifyName(char *z, int n){
872 int i, j;
873 while( n>1 && z[n-1]=='/' ){ n--; }
874 for(i=j=0; i<n; i++){
875 if( z[i]=='/' ){
876 if( z[i+1]=='/' ) continue;
877 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
878 i += 1;
879 continue;
880 }
881 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
882 while( j>0 && z[j-1]!='/' ){ j--; }
883 if( j>0 ){ j--; }
884 i += 2;
885 continue;
886 }
887 }
888 z[j++] = z[i];
889 }
890 z[j] = 0;
891 return j;
892}
893
894/*
895** Find a unique file ID for the given absolute pathname. Return
896** a pointer to the vxworksFileId object. This pointer is the unique
897** file ID.
898**
899** The nRef field of the vxworksFileId object is incremented before
900** the object is returned. A new vxworksFileId object is created
901** and added to the global list if necessary.
902**
903** If a memory allocation error occurs, return NULL.
904*/
905static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
906 struct vxworksFileId *pNew; /* search key and new file ID */
907 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
908 int n; /* Length of zAbsoluteName string */
909
910 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000911 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000912 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000913 if( pNew==0 ) return 0;
914 pNew->zCanonicalName = (char*)&pNew[1];
915 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
916 n = vxworksSimplifyName(pNew->zCanonicalName, n);
917
918 /* Search for an existing entry that matching the canonical name.
919 ** If found, increment the reference count and return a pointer to
920 ** the existing file ID.
921 */
922 unixEnterMutex();
923 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
924 if( pCandidate->nName==n
925 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
926 ){
927 sqlite3_free(pNew);
928 pCandidate->nRef++;
929 unixLeaveMutex();
930 return pCandidate;
931 }
932 }
933
934 /* No match was found. We will make a new file ID */
935 pNew->nRef = 1;
936 pNew->nName = n;
937 pNew->pNext = vxworksFileList;
938 vxworksFileList = pNew;
939 unixLeaveMutex();
940 return pNew;
941}
942
943/*
944** Decrement the reference count on a vxworksFileId object. Free
945** the object when the reference count reaches zero.
946*/
947static void vxworksReleaseFileId(struct vxworksFileId *pId){
948 unixEnterMutex();
949 assert( pId->nRef>0 );
950 pId->nRef--;
951 if( pId->nRef==0 ){
952 struct vxworksFileId **pp;
953 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
954 assert( *pp==pId );
955 *pp = pId->pNext;
956 sqlite3_free(pId);
957 }
958 unixLeaveMutex();
959}
960#endif /* OS_VXWORKS */
961/*************** End of Unique File ID Utility Used By VxWorks ****************
962******************************************************************************/
963
964
965/******************************************************************************
966*************************** Posix Advisory Locking ****************************
967**
drh9b35ea62008-11-29 02:20:26 +0000968** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000969** section 6.5.2.2 lines 483 through 490 specify that when a process
970** sets or clears a lock, that operation overrides any prior locks set
971** by the same process. It does not explicitly say so, but this implies
972** that it overrides locks set by the same process using a different
973** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000974**
975** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000976** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
977**
978** Suppose ./file1 and ./file2 are really the same file (because
979** one is a hard or symbolic link to the other) then if you set
980** an exclusive lock on fd1, then try to get an exclusive lock
981** on fd2, it works. I would have expected the second lock to
982** fail since there was already a lock on the file due to fd1.
983** But not so. Since both locks came from the same process, the
984** second overrides the first, even though they were on different
985** file descriptors opened on different file names.
986**
drh734c9862008-11-28 15:37:20 +0000987** This means that we cannot use POSIX locks to synchronize file access
988** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000989** to synchronize access for threads in separate processes, but not
990** threads within the same process.
991**
992** To work around the problem, SQLite has to manage file locks internally
993** on its own. Whenever a new database is opened, we have to find the
994** specific inode of the database file (the inode is determined by the
995** st_dev and st_ino fields of the stat structure that fstat() fills in)
996** and check for locks already existing on that inode. When locks are
997** created or removed, we have to look at our own internal record of the
998** locks to see if another thread has previously set a lock on that same
999** inode.
1000**
drh9b35ea62008-11-29 02:20:26 +00001001** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1002** For VxWorks, we have to use the alternative unique ID system based on
1003** canonical filename and implemented in the previous division.)
1004**
danielk1977ad94b582007-08-20 06:44:22 +00001005** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001006** descriptor. It is now a structure that holds the integer file
1007** descriptor and a pointer to a structure that describes the internal
1008** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001009** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001010** point to the same locking structure. The locking structure keeps
1011** a reference count (so we will know when to delete it) and a "cnt"
1012** field that tells us its internal lock status. cnt==0 means the
1013** file is unlocked. cnt==-1 means the file has an exclusive lock.
1014** cnt>0 means there are cnt shared locks on the file.
1015**
1016** Any attempt to lock or unlock a file first checks the locking
1017** structure. The fcntl() system call is only invoked to set a
1018** POSIX lock if the internal lock structure transitions between
1019** a locked and an unlocked state.
1020**
drh734c9862008-11-28 15:37:20 +00001021** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001022**
1023** If you close a file descriptor that points to a file that has locks,
1024** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001025** released. To work around this problem, each unixInodeInfo object
1026** maintains a count of the number of pending locks on tha inode.
1027** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001028** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001029** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001030** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001031** be closed and that list is walked (and cleared) when the last lock
1032** clears.
1033**
drh9b35ea62008-11-29 02:20:26 +00001034** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001035**
drh9b35ea62008-11-29 02:20:26 +00001036** Many older versions of linux use the LinuxThreads library which is
1037** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001038** A cannot be modified or overridden by a different thread B.
1039** Only thread A can modify the lock. Locking behavior is correct
1040** if the appliation uses the newer Native Posix Thread Library (NPTL)
1041** on linux - with NPTL a lock created by thread A can override locks
1042** in thread B. But there is no way to know at compile-time which
1043** threading library is being used. So there is no way to know at
1044** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001045** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001046** current process.
drh5fdae772004-06-29 03:29:00 +00001047**
drh8af6c222010-05-14 12:43:01 +00001048** SQLite used to support LinuxThreads. But support for LinuxThreads
1049** was dropped beginning with version 3.7.0. SQLite will still work with
1050** LinuxThreads provided that (1) there is no more than one connection
1051** per database file in the same process and (2) database connections
1052** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001053*/
1054
1055/*
1056** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001057** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001058*/
1059struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001060 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001061#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001062 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001063#else
drh107886a2008-11-21 22:21:50 +00001064 ino_t ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001065#endif
1066};
1067
1068/*
drhbbd42a62004-05-22 17:41:58 +00001069** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001070** inode. Or, on LinuxThreads, there is one of these structures for
1071** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001072**
danielk1977ad94b582007-08-20 06:44:22 +00001073** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001074** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001075** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001076*/
drh8af6c222010-05-14 12:43:01 +00001077struct unixInodeInfo {
1078 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001079 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001080 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1081 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001082 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001083 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1084 int nLock; /* Number of outstanding file locks */
1085 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1086 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1087 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001088#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001089 unsigned long long sharedByte; /* for AFP simulated shared lock */
1090#endif
drh6c7d5c52008-11-21 20:32:33 +00001091#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001092 sem_t *pSem; /* Named POSIX semaphore */
1093 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001094#endif
drhbbd42a62004-05-22 17:41:58 +00001095};
1096
drhda0e7682008-07-30 15:27:54 +00001097/*
drh8af6c222010-05-14 12:43:01 +00001098** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001099*/
drhd91c68f2010-05-14 14:52:25 +00001100static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001101
drh5fdae772004-06-29 03:29:00 +00001102/*
dane18d4952011-02-21 11:46:24 +00001103**
drhaaeaa182015-11-24 15:12:47 +00001104** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001105** unixLogError().
1106**
1107** It is invoked after an error occurs in an OS function and errno has been
1108** set. It logs a message using sqlite3_log() containing the current value of
1109** errno and, if possible, the human-readable equivalent from strerror() or
1110** strerror_r().
1111**
1112** The first argument passed to the macro should be the error code that
1113** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1114** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001115** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001116** if any.
1117*/
drh0e9365c2011-03-02 02:08:13 +00001118#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1119static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001120 int errcode, /* SQLite error code */
1121 const char *zFunc, /* Name of OS function that failed */
1122 const char *zPath, /* File path associated with error */
1123 int iLine /* Source line number where error occurred */
1124){
1125 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001126 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001127
1128 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1129 ** the strerror() function to obtain the human-readable error message
1130 ** equivalent to errno. Otherwise, use strerror_r().
1131 */
1132#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1133 char aErr[80];
1134 memset(aErr, 0, sizeof(aErr));
1135 zErr = aErr;
1136
1137 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001138 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001139 ** returns a pointer to a buffer containing the error message. That pointer
1140 ** may point to aErr[], or it may point to some static storage somewhere.
1141 ** Otherwise, assume that the system provides the POSIX version of
1142 ** strerror_r(), which always writes an error message into aErr[].
1143 **
1144 ** If the code incorrectly assumes that it is the POSIX version that is
1145 ** available, the error message will often be an empty string. Not a
1146 ** huge problem. Incorrectly concluding that the GNU version is available
1147 ** could lead to a segfault though.
1148 */
1149#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1150 zErr =
1151# endif
drh0e9365c2011-03-02 02:08:13 +00001152 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001153
1154#elif SQLITE_THREADSAFE
1155 /* This is a threadsafe build, but strerror_r() is not available. */
1156 zErr = "";
1157#else
1158 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001159 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001160#endif
1161
drh0e9365c2011-03-02 02:08:13 +00001162 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001163 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001164 "os_unix.c:%d: (%d) %s(%s) - %s",
1165 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001166 );
1167
1168 return errcode;
1169}
1170
drh0e9365c2011-03-02 02:08:13 +00001171/*
1172** Close a file descriptor.
1173**
1174** We assume that close() almost always works, since it is only in a
1175** very sick application or on a very sick platform that it might fail.
1176** If it does fail, simply leak the file descriptor, but do log the
1177** error.
1178**
1179** Note that it is not safe to retry close() after EINTR since the
1180** file descriptor might have already been reused by another thread.
1181** So we don't even try to recover from an EINTR. Just log the error
1182** and move on.
1183*/
1184static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001185 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001186 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1187 pFile ? pFile->zPath : 0, lineno);
1188 }
1189}
dane18d4952011-02-21 11:46:24 +00001190
1191/*
drhe6d41732015-02-21 00:49:00 +00001192** Set the pFile->lastErrno. Do this in a subroutine as that provides
1193** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001194*/
1195static void storeLastErrno(unixFile *pFile, int error){
1196 pFile->lastErrno = error;
1197}
1198
1199/*
danb0ac3e32010-06-16 10:55:42 +00001200** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001201*/
drh0e9365c2011-03-02 02:08:13 +00001202static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001203 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001204 UnixUnusedFd *p;
1205 UnixUnusedFd *pNext;
1206 for(p=pInode->pUnused; p; p=pNext){
1207 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001208 robust_close(pFile, p->fd, __LINE__);
1209 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001210 }
drh0e9365c2011-03-02 02:08:13 +00001211 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001212}
1213
1214/*
drh8af6c222010-05-14 12:43:01 +00001215** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001216**
1217** The mutex entered using the unixEnterMutex() function must be held
1218** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001219*/
danb0ac3e32010-06-16 10:55:42 +00001220static void releaseInodeInfo(unixFile *pFile){
1221 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001222 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001223 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001224 pInode->nRef--;
1225 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001226 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001227 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001228 if( pInode->pPrev ){
1229 assert( pInode->pPrev->pNext==pInode );
1230 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001231 }else{
drh8af6c222010-05-14 12:43:01 +00001232 assert( inodeList==pInode );
1233 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001234 }
drh8af6c222010-05-14 12:43:01 +00001235 if( pInode->pNext ){
1236 assert( pInode->pNext->pPrev==pInode );
1237 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001238 }
drh8af6c222010-05-14 12:43:01 +00001239 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001240 }
drhbbd42a62004-05-22 17:41:58 +00001241 }
1242}
1243
1244/*
drh8af6c222010-05-14 12:43:01 +00001245** Given a file descriptor, locate the unixInodeInfo object that
1246** describes that file descriptor. Create a new one if necessary. The
1247** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001248**
dan9359c7b2009-08-21 08:29:10 +00001249** The mutex entered using the unixEnterMutex() function must be held
1250** when this function is called.
1251**
drh6c7d5c52008-11-21 20:32:33 +00001252** Return an appropriate error code.
1253*/
drh8af6c222010-05-14 12:43:01 +00001254static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001255 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001256 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001257){
1258 int rc; /* System call return code */
1259 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001260 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1261 struct stat statbuf; /* Low-level file information */
1262 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001263
dan9359c7b2009-08-21 08:29:10 +00001264 assert( unixMutexHeld() );
1265
drh6c7d5c52008-11-21 20:32:33 +00001266 /* Get low-level information about the file that we can used to
1267 ** create a unique name for the file.
1268 */
1269 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001270 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001271 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001272 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001273#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001274 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1275#endif
1276 return SQLITE_IOERR;
1277 }
1278
drheb0d74f2009-02-03 15:27:02 +00001279#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001280 /* On OS X on an msdos filesystem, the inode number is reported
1281 ** incorrectly for zero-size files. See ticket #3260. To work
1282 ** around this problem (we consider it a bug in OS X, not SQLite)
1283 ** we always increase the file size to 1 by writing a single byte
1284 ** prior to accessing the inode number. The one byte written is
1285 ** an ASCII 'S' character which also happens to be the first byte
1286 ** in the header of every SQLite database. In this way, if there
1287 ** is a race condition such that another thread has already populated
1288 ** the first page of the database, no damage is done.
1289 */
drh7ed97b92010-01-20 13:07:21 +00001290 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001291 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001292 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001293 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001294 return SQLITE_IOERR;
1295 }
drh99ab3b12011-03-02 15:09:07 +00001296 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001297 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001298 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001299 return SQLITE_IOERR;
1300 }
1301 }
drheb0d74f2009-02-03 15:27:02 +00001302#endif
drh6c7d5c52008-11-21 20:32:33 +00001303
drh8af6c222010-05-14 12:43:01 +00001304 memset(&fileId, 0, sizeof(fileId));
1305 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001306#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001307 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001308#else
drh8af6c222010-05-14 12:43:01 +00001309 fileId.ino = statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001310#endif
drh8af6c222010-05-14 12:43:01 +00001311 pInode = inodeList;
1312 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1313 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001314 }
drh8af6c222010-05-14 12:43:01 +00001315 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001316 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001317 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001318 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001319 }
drh8af6c222010-05-14 12:43:01 +00001320 memset(pInode, 0, sizeof(*pInode));
1321 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1322 pInode->nRef = 1;
1323 pInode->pNext = inodeList;
1324 pInode->pPrev = 0;
1325 if( inodeList ) inodeList->pPrev = pInode;
1326 inodeList = pInode;
1327 }else{
1328 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001329 }
drh8af6c222010-05-14 12:43:01 +00001330 *ppInode = pInode;
1331 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001332}
drh6c7d5c52008-11-21 20:32:33 +00001333
drhb959a012013-12-07 12:29:22 +00001334/*
1335** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1336*/
1337static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001338#if OS_VXWORKS
1339 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1340#else
drhb959a012013-12-07 12:29:22 +00001341 struct stat buf;
1342 return pFile->pInode!=0 &&
drh61ffea52014-08-12 12:19:25 +00001343 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001344#endif
drhb959a012013-12-07 12:29:22 +00001345}
1346
aswift5b1a2562008-08-22 00:22:35 +00001347
1348/*
drhfbc7e882013-04-11 01:16:15 +00001349** Check a unixFile that is a database. Verify the following:
1350**
1351** (1) There is exactly one hard link on the file
1352** (2) The file is not a symbolic link
1353** (3) The file has not been renamed or unlinked
1354**
1355** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1356*/
1357static void verifyDbFile(unixFile *pFile){
1358 struct stat buf;
1359 int rc;
drhfbc7e882013-04-11 01:16:15 +00001360 rc = osFstat(pFile->h, &buf);
1361 if( rc!=0 ){
1362 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001363 return;
1364 }
drh3044b512014-06-16 16:41:52 +00001365 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
drhfbc7e882013-04-11 01:16:15 +00001366 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001367 return;
1368 }
1369 if( buf.st_nlink>1 ){
1370 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001371 return;
1372 }
drhb959a012013-12-07 12:29:22 +00001373 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001374 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001375 return;
1376 }
1377}
1378
1379
1380/*
danielk197713adf8a2004-06-03 16:08:41 +00001381** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001382** file by this or any other process. If such a lock is held, set *pResOut
1383** to a non-zero value otherwise *pResOut is set to zero. The return value
1384** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001385*/
danielk1977861f7452008-06-05 11:39:11 +00001386static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001387 int rc = SQLITE_OK;
1388 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001389 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001390
danielk1977861f7452008-06-05 11:39:11 +00001391 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1392
drh054889e2005-11-30 03:20:31 +00001393 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001394 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001395 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001396
1397 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001398 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001399 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001400 }
1401
drh2ac3ee92004-06-07 16:27:46 +00001402 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001403 */
danielk197709480a92009-02-09 05:32:32 +00001404#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001405 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001406 struct flock lock;
1407 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001408 lock.l_start = RESERVED_BYTE;
1409 lock.l_len = 1;
1410 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001411 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1412 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001413 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001414 } else if( lock.l_type!=F_UNLCK ){
1415 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001416 }
1417 }
danielk197709480a92009-02-09 05:32:32 +00001418#endif
danielk197713adf8a2004-06-03 16:08:41 +00001419
drh6c7d5c52008-11-21 20:32:33 +00001420 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001421 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001422
aswift5b1a2562008-08-22 00:22:35 +00001423 *pResOut = reserved;
1424 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001425}
1426
1427/*
drha7e61d82011-03-12 17:02:57 +00001428** Attempt to set a system-lock on the file pFile. The lock is
1429** described by pLock.
1430**
drh77197112011-03-15 19:08:48 +00001431** If the pFile was opened read/write from unix-excl, then the only lock
1432** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001433** the first time any lock is attempted. All subsequent system locking
1434** operations become no-ops. Locking operations still happen internally,
1435** in order to coordinate access between separate database connections
1436** within this process, but all of that is handled in memory and the
1437** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001438**
1439** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1440** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1441** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001442**
1443** Zero is returned if the call completes successfully, or -1 if a call
1444** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001445*/
1446static int unixFileLock(unixFile *pFile, struct flock *pLock){
1447 int rc;
drh3cb93392011-03-12 18:10:44 +00001448 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001449 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001450 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001451 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001452 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001453 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001454 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001455 lock.l_whence = SEEK_SET;
1456 lock.l_start = SHARED_FIRST;
1457 lock.l_len = SHARED_SIZE;
1458 lock.l_type = F_WRLCK;
1459 rc = osFcntl(pFile->h, F_SETLK, &lock);
1460 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001461 pInode->bProcessLock = 1;
1462 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001463 }else{
1464 rc = 0;
1465 }
1466 }else{
1467 rc = osFcntl(pFile->h, F_SETLK, pLock);
1468 }
1469 return rc;
1470}
1471
1472/*
drh308c2a52010-05-14 11:30:18 +00001473** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001474** of the following:
1475**
drh2ac3ee92004-06-07 16:27:46 +00001476** (1) SHARED_LOCK
1477** (2) RESERVED_LOCK
1478** (3) PENDING_LOCK
1479** (4) EXCLUSIVE_LOCK
1480**
drhb3e04342004-06-08 00:47:47 +00001481** Sometimes when requesting one lock state, additional lock states
1482** are inserted in between. The locking might fail on one of the later
1483** transitions leaving the lock state different from what it started but
1484** still short of its goal. The following chart shows the allowed
1485** transitions and the inserted intermediate states:
1486**
1487** UNLOCKED -> SHARED
1488** SHARED -> RESERVED
1489** SHARED -> (PENDING) -> EXCLUSIVE
1490** RESERVED -> (PENDING) -> EXCLUSIVE
1491** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001492**
drha6abd042004-06-09 17:37:22 +00001493** This routine will only increase a lock. Use the sqlite3OsUnlock()
1494** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001495*/
drh308c2a52010-05-14 11:30:18 +00001496static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001497 /* The following describes the implementation of the various locks and
1498 ** lock transitions in terms of the POSIX advisory shared and exclusive
1499 ** lock primitives (called read-locks and write-locks below, to avoid
1500 ** confusion with SQLite lock names). The algorithms are complicated
1501 ** slightly in order to be compatible with windows systems simultaneously
1502 ** accessing the same database file, in case that is ever required.
1503 **
1504 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1505 ** byte', each single bytes at well known offsets, and the 'shared byte
1506 ** range', a range of 510 bytes at a well known offset.
1507 **
1508 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
1509 ** byte'. If this is successful, a random byte from the 'shared byte
1510 ** range' is read-locked and the lock on the 'pending byte' released.
1511 **
danielk197790ba3bd2004-06-25 08:32:25 +00001512 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1513 ** A RESERVED lock is implemented by grabbing a write-lock on the
1514 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001515 **
1516 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001517 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1518 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1519 ** obtained, but existing SHARED locks are allowed to persist. A process
1520 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1521 ** This property is used by the algorithm for rolling back a journal file
1522 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001523 **
danielk197790ba3bd2004-06-25 08:32:25 +00001524 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1525 ** implemented by obtaining a write-lock on the entire 'shared byte
1526 ** range'. Since all other locks require a read-lock on one of the bytes
1527 ** within this range, this ensures that no other locks are held on the
1528 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001529 **
1530 ** The reason a single byte cannot be used instead of the 'shared byte
1531 ** range' is that some versions of windows do not support read-locks. By
1532 ** locking a random byte from a range, concurrent SHARED locks may exist
1533 ** even if the locking primitive used is always a write-lock.
1534 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001535 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001536 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001537 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001538 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001539 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001540
drh054889e2005-11-30 03:20:31 +00001541 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001542 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1543 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001544 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001545 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001546
1547 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001548 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001549 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001550 */
drh308c2a52010-05-14 11:30:18 +00001551 if( pFile->eFileLock>=eFileLock ){
1552 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1553 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001554 return SQLITE_OK;
1555 }
1556
drh0c2694b2009-09-03 16:23:44 +00001557 /* Make sure the locking sequence is correct.
1558 ** (1) We never move from unlocked to anything higher than shared lock.
1559 ** (2) SQLite never explicitly requests a pendig lock.
1560 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001561 */
drh308c2a52010-05-14 11:30:18 +00001562 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1563 assert( eFileLock!=PENDING_LOCK );
1564 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001565
drh8af6c222010-05-14 12:43:01 +00001566 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001567 */
drh6c7d5c52008-11-21 20:32:33 +00001568 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001569 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001570
danielk1977ad94b582007-08-20 06:44:22 +00001571 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001572 ** handle that precludes the requested lock, return BUSY.
1573 */
drh8af6c222010-05-14 12:43:01 +00001574 if( (pFile->eFileLock!=pInode->eFileLock &&
1575 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001576 ){
1577 rc = SQLITE_BUSY;
1578 goto end_lock;
1579 }
1580
1581 /* If a SHARED lock is requested, and some thread using this PID already
1582 ** has a SHARED or RESERVED lock, then increment reference counts and
1583 ** return SQLITE_OK.
1584 */
drh308c2a52010-05-14 11:30:18 +00001585 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001586 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001587 assert( eFileLock==SHARED_LOCK );
1588 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001589 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001590 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001591 pInode->nShared++;
1592 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001593 goto end_lock;
1594 }
1595
danielk19779a1d0ab2004-06-01 14:09:28 +00001596
drh3cde3bb2004-06-12 02:17:14 +00001597 /* A PENDING lock is needed before acquiring a SHARED lock and before
1598 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1599 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001600 */
drh0c2694b2009-09-03 16:23:44 +00001601 lock.l_len = 1L;
1602 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001603 if( eFileLock==SHARED_LOCK
1604 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001605 ){
drh308c2a52010-05-14 11:30:18 +00001606 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001607 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001608 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001609 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001610 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001611 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001612 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001613 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001614 goto end_lock;
1615 }
drh3cde3bb2004-06-12 02:17:14 +00001616 }
1617
1618
1619 /* If control gets to this point, then actually go ahead and make
1620 ** operating system calls for the specified lock.
1621 */
drh308c2a52010-05-14 11:30:18 +00001622 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001623 assert( pInode->nShared==0 );
1624 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001625 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001626
drh2ac3ee92004-06-07 16:27:46 +00001627 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001628 lock.l_start = SHARED_FIRST;
1629 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001630 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001631 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001632 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001633 }
dan661d71a2011-03-30 19:08:03 +00001634
drh2ac3ee92004-06-07 16:27:46 +00001635 /* Drop the temporary PENDING lock */
1636 lock.l_start = PENDING_BYTE;
1637 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001638 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001639 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1640 /* This could happen with a network mount */
1641 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001642 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001643 }
dan661d71a2011-03-30 19:08:03 +00001644
1645 if( rc ){
1646 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001647 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001648 }
dan661d71a2011-03-30 19:08:03 +00001649 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001650 }else{
drh308c2a52010-05-14 11:30:18 +00001651 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001652 pInode->nLock++;
1653 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001654 }
drh8af6c222010-05-14 12:43:01 +00001655 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001656 /* We are trying for an exclusive lock but another thread in this
1657 ** same process is still holding a shared lock. */
1658 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001659 }else{
drh3cde3bb2004-06-12 02:17:14 +00001660 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001661 ** assumed that there is a SHARED or greater lock on the file
1662 ** already.
1663 */
drh308c2a52010-05-14 11:30:18 +00001664 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001665 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001666
1667 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1668 if( eFileLock==RESERVED_LOCK ){
1669 lock.l_start = RESERVED_BYTE;
1670 lock.l_len = 1L;
1671 }else{
1672 lock.l_start = SHARED_FIRST;
1673 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001674 }
dan661d71a2011-03-30 19:08:03 +00001675
1676 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001677 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001678 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001679 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001680 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001681 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001682 }
drhbbd42a62004-05-22 17:41:58 +00001683 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001684
drh8f941bc2009-01-14 23:03:40 +00001685
drhd3d8c042012-05-29 17:02:40 +00001686#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001687 /* Set up the transaction-counter change checking flags when
1688 ** transitioning from a SHARED to a RESERVED lock. The change
1689 ** from SHARED to RESERVED marks the beginning of a normal
1690 ** write operation (not a hot journal rollback).
1691 */
1692 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001693 && pFile->eFileLock<=SHARED_LOCK
1694 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001695 ){
1696 pFile->transCntrChng = 0;
1697 pFile->dbUpdate = 0;
1698 pFile->inNormalWrite = 1;
1699 }
1700#endif
1701
1702
danielk1977ecb2a962004-06-02 06:30:16 +00001703 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001704 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001705 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001706 }else if( eFileLock==EXCLUSIVE_LOCK ){
1707 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001708 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001709 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001710
1711end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001712 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001713 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1714 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001715 return rc;
1716}
1717
1718/*
dan08da86a2009-08-21 17:18:03 +00001719** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001720** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001721*/
1722static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001723 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001724 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001725 p->pNext = pInode->pUnused;
1726 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001727 pFile->h = -1;
1728 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001729}
1730
1731/*
drh308c2a52010-05-14 11:30:18 +00001732** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001733** must be either NO_LOCK or SHARED_LOCK.
1734**
1735** If the locking level of the file descriptor is already at or below
1736** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001737**
1738** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1739** the byte range is divided into 2 parts and the first part is unlocked then
1740** set to a read lock, then the other part is simply unlocked. This works
1741** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1742** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001743*/
drha7e61d82011-03-12 17:02:57 +00001744static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001745 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001746 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001747 struct flock lock;
1748 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001749
drh054889e2005-11-30 03:20:31 +00001750 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001751 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001752 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001753 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001754
drh308c2a52010-05-14 11:30:18 +00001755 assert( eFileLock<=SHARED_LOCK );
1756 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001757 return SQLITE_OK;
1758 }
drh6c7d5c52008-11-21 20:32:33 +00001759 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001760 pInode = pFile->pInode;
1761 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001762 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001763 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001764
drhd3d8c042012-05-29 17:02:40 +00001765#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001766 /* When reducing a lock such that other processes can start
1767 ** reading the database file again, make sure that the
1768 ** transaction counter was updated if any part of the database
1769 ** file changed. If the transaction counter is not updated,
1770 ** other connections to the same file might not realize that
1771 ** the file has changed and hence might not know to flush their
1772 ** cache. The use of a stale cache can lead to database corruption.
1773 */
drh8f941bc2009-01-14 23:03:40 +00001774 pFile->inNormalWrite = 0;
1775#endif
1776
drh7ed97b92010-01-20 13:07:21 +00001777 /* downgrading to a shared lock on NFS involves clearing the write lock
1778 ** before establishing the readlock - to avoid a race condition we downgrade
1779 ** the lock in 2 blocks, so that part of the range will be covered by a
1780 ** write lock until the rest is covered by a read lock:
1781 ** 1: [WWWWW]
1782 ** 2: [....W]
1783 ** 3: [RRRRW]
1784 ** 4: [RRRR.]
1785 */
drh308c2a52010-05-14 11:30:18 +00001786 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001787#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001788 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001789 assert( handleNFSUnlock==0 );
1790#endif
1791#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001792 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001793 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001794 off_t divSize = SHARED_SIZE - 1;
1795
1796 lock.l_type = F_UNLCK;
1797 lock.l_whence = SEEK_SET;
1798 lock.l_start = SHARED_FIRST;
1799 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001800 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001801 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001802 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001803 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001804 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001805 }
drh7ed97b92010-01-20 13:07:21 +00001806 lock.l_type = F_RDLCK;
1807 lock.l_whence = SEEK_SET;
1808 lock.l_start = SHARED_FIRST;
1809 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001810 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001811 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001812 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1813 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001814 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001815 }
1816 goto end_unlock;
1817 }
1818 lock.l_type = F_UNLCK;
1819 lock.l_whence = SEEK_SET;
1820 lock.l_start = SHARED_FIRST+divSize;
1821 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001822 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001823 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001824 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001825 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001826 goto end_unlock;
1827 }
drh30f776f2011-02-25 03:25:07 +00001828 }else
1829#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1830 {
drh7ed97b92010-01-20 13:07:21 +00001831 lock.l_type = F_RDLCK;
1832 lock.l_whence = SEEK_SET;
1833 lock.l_start = SHARED_FIRST;
1834 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001835 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001836 /* In theory, the call to unixFileLock() cannot fail because another
1837 ** process is holding an incompatible lock. If it does, this
1838 ** indicates that the other process is not following the locking
1839 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1840 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1841 ** an assert to fail). */
1842 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001843 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001844 goto end_unlock;
1845 }
drh9c105bb2004-10-02 20:38:28 +00001846 }
1847 }
drhbbd42a62004-05-22 17:41:58 +00001848 lock.l_type = F_UNLCK;
1849 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001850 lock.l_start = PENDING_BYTE;
1851 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001852 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001853 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001854 }else{
danea83bc62011-04-01 11:56:32 +00001855 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001856 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001857 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001858 }
drhbbd42a62004-05-22 17:41:58 +00001859 }
drh308c2a52010-05-14 11:30:18 +00001860 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001861 /* Decrement the shared lock counter. Release the lock using an
1862 ** OS call only when all threads in this same process have released
1863 ** the lock.
1864 */
drh8af6c222010-05-14 12:43:01 +00001865 pInode->nShared--;
1866 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001867 lock.l_type = F_UNLCK;
1868 lock.l_whence = SEEK_SET;
1869 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001870 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001871 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001872 }else{
danea83bc62011-04-01 11:56:32 +00001873 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001874 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001875 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001876 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001877 }
drha6abd042004-06-09 17:37:22 +00001878 }
1879
drhbbd42a62004-05-22 17:41:58 +00001880 /* Decrement the count of locks against this same file. When the
1881 ** count reaches zero, close any other file descriptors whose close
1882 ** was deferred because of outstanding locks.
1883 */
drh8af6c222010-05-14 12:43:01 +00001884 pInode->nLock--;
1885 assert( pInode->nLock>=0 );
1886 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001887 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001888 }
1889 }
drhf2f105d2012-08-20 15:53:54 +00001890
aswift5b1a2562008-08-22 00:22:35 +00001891end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001892 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001893 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001894 return rc;
drhbbd42a62004-05-22 17:41:58 +00001895}
1896
1897/*
drh308c2a52010-05-14 11:30:18 +00001898** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001899** must be either NO_LOCK or SHARED_LOCK.
1900**
1901** If the locking level of the file descriptor is already at or below
1902** the requested locking level, this routine is a no-op.
1903*/
drh308c2a52010-05-14 11:30:18 +00001904static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001905#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001906 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001907#endif
drha7e61d82011-03-12 17:02:57 +00001908 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001909}
1910
mistachkine98844f2013-08-24 00:59:24 +00001911#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001912static int unixMapfile(unixFile *pFd, i64 nByte);
1913static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001914#endif
danf23da962013-03-23 21:00:41 +00001915
drh7ed97b92010-01-20 13:07:21 +00001916/*
danielk1977e339d652008-06-28 11:23:00 +00001917** This function performs the parts of the "close file" operation
1918** common to all locking schemes. It closes the directory and file
1919** handles, if they are valid, and sets all fields of the unixFile
1920** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001921**
1922** It is *not* necessary to hold the mutex when this routine is called,
1923** even on VxWorks. A mutex will be acquired on VxWorks by the
1924** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001925*/
1926static int closeUnixFile(sqlite3_file *id){
1927 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001928#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001929 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001930#endif
dan661d71a2011-03-30 19:08:03 +00001931 if( pFile->h>=0 ){
1932 robust_close(pFile, pFile->h, __LINE__);
1933 pFile->h = -1;
1934 }
1935#if OS_VXWORKS
1936 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001937 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001938 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001939 }
1940 vxworksReleaseFileId(pFile->pId);
1941 pFile->pId = 0;
1942 }
1943#endif
drh0bdbc902014-06-16 18:35:06 +00001944#ifdef SQLITE_UNLINK_AFTER_CLOSE
1945 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1946 osUnlink(pFile->zPath);
1947 sqlite3_free(*(char**)&pFile->zPath);
1948 pFile->zPath = 0;
1949 }
1950#endif
dan661d71a2011-03-30 19:08:03 +00001951 OSTRACE(("CLOSE %-3d\n", pFile->h));
1952 OpenCounter(-1);
1953 sqlite3_free(pFile->pUnused);
1954 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001955 return SQLITE_OK;
1956}
1957
1958/*
danielk1977e3026632004-06-22 11:29:02 +00001959** Close a file.
1960*/
danielk197762079062007-08-15 17:08:46 +00001961static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001962 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001963 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001964 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001965 unixUnlock(id, NO_LOCK);
1966 unixEnterMutex();
1967
1968 /* unixFile.pInode is always valid here. Otherwise, a different close
1969 ** routine (e.g. nolockClose()) would be called instead.
1970 */
1971 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1972 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1973 /* If there are outstanding locks, do not actually close the file just
1974 ** yet because that would clear those locks. Instead, add the file
1975 ** descriptor to pInode->pUnused list. It will be automatically closed
1976 ** when the last lock is cleared.
1977 */
1978 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00001979 }
dan661d71a2011-03-30 19:08:03 +00001980 releaseInodeInfo(pFile);
1981 rc = closeUnixFile(id);
1982 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00001983 return rc;
danielk1977e3026632004-06-22 11:29:02 +00001984}
1985
drh734c9862008-11-28 15:37:20 +00001986/************** End of the posix advisory lock implementation *****************
1987******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00001988
drh734c9862008-11-28 15:37:20 +00001989/******************************************************************************
1990****************************** No-op Locking **********************************
1991**
1992** Of the various locking implementations available, this is by far the
1993** simplest: locking is ignored. No attempt is made to lock the database
1994** file for reading or writing.
1995**
1996** This locking mode is appropriate for use on read-only databases
1997** (ex: databases that are burned into CD-ROM, for example.) It can
1998** also be used if the application employs some external mechanism to
1999** prevent simultaneous access of the same database by two or more
2000** database connections. But there is a serious risk of database
2001** corruption if this locking mode is used in situations where multiple
2002** database connections are accessing the same database file at the same
2003** time and one or more of those connections are writing.
2004*/
drhbfe66312006-10-03 17:40:40 +00002005
drh734c9862008-11-28 15:37:20 +00002006static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2007 UNUSED_PARAMETER(NotUsed);
2008 *pResOut = 0;
2009 return SQLITE_OK;
2010}
drh734c9862008-11-28 15:37:20 +00002011static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2012 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2013 return SQLITE_OK;
2014}
drh734c9862008-11-28 15:37:20 +00002015static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2016 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2017 return SQLITE_OK;
2018}
2019
2020/*
drh9b35ea62008-11-29 02:20:26 +00002021** Close the file.
drh734c9862008-11-28 15:37:20 +00002022*/
2023static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002024 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002025}
2026
2027/******************* End of the no-op lock implementation *********************
2028******************************************************************************/
2029
2030/******************************************************************************
2031************************* Begin dot-file Locking ******************************
2032**
mistachkin48864df2013-03-21 21:20:32 +00002033** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002034** files (really a directory) to control access to the database. This works
2035** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002036**
2037** (1) There is zero concurrency. A single reader blocks all other
2038** connections from reading or writing the database.
2039**
2040** (2) An application crash or power loss can leave stale lock files
2041** sitting around that need to be cleared manually.
2042**
2043** Nevertheless, a dotlock is an appropriate locking mode for use if no
2044** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002045**
drh9ef6bc42011-11-04 02:24:02 +00002046** Dotfile locking works by creating a subdirectory in the same directory as
2047** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002048** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002049** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002050*/
2051
2052/*
2053** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002054** lock directory.
drh734c9862008-11-28 15:37:20 +00002055*/
2056#define DOTLOCK_SUFFIX ".lock"
2057
drh7708e972008-11-29 00:56:52 +00002058/*
2059** This routine checks if there is a RESERVED lock held on the specified
2060** file by this or any other process. If such a lock is held, set *pResOut
2061** to a non-zero value otherwise *pResOut is set to zero. The return value
2062** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2063**
2064** In dotfile locking, either a lock exists or it does not. So in this
2065** variation of CheckReservedLock(), *pResOut is set to true if any lock
2066** is held on the file and false if the file is unlocked.
2067*/
drh734c9862008-11-28 15:37:20 +00002068static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2069 int rc = SQLITE_OK;
2070 int reserved = 0;
2071 unixFile *pFile = (unixFile*)id;
2072
2073 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2074
2075 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002076 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002077 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002078 *pResOut = reserved;
2079 return rc;
2080}
2081
drh7708e972008-11-29 00:56:52 +00002082/*
drh308c2a52010-05-14 11:30:18 +00002083** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002084** of the following:
2085**
2086** (1) SHARED_LOCK
2087** (2) RESERVED_LOCK
2088** (3) PENDING_LOCK
2089** (4) EXCLUSIVE_LOCK
2090**
2091** Sometimes when requesting one lock state, additional lock states
2092** are inserted in between. The locking might fail on one of the later
2093** transitions leaving the lock state different from what it started but
2094** still short of its goal. The following chart shows the allowed
2095** transitions and the inserted intermediate states:
2096**
2097** UNLOCKED -> SHARED
2098** SHARED -> RESERVED
2099** SHARED -> (PENDING) -> EXCLUSIVE
2100** RESERVED -> (PENDING) -> EXCLUSIVE
2101** PENDING -> EXCLUSIVE
2102**
2103** This routine will only increase a lock. Use the sqlite3OsUnlock()
2104** routine to lower a locking level.
2105**
2106** With dotfile locking, we really only support state (4): EXCLUSIVE.
2107** But we track the other locking levels internally.
2108*/
drh308c2a52010-05-14 11:30:18 +00002109static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002110 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002111 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002112 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002113
drh7708e972008-11-29 00:56:52 +00002114
2115 /* If we have any lock, then the lock file already exists. All we have
2116 ** to do is adjust our internal record of the lock level.
2117 */
drh308c2a52010-05-14 11:30:18 +00002118 if( pFile->eFileLock > NO_LOCK ){
2119 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002120 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002121#ifdef HAVE_UTIME
2122 utime(zLockFile, NULL);
2123#else
drh734c9862008-11-28 15:37:20 +00002124 utimes(zLockFile, NULL);
2125#endif
drh7708e972008-11-29 00:56:52 +00002126 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002127 }
2128
2129 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002130 rc = osMkdir(zLockFile, 0777);
2131 if( rc<0 ){
2132 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002133 int tErrno = errno;
2134 if( EEXIST == tErrno ){
2135 rc = SQLITE_BUSY;
2136 } else {
2137 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002138 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002139 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002140 }
2141 }
drh7708e972008-11-29 00:56:52 +00002142 return rc;
drh734c9862008-11-28 15:37:20 +00002143 }
drh734c9862008-11-28 15:37:20 +00002144
2145 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002146 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002147 return rc;
2148}
2149
drh7708e972008-11-29 00:56:52 +00002150/*
drh308c2a52010-05-14 11:30:18 +00002151** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002152** must be either NO_LOCK or SHARED_LOCK.
2153**
2154** If the locking level of the file descriptor is already at or below
2155** the requested locking level, this routine is a no-op.
2156**
2157** When the locking level reaches NO_LOCK, delete the lock file.
2158*/
drh308c2a52010-05-14 11:30:18 +00002159static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002160 unixFile *pFile = (unixFile*)id;
2161 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002162 int rc;
drh734c9862008-11-28 15:37:20 +00002163
2164 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002165 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002166 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002167 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002168
2169 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002170 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002171 return SQLITE_OK;
2172 }
drh7708e972008-11-29 00:56:52 +00002173
2174 /* To downgrade to shared, simply update our internal notion of the
2175 ** lock state. No need to mess with the file on disk.
2176 */
drh308c2a52010-05-14 11:30:18 +00002177 if( eFileLock==SHARED_LOCK ){
2178 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002179 return SQLITE_OK;
2180 }
2181
drh7708e972008-11-29 00:56:52 +00002182 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002183 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002184 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002185 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002186 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002187 if( tErrno==ENOENT ){
2188 rc = SQLITE_OK;
2189 }else{
danea83bc62011-04-01 11:56:32 +00002190 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002191 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002192 }
2193 return rc;
2194 }
drh308c2a52010-05-14 11:30:18 +00002195 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002196 return SQLITE_OK;
2197}
2198
2199/*
drh9b35ea62008-11-29 02:20:26 +00002200** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002201*/
2202static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002203 unixFile *pFile = (unixFile*)id;
2204 assert( id!=0 );
2205 dotlockUnlock(id, NO_LOCK);
2206 sqlite3_free(pFile->lockingContext);
2207 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002208}
2209/****************** End of the dot-file lock implementation *******************
2210******************************************************************************/
2211
2212/******************************************************************************
2213************************** Begin flock Locking ********************************
2214**
2215** Use the flock() system call to do file locking.
2216**
drh6b9d6dd2008-12-03 19:34:47 +00002217** flock() locking is like dot-file locking in that the various
2218** fine-grain locking levels supported by SQLite are collapsed into
2219** a single exclusive lock. In other words, SHARED, RESERVED, and
2220** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2221** still works when you do this, but concurrency is reduced since
2222** only a single process can be reading the database at a time.
2223**
drhe89b2912015-03-03 20:42:01 +00002224** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002225*/
drhe89b2912015-03-03 20:42:01 +00002226#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002227
drh6b9d6dd2008-12-03 19:34:47 +00002228/*
drhff812312011-02-23 13:33:46 +00002229** Retry flock() calls that fail with EINTR
2230*/
2231#ifdef EINTR
2232static int robust_flock(int fd, int op){
2233 int rc;
2234 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2235 return rc;
2236}
2237#else
drh5c819272011-02-23 14:00:12 +00002238# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002239#endif
2240
2241
2242/*
drh6b9d6dd2008-12-03 19:34:47 +00002243** This routine checks if there is a RESERVED lock held on the specified
2244** file by this or any other process. If such a lock is held, set *pResOut
2245** to a non-zero value otherwise *pResOut is set to zero. The return value
2246** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2247*/
drh734c9862008-11-28 15:37:20 +00002248static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2249 int rc = SQLITE_OK;
2250 int reserved = 0;
2251 unixFile *pFile = (unixFile*)id;
2252
2253 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2254
2255 assert( pFile );
2256
2257 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002258 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002259 reserved = 1;
2260 }
2261
2262 /* Otherwise see if some other process holds it. */
2263 if( !reserved ){
2264 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002265 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002266 if( !lrc ){
2267 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002268 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002269 if ( lrc ) {
2270 int tErrno = errno;
2271 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002272 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002273 storeLastErrno(pFile, tErrno);
2274 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002275 }
2276 } else {
2277 int tErrno = errno;
2278 reserved = 1;
2279 /* someone else might have it reserved */
2280 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2281 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002282 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002283 rc = lrc;
2284 }
2285 }
2286 }
drh308c2a52010-05-14 11:30:18 +00002287 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002288
2289#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2290 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2291 rc = SQLITE_OK;
2292 reserved=1;
2293 }
2294#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2295 *pResOut = reserved;
2296 return rc;
2297}
2298
drh6b9d6dd2008-12-03 19:34:47 +00002299/*
drh308c2a52010-05-14 11:30:18 +00002300** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002301** of the following:
2302**
2303** (1) SHARED_LOCK
2304** (2) RESERVED_LOCK
2305** (3) PENDING_LOCK
2306** (4) EXCLUSIVE_LOCK
2307**
2308** Sometimes when requesting one lock state, additional lock states
2309** are inserted in between. The locking might fail on one of the later
2310** transitions leaving the lock state different from what it started but
2311** still short of its goal. The following chart shows the allowed
2312** transitions and the inserted intermediate states:
2313**
2314** UNLOCKED -> SHARED
2315** SHARED -> RESERVED
2316** SHARED -> (PENDING) -> EXCLUSIVE
2317** RESERVED -> (PENDING) -> EXCLUSIVE
2318** PENDING -> EXCLUSIVE
2319**
2320** flock() only really support EXCLUSIVE locks. We track intermediate
2321** lock states in the sqlite3_file structure, but all locks SHARED or
2322** above are really EXCLUSIVE locks and exclude all other processes from
2323** access the file.
2324**
2325** This routine will only increase a lock. Use the sqlite3OsUnlock()
2326** routine to lower a locking level.
2327*/
drh308c2a52010-05-14 11:30:18 +00002328static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002329 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002330 unixFile *pFile = (unixFile*)id;
2331
2332 assert( pFile );
2333
2334 /* if we already have a lock, it is exclusive.
2335 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002336 if (pFile->eFileLock > NO_LOCK) {
2337 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002338 return SQLITE_OK;
2339 }
2340
2341 /* grab an exclusive lock */
2342
drhff812312011-02-23 13:33:46 +00002343 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002344 int tErrno = errno;
2345 /* didn't get, must be busy */
2346 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2347 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002348 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002349 }
2350 } else {
2351 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002352 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002353 }
drh308c2a52010-05-14 11:30:18 +00002354 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2355 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002356#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2357 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2358 rc = SQLITE_BUSY;
2359 }
2360#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2361 return rc;
2362}
2363
drh6b9d6dd2008-12-03 19:34:47 +00002364
2365/*
drh308c2a52010-05-14 11:30:18 +00002366** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002367** must be either NO_LOCK or SHARED_LOCK.
2368**
2369** If the locking level of the file descriptor is already at or below
2370** the requested locking level, this routine is a no-op.
2371*/
drh308c2a52010-05-14 11:30:18 +00002372static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002373 unixFile *pFile = (unixFile*)id;
2374
2375 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002376 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002377 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002378 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002379
2380 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002381 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002382 return SQLITE_OK;
2383 }
2384
2385 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002386 if (eFileLock==SHARED_LOCK) {
2387 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002388 return SQLITE_OK;
2389 }
2390
2391 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002392 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002393#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002394 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002395#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002396 return SQLITE_IOERR_UNLOCK;
2397 }else{
drh308c2a52010-05-14 11:30:18 +00002398 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002399 return SQLITE_OK;
2400 }
2401}
2402
2403/*
2404** Close a file.
2405*/
2406static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002407 assert( id!=0 );
2408 flockUnlock(id, NO_LOCK);
2409 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002410}
2411
2412#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2413
2414/******************* End of the flock lock implementation *********************
2415******************************************************************************/
2416
2417/******************************************************************************
2418************************ Begin Named Semaphore Locking ************************
2419**
2420** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002421**
2422** Semaphore locking is like dot-lock and flock in that it really only
2423** supports EXCLUSIVE locking. Only a single process can read or write
2424** the database file at a time. This reduces potential concurrency, but
2425** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002426*/
2427#if OS_VXWORKS
2428
drh6b9d6dd2008-12-03 19:34:47 +00002429/*
2430** This routine checks if there is a RESERVED lock held on the specified
2431** file by this or any other process. If such a lock is held, set *pResOut
2432** to a non-zero value otherwise *pResOut is set to zero. The return value
2433** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2434*/
drh8cd5b252015-03-02 22:06:43 +00002435static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002436 int rc = SQLITE_OK;
2437 int reserved = 0;
2438 unixFile *pFile = (unixFile*)id;
2439
2440 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2441
2442 assert( pFile );
2443
2444 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002445 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002446 reserved = 1;
2447 }
2448
2449 /* Otherwise see if some other process holds it. */
2450 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002451 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002452
2453 if( sem_trywait(pSem)==-1 ){
2454 int tErrno = errno;
2455 if( EAGAIN != tErrno ){
2456 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002457 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002458 } else {
2459 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002460 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002461 }
2462 }else{
2463 /* we could have it if we want it */
2464 sem_post(pSem);
2465 }
2466 }
drh308c2a52010-05-14 11:30:18 +00002467 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002468
2469 *pResOut = reserved;
2470 return rc;
2471}
2472
drh6b9d6dd2008-12-03 19:34:47 +00002473/*
drh308c2a52010-05-14 11:30:18 +00002474** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002475** of the following:
2476**
2477** (1) SHARED_LOCK
2478** (2) RESERVED_LOCK
2479** (3) PENDING_LOCK
2480** (4) EXCLUSIVE_LOCK
2481**
2482** Sometimes when requesting one lock state, additional lock states
2483** are inserted in between. The locking might fail on one of the later
2484** transitions leaving the lock state different from what it started but
2485** still short of its goal. The following chart shows the allowed
2486** transitions and the inserted intermediate states:
2487**
2488** UNLOCKED -> SHARED
2489** SHARED -> RESERVED
2490** SHARED -> (PENDING) -> EXCLUSIVE
2491** RESERVED -> (PENDING) -> EXCLUSIVE
2492** PENDING -> EXCLUSIVE
2493**
2494** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2495** lock states in the sqlite3_file structure, but all locks SHARED or
2496** above are really EXCLUSIVE locks and exclude all other processes from
2497** access the file.
2498**
2499** This routine will only increase a lock. Use the sqlite3OsUnlock()
2500** routine to lower a locking level.
2501*/
drh8cd5b252015-03-02 22:06:43 +00002502static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002503 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002504 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002505 int rc = SQLITE_OK;
2506
2507 /* if we already have a lock, it is exclusive.
2508 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002509 if (pFile->eFileLock > NO_LOCK) {
2510 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002511 rc = SQLITE_OK;
2512 goto sem_end_lock;
2513 }
2514
2515 /* lock semaphore now but bail out when already locked. */
2516 if( sem_trywait(pSem)==-1 ){
2517 rc = SQLITE_BUSY;
2518 goto sem_end_lock;
2519 }
2520
2521 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002522 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002523
2524 sem_end_lock:
2525 return rc;
2526}
2527
drh6b9d6dd2008-12-03 19:34:47 +00002528/*
drh308c2a52010-05-14 11:30:18 +00002529** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002530** must be either NO_LOCK or SHARED_LOCK.
2531**
2532** If the locking level of the file descriptor is already at or below
2533** the requested locking level, this routine is a no-op.
2534*/
drh8cd5b252015-03-02 22:06:43 +00002535static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002536 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002537 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002538
2539 assert( pFile );
2540 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002541 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002542 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002543 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002544
2545 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002546 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002547 return SQLITE_OK;
2548 }
2549
2550 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002551 if (eFileLock==SHARED_LOCK) {
2552 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002553 return SQLITE_OK;
2554 }
2555
2556 /* no, really unlock. */
2557 if ( sem_post(pSem)==-1 ) {
2558 int rc, tErrno = errno;
2559 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2560 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002561 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002562 }
2563 return rc;
2564 }
drh308c2a52010-05-14 11:30:18 +00002565 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002566 return SQLITE_OK;
2567}
2568
2569/*
2570 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002571 */
drh8cd5b252015-03-02 22:06:43 +00002572static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002573 if( id ){
2574 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002575 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002576 assert( pFile );
2577 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002578 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002579 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002580 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002581 }
2582 return SQLITE_OK;
2583}
2584
2585#endif /* OS_VXWORKS */
2586/*
2587** Named semaphore locking is only available on VxWorks.
2588**
2589*************** End of the named semaphore lock implementation ****************
2590******************************************************************************/
2591
2592
2593/******************************************************************************
2594*************************** Begin AFP Locking *********************************
2595**
2596** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2597** on Apple Macintosh computers - both OS9 and OSX.
2598**
2599** Third-party implementations of AFP are available. But this code here
2600** only works on OSX.
2601*/
2602
drhd2cb50b2009-01-09 21:41:17 +00002603#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002604/*
2605** The afpLockingContext structure contains all afp lock specific state
2606*/
drhbfe66312006-10-03 17:40:40 +00002607typedef struct afpLockingContext afpLockingContext;
2608struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002609 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002610 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002611};
2612
2613struct ByteRangeLockPB2
2614{
2615 unsigned long long offset; /* offset to first byte to lock */
2616 unsigned long long length; /* nbr of bytes to lock */
2617 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2618 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2619 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2620 int fd; /* file desc to assoc this lock with */
2621};
2622
drhfd131da2007-08-07 17:13:03 +00002623#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002624
drh6b9d6dd2008-12-03 19:34:47 +00002625/*
2626** This is a utility for setting or clearing a bit-range lock on an
2627** AFP filesystem.
2628**
2629** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2630*/
2631static int afpSetLock(
2632 const char *path, /* Name of the file to be locked or unlocked */
2633 unixFile *pFile, /* Open file descriptor on path */
2634 unsigned long long offset, /* First byte to be locked */
2635 unsigned long long length, /* Number of bytes to lock */
2636 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002637){
drh6b9d6dd2008-12-03 19:34:47 +00002638 struct ByteRangeLockPB2 pb;
2639 int err;
drhbfe66312006-10-03 17:40:40 +00002640
2641 pb.unLockFlag = setLockFlag ? 0 : 1;
2642 pb.startEndFlag = 0;
2643 pb.offset = offset;
2644 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002645 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002646
drh308c2a52010-05-14 11:30:18 +00002647 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002648 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002649 offset, length));
drhbfe66312006-10-03 17:40:40 +00002650 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2651 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002652 int rc;
2653 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002654 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2655 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002656#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2657 rc = SQLITE_BUSY;
2658#else
drh734c9862008-11-28 15:37:20 +00002659 rc = sqliteErrorFromPosixError(tErrno,
2660 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002661#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002662 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002663 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002664 }
2665 return rc;
drhbfe66312006-10-03 17:40:40 +00002666 } else {
aswift5b1a2562008-08-22 00:22:35 +00002667 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002668 }
2669}
2670
drh6b9d6dd2008-12-03 19:34:47 +00002671/*
2672** This routine checks if there is a RESERVED lock held on the specified
2673** file by this or any other process. If such a lock is held, set *pResOut
2674** to a non-zero value otherwise *pResOut is set to zero. The return value
2675** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2676*/
danielk1977e339d652008-06-28 11:23:00 +00002677static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002678 int rc = SQLITE_OK;
2679 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002680 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002681 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002682
aswift5b1a2562008-08-22 00:22:35 +00002683 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2684
2685 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002686 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002687 if( context->reserved ){
2688 *pResOut = 1;
2689 return SQLITE_OK;
2690 }
drh8af6c222010-05-14 12:43:01 +00002691 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002692
2693 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002694 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002695 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002696 }
2697
2698 /* Otherwise see if some other process holds it.
2699 */
aswift5b1a2562008-08-22 00:22:35 +00002700 if( !reserved ){
2701 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002702 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002703 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002704 /* if we succeeded in taking the reserved lock, unlock it to restore
2705 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002706 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002707 } else {
2708 /* if we failed to get the lock then someone else must have it */
2709 reserved = 1;
2710 }
2711 if( IS_LOCK_ERROR(lrc) ){
2712 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002713 }
2714 }
drhbfe66312006-10-03 17:40:40 +00002715
drh7ed97b92010-01-20 13:07:21 +00002716 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002717 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002718
2719 *pResOut = reserved;
2720 return rc;
drhbfe66312006-10-03 17:40:40 +00002721}
2722
drh6b9d6dd2008-12-03 19:34:47 +00002723/*
drh308c2a52010-05-14 11:30:18 +00002724** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002725** of the following:
2726**
2727** (1) SHARED_LOCK
2728** (2) RESERVED_LOCK
2729** (3) PENDING_LOCK
2730** (4) EXCLUSIVE_LOCK
2731**
2732** Sometimes when requesting one lock state, additional lock states
2733** are inserted in between. The locking might fail on one of the later
2734** transitions leaving the lock state different from what it started but
2735** still short of its goal. The following chart shows the allowed
2736** transitions and the inserted intermediate states:
2737**
2738** UNLOCKED -> SHARED
2739** SHARED -> RESERVED
2740** SHARED -> (PENDING) -> EXCLUSIVE
2741** RESERVED -> (PENDING) -> EXCLUSIVE
2742** PENDING -> EXCLUSIVE
2743**
2744** This routine will only increase a lock. Use the sqlite3OsUnlock()
2745** routine to lower a locking level.
2746*/
drh308c2a52010-05-14 11:30:18 +00002747static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002748 int rc = SQLITE_OK;
2749 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002750 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002751 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002752
2753 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002754 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2755 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002756 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002757
drhbfe66312006-10-03 17:40:40 +00002758 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002759 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002760 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002761 */
drh308c2a52010-05-14 11:30:18 +00002762 if( pFile->eFileLock>=eFileLock ){
2763 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2764 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002765 return SQLITE_OK;
2766 }
2767
2768 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002769 ** (1) We never move from unlocked to anything higher than shared lock.
2770 ** (2) SQLite never explicitly requests a pendig lock.
2771 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002772 */
drh308c2a52010-05-14 11:30:18 +00002773 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2774 assert( eFileLock!=PENDING_LOCK );
2775 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002776
drh8af6c222010-05-14 12:43:01 +00002777 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002778 */
drh6c7d5c52008-11-21 20:32:33 +00002779 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002780 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002781
2782 /* If some thread using this PID has a lock via a different unixFile*
2783 ** handle that precludes the requested lock, return BUSY.
2784 */
drh8af6c222010-05-14 12:43:01 +00002785 if( (pFile->eFileLock!=pInode->eFileLock &&
2786 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002787 ){
2788 rc = SQLITE_BUSY;
2789 goto afp_end_lock;
2790 }
2791
2792 /* If a SHARED lock is requested, and some thread using this PID already
2793 ** has a SHARED or RESERVED lock, then increment reference counts and
2794 ** return SQLITE_OK.
2795 */
drh308c2a52010-05-14 11:30:18 +00002796 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002797 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002798 assert( eFileLock==SHARED_LOCK );
2799 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002800 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002801 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002802 pInode->nShared++;
2803 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002804 goto afp_end_lock;
2805 }
drhbfe66312006-10-03 17:40:40 +00002806
2807 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002808 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2809 ** be released.
2810 */
drh308c2a52010-05-14 11:30:18 +00002811 if( eFileLock==SHARED_LOCK
2812 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002813 ){
2814 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002815 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002816 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002817 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002818 goto afp_end_lock;
2819 }
2820 }
2821
2822 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002823 ** operating system calls for the specified lock.
2824 */
drh308c2a52010-05-14 11:30:18 +00002825 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002826 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002827 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002828
drh8af6c222010-05-14 12:43:01 +00002829 assert( pInode->nShared==0 );
2830 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002831
2832 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002833 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002834 /* note that the quality of the randomness doesn't matter that much */
2835 lk = random();
drh8af6c222010-05-14 12:43:01 +00002836 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002837 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002838 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002839 if( IS_LOCK_ERROR(lrc1) ){
2840 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002841 }
aswift5b1a2562008-08-22 00:22:35 +00002842 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002843 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002844
aswift5b1a2562008-08-22 00:22:35 +00002845 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002846 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002847 rc = lrc1;
2848 goto afp_end_lock;
2849 } else if( IS_LOCK_ERROR(lrc2) ){
2850 rc = lrc2;
2851 goto afp_end_lock;
2852 } else if( lrc1 != SQLITE_OK ) {
2853 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002854 } else {
drh308c2a52010-05-14 11:30:18 +00002855 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002856 pInode->nLock++;
2857 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002858 }
drh8af6c222010-05-14 12:43:01 +00002859 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002860 /* We are trying for an exclusive lock but another thread in this
2861 ** same process is still holding a shared lock. */
2862 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002863 }else{
2864 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2865 ** assumed that there is a SHARED or greater lock on the file
2866 ** already.
2867 */
2868 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002869 assert( 0!=pFile->eFileLock );
2870 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002871 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002872 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002873 if( !failed ){
2874 context->reserved = 1;
2875 }
drhbfe66312006-10-03 17:40:40 +00002876 }
drh308c2a52010-05-14 11:30:18 +00002877 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002878 /* Acquire an EXCLUSIVE lock */
2879
2880 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002881 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002882 */
drh6b9d6dd2008-12-03 19:34:47 +00002883 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002884 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002885 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002886 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002887 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002888 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002889 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002890 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002891 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2892 ** a critical I/O error
2893 */
2894 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2895 SQLITE_IOERR_LOCK;
2896 goto afp_end_lock;
2897 }
2898 }else{
aswift5b1a2562008-08-22 00:22:35 +00002899 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002900 }
2901 }
aswift5b1a2562008-08-22 00:22:35 +00002902 if( failed ){
2903 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002904 }
2905 }
2906
2907 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002908 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002909 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002910 }else if( eFileLock==EXCLUSIVE_LOCK ){
2911 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002912 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002913 }
2914
2915afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002916 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002917 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2918 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002919 return rc;
2920}
2921
2922/*
drh308c2a52010-05-14 11:30:18 +00002923** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002924** must be either NO_LOCK or SHARED_LOCK.
2925**
2926** If the locking level of the file descriptor is already at or below
2927** the requested locking level, this routine is a no-op.
2928*/
drh308c2a52010-05-14 11:30:18 +00002929static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002930 int rc = SQLITE_OK;
2931 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002932 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002933 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2934 int skipShared = 0;
2935#ifdef SQLITE_TEST
2936 int h = pFile->h;
2937#endif
drhbfe66312006-10-03 17:40:40 +00002938
2939 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002940 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002941 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002942 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002943
drh308c2a52010-05-14 11:30:18 +00002944 assert( eFileLock<=SHARED_LOCK );
2945 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002946 return SQLITE_OK;
2947 }
drh6c7d5c52008-11-21 20:32:33 +00002948 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002949 pInode = pFile->pInode;
2950 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002951 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002952 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002953 SimulateIOErrorBenign(1);
2954 SimulateIOError( h=(-1) )
2955 SimulateIOErrorBenign(0);
2956
drhd3d8c042012-05-29 17:02:40 +00002957#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002958 /* When reducing a lock such that other processes can start
2959 ** reading the database file again, make sure that the
2960 ** transaction counter was updated if any part of the database
2961 ** file changed. If the transaction counter is not updated,
2962 ** other connections to the same file might not realize that
2963 ** the file has changed and hence might not know to flush their
2964 ** cache. The use of a stale cache can lead to database corruption.
2965 */
2966 assert( pFile->inNormalWrite==0
2967 || pFile->dbUpdate==0
2968 || pFile->transCntrChng==1 );
2969 pFile->inNormalWrite = 0;
2970#endif
aswiftaebf4132008-11-21 00:10:35 +00002971
drh308c2a52010-05-14 11:30:18 +00002972 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002973 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002974 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002975 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002976 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002977 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2978 } else {
2979 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00002980 }
2981 }
drh308c2a52010-05-14 11:30:18 +00002982 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002983 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00002984 }
drh308c2a52010-05-14 11:30:18 +00002985 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00002986 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2987 if( !rc ){
2988 context->reserved = 0;
2989 }
aswiftaebf4132008-11-21 00:10:35 +00002990 }
drh8af6c222010-05-14 12:43:01 +00002991 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2992 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00002993 }
aswiftaebf4132008-11-21 00:10:35 +00002994 }
drh308c2a52010-05-14 11:30:18 +00002995 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00002996
drh7ed97b92010-01-20 13:07:21 +00002997 /* Decrement the shared lock counter. Release the lock using an
2998 ** OS call only when all threads in this same process have released
2999 ** the lock.
3000 */
drh8af6c222010-05-14 12:43:01 +00003001 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3002 pInode->nShared--;
3003 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003004 SimulateIOErrorBenign(1);
3005 SimulateIOError( h=(-1) )
3006 SimulateIOErrorBenign(0);
3007 if( !skipShared ){
3008 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3009 }
3010 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003011 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003012 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003013 }
3014 }
3015 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003016 pInode->nLock--;
3017 assert( pInode->nLock>=0 );
3018 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003019 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003020 }
3021 }
drhbfe66312006-10-03 17:40:40 +00003022 }
drh7ed97b92010-01-20 13:07:21 +00003023
drh6c7d5c52008-11-21 20:32:33 +00003024 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003025 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003026 return rc;
3027}
3028
3029/*
drh339eb0b2008-03-07 15:34:11 +00003030** Close a file & cleanup AFP specific locking context
3031*/
danielk1977e339d652008-06-28 11:23:00 +00003032static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003033 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003034 unixFile *pFile = (unixFile*)id;
3035 assert( id!=0 );
3036 afpUnlock(id, NO_LOCK);
3037 unixEnterMutex();
3038 if( pFile->pInode && pFile->pInode->nLock ){
3039 /* If there are outstanding locks, do not actually close the file just
3040 ** yet because that would clear those locks. Instead, add the file
3041 ** descriptor to pInode->aPending. It will be automatically closed when
3042 ** the last lock is cleared.
3043 */
3044 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003045 }
drha8de1e12015-11-30 00:05:39 +00003046 releaseInodeInfo(pFile);
3047 sqlite3_free(pFile->lockingContext);
3048 rc = closeUnixFile(id);
3049 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003050 return rc;
drhbfe66312006-10-03 17:40:40 +00003051}
3052
drhd2cb50b2009-01-09 21:41:17 +00003053#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003054/*
3055** The code above is the AFP lock implementation. The code is specific
3056** to MacOSX and does not work on other unix platforms. No alternative
3057** is available. If you don't compile for a mac, then the "unix-afp"
3058** VFS is not available.
3059**
3060********************* End of the AFP lock implementation **********************
3061******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003062
drh7ed97b92010-01-20 13:07:21 +00003063/******************************************************************************
3064*************************** Begin NFS Locking ********************************/
3065
3066#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3067/*
drh308c2a52010-05-14 11:30:18 +00003068 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003069 ** must be either NO_LOCK or SHARED_LOCK.
3070 **
3071 ** If the locking level of the file descriptor is already at or below
3072 ** the requested locking level, this routine is a no-op.
3073 */
drh308c2a52010-05-14 11:30:18 +00003074static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003075 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003076}
3077
3078#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3079/*
3080** The code above is the NFS lock implementation. The code is specific
3081** to MacOSX and does not work on other unix platforms. No alternative
3082** is available.
3083**
3084********************* End of the NFS lock implementation **********************
3085******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003086
3087/******************************************************************************
3088**************** Non-locking sqlite3_file methods *****************************
3089**
3090** The next division contains implementations for all methods of the
3091** sqlite3_file object other than the locking methods. The locking
3092** methods were defined in divisions above (one locking method per
3093** division). Those methods that are common to all locking modes
3094** are gather together into this division.
3095*/
drhbfe66312006-10-03 17:40:40 +00003096
3097/*
drh734c9862008-11-28 15:37:20 +00003098** Seek to the offset passed as the second argument, then read cnt
3099** bytes into pBuf. Return the number of bytes actually read.
3100**
3101** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3102** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3103** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003104** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003105** See tickets #2741 and #2681.
3106**
3107** To avoid stomping the errno value on a failed read the lastErrno value
3108** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003109*/
drh734c9862008-11-28 15:37:20 +00003110static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3111 int got;
drh58024642011-11-07 18:16:00 +00003112 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003113#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3114 i64 newOffset;
3115#endif
drh734c9862008-11-28 15:37:20 +00003116 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003117 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003118 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003119 do{
drh734c9862008-11-28 15:37:20 +00003120#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003121 got = osPread(id->h, pBuf, cnt, offset);
3122 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003123#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003124 got = osPread64(id->h, pBuf, cnt, offset);
3125 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003126#else
drha46cadc2016-03-04 03:02:06 +00003127 newOffset = lseek(id->h, offset, SEEK_SET);
3128 SimulateIOError( newOffset = -1 );
3129 if( newOffset<0 ){
3130 storeLastErrno((unixFile*)id, errno);
3131 return -1;
3132 }
3133 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003134#endif
drh58024642011-11-07 18:16:00 +00003135 if( got==cnt ) break;
3136 if( got<0 ){
3137 if( errno==EINTR ){ got = 1; continue; }
3138 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003139 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003140 break;
3141 }else if( got>0 ){
3142 cnt -= got;
3143 offset += got;
3144 prior += got;
3145 pBuf = (void*)(got + (char*)pBuf);
3146 }
3147 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003148 TIMER_END;
drh58024642011-11-07 18:16:00 +00003149 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3150 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3151 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003152}
3153
3154/*
drh734c9862008-11-28 15:37:20 +00003155** Read data from a file into a buffer. Return SQLITE_OK if all
3156** bytes were read successfully and SQLITE_IOERR if anything goes
3157** wrong.
drh339eb0b2008-03-07 15:34:11 +00003158*/
drh734c9862008-11-28 15:37:20 +00003159static int unixRead(
3160 sqlite3_file *id,
3161 void *pBuf,
3162 int amt,
3163 sqlite3_int64 offset
3164){
dan08da86a2009-08-21 17:18:03 +00003165 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003166 int got;
3167 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003168 assert( offset>=0 );
3169 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003170
dan08da86a2009-08-21 17:18:03 +00003171 /* If this is a database file (not a journal, master-journal or temp
3172 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003173#if 0
dane946c392009-08-22 11:39:46 +00003174 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003175 || offset>=PENDING_BYTE+512
3176 || offset+amt<=PENDING_BYTE
3177 );
dan7c246102010-04-12 19:00:29 +00003178#endif
drh08c6d442009-02-09 17:34:07 +00003179
drh9b4c59f2013-04-15 17:03:42 +00003180#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003181 /* Deal with as much of this read request as possible by transfering
3182 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003183 if( offset<pFile->mmapSize ){
3184 if( offset+amt <= pFile->mmapSize ){
3185 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3186 return SQLITE_OK;
3187 }else{
3188 int nCopy = pFile->mmapSize - offset;
3189 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3190 pBuf = &((u8 *)pBuf)[nCopy];
3191 amt -= nCopy;
3192 offset += nCopy;
3193 }
3194 }
drh6e0b6d52013-04-09 16:19:20 +00003195#endif
danf23da962013-03-23 21:00:41 +00003196
dan08da86a2009-08-21 17:18:03 +00003197 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003198 if( got==amt ){
3199 return SQLITE_OK;
3200 }else if( got<0 ){
3201 /* lastErrno set by seekAndRead */
3202 return SQLITE_IOERR_READ;
3203 }else{
drh4bf66fd2015-02-19 02:43:02 +00003204 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003205 /* Unread parts of the buffer must be zero-filled */
3206 memset(&((char*)pBuf)[got], 0, amt-got);
3207 return SQLITE_IOERR_SHORT_READ;
3208 }
3209}
3210
3211/*
dan47a2b4a2013-04-26 16:09:29 +00003212** Attempt to seek the file-descriptor passed as the first argument to
3213** absolute offset iOff, then attempt to write nBuf bytes of data from
3214** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3215** return the actual number of bytes written (which may be less than
3216** nBuf).
3217*/
3218static int seekAndWriteFd(
3219 int fd, /* File descriptor to write to */
3220 i64 iOff, /* File offset to begin writing at */
3221 const void *pBuf, /* Copy data from this buffer to the file */
3222 int nBuf, /* Size of buffer pBuf in bytes */
3223 int *piErrno /* OUT: Error number if error occurs */
3224){
3225 int rc = 0; /* Value returned by system call */
3226
3227 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003228 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003229 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003230 nBuf &= 0x1ffff;
3231 TIMER_START;
3232
3233#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003234 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003235#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003236 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003237#else
3238 do{
3239 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003240 SimulateIOError( iSeek = -1 );
3241 if( iSeek<0 ){
3242 rc = -1;
3243 break;
dan47a2b4a2013-04-26 16:09:29 +00003244 }
3245 rc = osWrite(fd, pBuf, nBuf);
3246 }while( rc<0 && errno==EINTR );
3247#endif
3248
3249 TIMER_END;
3250 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3251
drhe1818ec2015-12-01 16:21:35 +00003252 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003253 return rc;
3254}
3255
3256
3257/*
drh734c9862008-11-28 15:37:20 +00003258** Seek to the offset in id->offset then read cnt bytes into pBuf.
3259** Return the number of bytes actually read. Update the offset.
3260**
3261** To avoid stomping the errno value on a failed write the lastErrno value
3262** is set before returning.
3263*/
3264static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003265 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003266}
3267
3268
3269/*
3270** Write data from a buffer into a file. Return SQLITE_OK on success
3271** or some other error code on failure.
3272*/
3273static int unixWrite(
3274 sqlite3_file *id,
3275 const void *pBuf,
3276 int amt,
3277 sqlite3_int64 offset
3278){
dan08da86a2009-08-21 17:18:03 +00003279 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003280 int wrote = 0;
3281 assert( id );
3282 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003283
dan08da86a2009-08-21 17:18:03 +00003284 /* If this is a database file (not a journal, master-journal or temp
3285 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003286#if 0
dane946c392009-08-22 11:39:46 +00003287 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003288 || offset>=PENDING_BYTE+512
3289 || offset+amt<=PENDING_BYTE
3290 );
dan7c246102010-04-12 19:00:29 +00003291#endif
drh08c6d442009-02-09 17:34:07 +00003292
drhd3d8c042012-05-29 17:02:40 +00003293#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003294 /* If we are doing a normal write to a database file (as opposed to
3295 ** doing a hot-journal rollback or a write to some file other than a
3296 ** normal database file) then record the fact that the database
3297 ** has changed. If the transaction counter is modified, record that
3298 ** fact too.
3299 */
dan08da86a2009-08-21 17:18:03 +00003300 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003301 pFile->dbUpdate = 1; /* The database has been modified */
3302 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003303 int rc;
drh8f941bc2009-01-14 23:03:40 +00003304 char oldCntr[4];
3305 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003306 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003307 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003308 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003309 pFile->transCntrChng = 1; /* The transaction counter has changed */
3310 }
3311 }
3312 }
3313#endif
3314
danfe33e392015-11-17 20:56:06 +00003315#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003316 /* Deal with as much of this write request as possible by transfering
3317 ** data from the memory mapping using memcpy(). */
3318 if( offset<pFile->mmapSize ){
3319 if( offset+amt <= pFile->mmapSize ){
3320 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3321 return SQLITE_OK;
3322 }else{
3323 int nCopy = pFile->mmapSize - offset;
3324 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3325 pBuf = &((u8 *)pBuf)[nCopy];
3326 amt -= nCopy;
3327 offset += nCopy;
3328 }
3329 }
drh6e0b6d52013-04-09 16:19:20 +00003330#endif
drh02bf8b42015-09-01 23:51:53 +00003331
3332 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003333 amt -= wrote;
3334 offset += wrote;
3335 pBuf = &((char*)pBuf)[wrote];
3336 }
3337 SimulateIOError(( wrote=(-1), amt=1 ));
3338 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003339
drh02bf8b42015-09-01 23:51:53 +00003340 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003341 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003342 /* lastErrno set by seekAndWrite */
3343 return SQLITE_IOERR_WRITE;
3344 }else{
drh4bf66fd2015-02-19 02:43:02 +00003345 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003346 return SQLITE_FULL;
3347 }
3348 }
dan6e09d692010-07-27 18:34:15 +00003349
drh734c9862008-11-28 15:37:20 +00003350 return SQLITE_OK;
3351}
3352
3353#ifdef SQLITE_TEST
3354/*
3355** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003356** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003357*/
3358int sqlite3_sync_count = 0;
3359int sqlite3_fullsync_count = 0;
3360#endif
3361
3362/*
drh89240432009-03-25 01:06:01 +00003363** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003364** Others do no. To be safe, we will stick with the (slightly slower)
3365** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003366** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003367*/
drhf7a4a1b2015-01-10 18:02:45 +00003368#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003369# define fdatasync fsync
3370#endif
3371
3372/*
3373** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3374** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3375** only available on Mac OS X. But that could change.
3376*/
3377#ifdef F_FULLFSYNC
3378# define HAVE_FULLFSYNC 1
3379#else
3380# define HAVE_FULLFSYNC 0
3381#endif
3382
3383
3384/*
3385** The fsync() system call does not work as advertised on many
3386** unix systems. The following procedure is an attempt to make
3387** it work better.
3388**
3389** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3390** for testing when we want to run through the test suite quickly.
3391** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3392** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3393** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003394**
3395** SQLite sets the dataOnly flag if the size of the file is unchanged.
3396** The idea behind dataOnly is that it should only write the file content
3397** to disk, not the inode. We only set dataOnly if the file size is
3398** unchanged since the file size is part of the inode. However,
3399** Ted Ts'o tells us that fdatasync() will also write the inode if the
3400** file size has changed. The only real difference between fdatasync()
3401** and fsync(), Ted tells us, is that fdatasync() will not flush the
3402** inode if the mtime or owner or other inode attributes have changed.
3403** We only care about the file size, not the other file attributes, so
3404** as far as SQLite is concerned, an fdatasync() is always adequate.
3405** So, we always use fdatasync() if it is available, regardless of
3406** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003407*/
3408static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003409 int rc;
drh734c9862008-11-28 15:37:20 +00003410
3411 /* The following "ifdef/elif/else/" block has the same structure as
3412 ** the one below. It is replicated here solely to avoid cluttering
3413 ** up the real code with the UNUSED_PARAMETER() macros.
3414 */
3415#ifdef SQLITE_NO_SYNC
3416 UNUSED_PARAMETER(fd);
3417 UNUSED_PARAMETER(fullSync);
3418 UNUSED_PARAMETER(dataOnly);
3419#elif HAVE_FULLFSYNC
3420 UNUSED_PARAMETER(dataOnly);
3421#else
3422 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003423 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003424#endif
3425
3426 /* Record the number of times that we do a normal fsync() and
3427 ** FULLSYNC. This is used during testing to verify that this procedure
3428 ** gets called with the correct arguments.
3429 */
3430#ifdef SQLITE_TEST
3431 if( fullSync ) sqlite3_fullsync_count++;
3432 sqlite3_sync_count++;
3433#endif
3434
3435 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003436 ** no-op. But go ahead and call fstat() to validate the file
3437 ** descriptor as we need a method to provoke a failure during
3438 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003439 */
3440#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003441 {
3442 struct stat buf;
3443 rc = osFstat(fd, &buf);
3444 }
drh734c9862008-11-28 15:37:20 +00003445#elif HAVE_FULLFSYNC
3446 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003447 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003448 }else{
3449 rc = 1;
3450 }
3451 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003452 ** It shouldn't be possible for fullfsync to fail on the local
3453 ** file system (on OSX), so failure indicates that FULLFSYNC
3454 ** isn't supported for this file system. So, attempt an fsync
3455 ** and (for now) ignore the overhead of a superfluous fcntl call.
3456 ** It'd be better to detect fullfsync support once and avoid
3457 ** the fcntl call every time sync is called.
3458 */
drh734c9862008-11-28 15:37:20 +00003459 if( rc ) rc = fsync(fd);
3460
drh7ed97b92010-01-20 13:07:21 +00003461#elif defined(__APPLE__)
3462 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3463 ** so currently we default to the macro that redefines fdatasync to fsync
3464 */
3465 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003466#else
drh0b647ff2009-03-21 14:41:04 +00003467 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003468#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003469 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003470 rc = fsync(fd);
3471 }
drh0b647ff2009-03-21 14:41:04 +00003472#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003473#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3474
3475 if( OS_VXWORKS && rc!= -1 ){
3476 rc = 0;
3477 }
chw97185482008-11-17 08:05:31 +00003478 return rc;
drhbfe66312006-10-03 17:40:40 +00003479}
3480
drh734c9862008-11-28 15:37:20 +00003481/*
drh0059eae2011-08-08 23:48:40 +00003482** Open a file descriptor to the directory containing file zFilename.
3483** If successful, *pFd is set to the opened file descriptor and
3484** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3485** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3486** value.
3487**
drh90315a22011-08-10 01:52:12 +00003488** The directory file descriptor is used for only one thing - to
3489** fsync() a directory to make sure file creation and deletion events
3490** are flushed to disk. Such fsyncs are not needed on newer
3491** journaling filesystems, but are required on older filesystems.
3492**
3493** This routine can be overridden using the xSetSysCall interface.
3494** The ability to override this routine was added in support of the
3495** chromium sandbox. Opening a directory is a security risk (we are
3496** told) so making it overrideable allows the chromium sandbox to
3497** replace this routine with a harmless no-op. To make this routine
3498** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3499** *pFd set to a negative number.
3500**
drh0059eae2011-08-08 23:48:40 +00003501** If SQLITE_OK is returned, the caller is responsible for closing
3502** the file descriptor *pFd using close().
3503*/
3504static int openDirectory(const char *zFilename, int *pFd){
3505 int ii;
3506 int fd = -1;
3507 char zDirname[MAX_PATHNAME+1];
3508
3509 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003510 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3511 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003512 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003513 }else{
3514 if( zDirname[0]!='/' ) zDirname[0] = '.';
3515 zDirname[1] = 0;
3516 }
3517 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3518 if( fd>=0 ){
3519 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003520 }
3521 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003522 if( fd>=0 ) return SQLITE_OK;
3523 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003524}
3525
3526/*
drh734c9862008-11-28 15:37:20 +00003527** Make sure all writes to a particular file are committed to disk.
3528**
3529** If dataOnly==0 then both the file itself and its metadata (file
3530** size, access time, etc) are synced. If dataOnly!=0 then only the
3531** file data is synced.
3532**
3533** Under Unix, also make sure that the directory entry for the file
3534** has been created by fsync-ing the directory that contains the file.
3535** If we do not do this and we encounter a power failure, the directory
3536** entry for the journal might not exist after we reboot. The next
3537** SQLite to access the file will not know that the journal exists (because
3538** the directory entry for the journal was never created) and the transaction
3539** will not roll back - possibly leading to database corruption.
3540*/
3541static int unixSync(sqlite3_file *id, int flags){
3542 int rc;
3543 unixFile *pFile = (unixFile*)id;
3544
3545 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3546 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3547
3548 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3549 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3550 || (flags&0x0F)==SQLITE_SYNC_FULL
3551 );
3552
3553 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3554 ** line is to test that doing so does not cause any problems.
3555 */
3556 SimulateDiskfullError( return SQLITE_FULL );
3557
3558 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003559 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003560 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3561 SimulateIOError( rc=1 );
3562 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003563 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003564 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003565 }
drh0059eae2011-08-08 23:48:40 +00003566
3567 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003568 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003569 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003570 */
3571 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3572 int dirfd;
3573 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003574 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003575 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003576 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003577 full_fsync(dirfd, 0, 0);
3578 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003579 }else{
3580 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003581 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003582 }
drh0059eae2011-08-08 23:48:40 +00003583 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003584 }
3585 return rc;
3586}
3587
3588/*
3589** Truncate an open file to a specified size
3590*/
3591static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003592 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003593 int rc;
dan6e09d692010-07-27 18:34:15 +00003594 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003595 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003596
3597 /* If the user has configured a chunk-size for this file, truncate the
3598 ** file so that it consists of an integer number of chunks (i.e. the
3599 ** actual file size after the operation may be larger than the requested
3600 ** size).
3601 */
drhb8af4b72012-04-05 20:04:39 +00003602 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003603 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3604 }
3605
dan2ee53412014-09-06 16:49:40 +00003606 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003607 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003608 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003609 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003610 }else{
drhd3d8c042012-05-29 17:02:40 +00003611#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003612 /* If we are doing a normal write to a database file (as opposed to
3613 ** doing a hot-journal rollback or a write to some file other than a
3614 ** normal database file) and we truncate the file to zero length,
3615 ** that effectively updates the change counter. This might happen
3616 ** when restoring a database using the backup API from a zero-length
3617 ** source.
3618 */
dan6e09d692010-07-27 18:34:15 +00003619 if( pFile->inNormalWrite && nByte==0 ){
3620 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003621 }
danf23da962013-03-23 21:00:41 +00003622#endif
danc0003312013-03-22 17:46:11 +00003623
mistachkine98844f2013-08-24 00:59:24 +00003624#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003625 /* If the file was just truncated to a size smaller than the currently
3626 ** mapped region, reduce the effective mapping size as well. SQLite will
3627 ** use read() and write() to access data beyond this point from now on.
3628 */
3629 if( nByte<pFile->mmapSize ){
3630 pFile->mmapSize = nByte;
3631 }
mistachkine98844f2013-08-24 00:59:24 +00003632#endif
drh3313b142009-11-06 04:13:18 +00003633
drh734c9862008-11-28 15:37:20 +00003634 return SQLITE_OK;
3635 }
3636}
3637
3638/*
3639** Determine the current size of a file in bytes
3640*/
3641static int unixFileSize(sqlite3_file *id, i64 *pSize){
3642 int rc;
3643 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003644 assert( id );
3645 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003646 SimulateIOError( rc=1 );
3647 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003648 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003649 return SQLITE_IOERR_FSTAT;
3650 }
3651 *pSize = buf.st_size;
3652
drh8af6c222010-05-14 12:43:01 +00003653 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003654 ** writes a single byte into that file in order to work around a bug
3655 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3656 ** layers, we need to report this file size as zero even though it is
3657 ** really 1. Ticket #3260.
3658 */
3659 if( *pSize==1 ) *pSize = 0;
3660
3661
3662 return SQLITE_OK;
3663}
3664
drhd2cb50b2009-01-09 21:41:17 +00003665#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003666/*
3667** Handler for proxy-locking file-control verbs. Defined below in the
3668** proxying locking division.
3669*/
3670static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003671#endif
drh715ff302008-12-03 22:32:44 +00003672
dan502019c2010-07-28 14:26:17 +00003673/*
3674** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003675** file-control operation. Enlarge the database to nBytes in size
3676** (rounded up to the next chunk-size). If the database is already
3677** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003678*/
3679static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003680 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003681 i64 nSize; /* Required file size */
3682 struct stat buf; /* Used to hold return values of fstat() */
3683
drh4bf66fd2015-02-19 02:43:02 +00003684 if( osFstat(pFile->h, &buf) ){
3685 return SQLITE_IOERR_FSTAT;
3686 }
dan502019c2010-07-28 14:26:17 +00003687
3688 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3689 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003690
dan502019c2010-07-28 14:26:17 +00003691#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003692 /* The code below is handling the return value of osFallocate()
3693 ** correctly. posix_fallocate() is defined to "returns zero on success,
3694 ** or an error number on failure". See the manpage for details. */
3695 int err;
drhff812312011-02-23 13:33:46 +00003696 do{
dan661d71a2011-03-30 19:08:03 +00003697 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3698 }while( err==EINTR );
3699 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003700#else
dan592bf7f2014-12-30 19:58:31 +00003701 /* If the OS does not have posix_fallocate(), fake it. Write a
3702 ** single byte to the last byte in each block that falls entirely
3703 ** within the extended region. Then, if required, a single byte
3704 ** at offset (nSize-1), to set the size of the file correctly.
3705 ** This is a similar technique to that used by glibc on systems
3706 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003707 */
3708 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003709 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003710 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003711
drh053378d2015-12-01 22:09:42 +00003712 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003713 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003714 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003715 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3716 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003717 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003718 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003719 }
dan502019c2010-07-28 14:26:17 +00003720#endif
3721 }
3722 }
3723
mistachkine98844f2013-08-24 00:59:24 +00003724#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003725 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003726 int rc;
3727 if( pFile->szChunk<=0 ){
3728 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003729 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003730 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3731 }
3732 }
3733
3734 rc = unixMapfile(pFile, nByte);
3735 return rc;
3736 }
mistachkine98844f2013-08-24 00:59:24 +00003737#endif
danf23da962013-03-23 21:00:41 +00003738
dan502019c2010-07-28 14:26:17 +00003739 return SQLITE_OK;
3740}
danielk1977ad94b582007-08-20 06:44:22 +00003741
danielk1977e3026632004-06-22 11:29:02 +00003742/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003743** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003744** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3745**
3746** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3747*/
3748static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3749 if( *pArg<0 ){
3750 *pArg = (pFile->ctrlFlags & mask)!=0;
3751 }else if( (*pArg)==0 ){
3752 pFile->ctrlFlags &= ~mask;
3753 }else{
3754 pFile->ctrlFlags |= mask;
3755 }
3756}
3757
drh696b33e2012-12-06 19:01:42 +00003758/* Forward declaration */
3759static int unixGetTempname(int nBuf, char *zBuf);
3760
drhf12b3f62011-12-21 14:42:29 +00003761/*
drh9e33c2c2007-08-31 18:34:59 +00003762** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003763*/
drhcc6bb3e2007-08-31 16:11:35 +00003764static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003765 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003766 switch( op ){
3767 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003768 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003769 return SQLITE_OK;
3770 }
drh4bf66fd2015-02-19 02:43:02 +00003771 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003772 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003773 return SQLITE_OK;
3774 }
dan6e09d692010-07-27 18:34:15 +00003775 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003776 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003777 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003778 }
drh9ff27ec2010-05-19 19:26:05 +00003779 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003780 int rc;
3781 SimulateIOErrorBenign(1);
3782 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3783 SimulateIOErrorBenign(0);
3784 return rc;
drhf0b190d2011-07-26 16:03:07 +00003785 }
3786 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003787 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3788 return SQLITE_OK;
3789 }
drhcb15f352011-12-23 01:04:17 +00003790 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3791 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003792 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003793 }
drhde60fc22011-12-14 17:53:36 +00003794 case SQLITE_FCNTL_VFSNAME: {
3795 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3796 return SQLITE_OK;
3797 }
drh696b33e2012-12-06 19:01:42 +00003798 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003799 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003800 if( zTFile ){
3801 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3802 *(char**)pArg = zTFile;
3803 }
3804 return SQLITE_OK;
3805 }
drhb959a012013-12-07 12:29:22 +00003806 case SQLITE_FCNTL_HAS_MOVED: {
3807 *(int*)pArg = fileHasMoved(pFile);
3808 return SQLITE_OK;
3809 }
mistachkine98844f2013-08-24 00:59:24 +00003810#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003811 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003812 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003813 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003814 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3815 newLimit = sqlite3GlobalConfig.mxMmap;
3816 }
3817 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003818 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003819 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003820 if( pFile->mmapSize>0 ){
3821 unixUnmapfile(pFile);
3822 rc = unixMapfile(pFile, -1);
3823 }
danbcb8a862013-04-08 15:30:41 +00003824 }
drh34e258c2013-05-23 01:40:53 +00003825 return rc;
danb2d3de32013-03-14 18:34:37 +00003826 }
mistachkine98844f2013-08-24 00:59:24 +00003827#endif
drhd3d8c042012-05-29 17:02:40 +00003828#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003829 /* The pager calls this method to signal that it has done
3830 ** a rollback and that the database is therefore unchanged and
3831 ** it hence it is OK for the transaction change counter to be
3832 ** unchanged.
3833 */
3834 case SQLITE_FCNTL_DB_UNCHANGED: {
3835 ((unixFile*)id)->dbUpdate = 0;
3836 return SQLITE_OK;
3837 }
3838#endif
drhd2cb50b2009-01-09 21:41:17 +00003839#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003840 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3841 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003842 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003843 }
drhd2cb50b2009-01-09 21:41:17 +00003844#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003845 }
drh0b52b7d2011-01-26 19:46:22 +00003846 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003847}
3848
3849/*
danielk1977a3d4c882007-03-23 10:08:38 +00003850** Return the sector size in bytes of the underlying block device for
3851** the specified file. This is almost always 512 bytes, but may be
3852** larger for some devices.
3853**
3854** SQLite code assumes this function cannot fail. It also assumes that
3855** if two files are created in the same file-system directory (i.e.
drh85b623f2007-12-13 21:54:09 +00003856** a database and its journal file) that the sector size will be the
danielk1977a3d4c882007-03-23 10:08:38 +00003857** same for both.
3858*/
drh537dddf2012-10-26 13:46:24 +00003859#ifndef __QNXNTO__
3860static int unixSectorSize(sqlite3_file *NotUsed){
3861 UNUSED_PARAMETER(NotUsed);
drh8942d412012-01-02 18:20:14 +00003862 return SQLITE_DEFAULT_SECTOR_SIZE;
danielk1977a3d4c882007-03-23 10:08:38 +00003863}
drh537dddf2012-10-26 13:46:24 +00003864#endif
3865
3866/*
3867** The following version of unixSectorSize() is optimized for QNX.
3868*/
3869#ifdef __QNXNTO__
3870#include <sys/dcmd_blk.h>
3871#include <sys/statvfs.h>
3872static int unixSectorSize(sqlite3_file *id){
3873 unixFile *pFile = (unixFile*)id;
3874 if( pFile->sectorSize == 0 ){
3875 struct statvfs fsInfo;
3876
3877 /* Set defaults for non-supported filesystems */
3878 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3879 pFile->deviceCharacteristics = 0;
3880 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3881 return pFile->sectorSize;
3882 }
3883
3884 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3885 pFile->sectorSize = fsInfo.f_bsize;
3886 pFile->deviceCharacteristics =
3887 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3888 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3889 ** the write succeeds */
3890 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3891 ** so it is ordered */
3892 0;
3893 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3894 pFile->sectorSize = fsInfo.f_bsize;
3895 pFile->deviceCharacteristics =
3896 /* etfs cluster size writes are atomic */
3897 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3898 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3899 ** the write succeeds */
3900 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3901 ** so it is ordered */
3902 0;
3903 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3904 pFile->sectorSize = fsInfo.f_bsize;
3905 pFile->deviceCharacteristics =
3906 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3907 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3908 ** the write succeeds */
3909 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3910 ** so it is ordered */
3911 0;
3912 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3913 pFile->sectorSize = fsInfo.f_bsize;
3914 pFile->deviceCharacteristics =
3915 /* full bitset of atomics from max sector size and smaller */
3916 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3917 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3918 ** so it is ordered */
3919 0;
3920 }else if( strstr(fsInfo.f_basetype, "dos") ){
3921 pFile->sectorSize = fsInfo.f_bsize;
3922 pFile->deviceCharacteristics =
3923 /* full bitset of atomics from max sector size and smaller */
3924 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3925 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3926 ** so it is ordered */
3927 0;
3928 }else{
3929 pFile->deviceCharacteristics =
3930 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3931 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3932 ** the write succeeds */
3933 0;
3934 }
3935 }
3936 /* Last chance verification. If the sector size isn't a multiple of 512
3937 ** then it isn't valid.*/
3938 if( pFile->sectorSize % 512 != 0 ){
3939 pFile->deviceCharacteristics = 0;
3940 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3941 }
3942 return pFile->sectorSize;
3943}
3944#endif /* __QNXNTO__ */
danielk1977a3d4c882007-03-23 10:08:38 +00003945
danielk197790949c22007-08-17 16:50:38 +00003946/*
drhf12b3f62011-12-21 14:42:29 +00003947** Return the device characteristics for the file.
3948**
drhcb15f352011-12-23 01:04:17 +00003949** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00003950** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00003951** file system does not always provide powersafe overwrites. (In other
3952** words, after a power-loss event, parts of the file that were never
3953** written might end up being altered.) However, non-PSOW behavior is very,
3954** very rare. And asserting PSOW makes a large reduction in the amount
3955** of required I/O for journaling, since a lot of padding is eliminated.
3956** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
3957** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00003958*/
drhf12b3f62011-12-21 14:42:29 +00003959static int unixDeviceCharacteristics(sqlite3_file *id){
3960 unixFile *p = (unixFile*)id;
drh537dddf2012-10-26 13:46:24 +00003961 int rc = 0;
3962#ifdef __QNXNTO__
3963 if( p->sectorSize==0 ) unixSectorSize(id);
3964 rc = p->deviceCharacteristics;
3965#endif
drhcb15f352011-12-23 01:04:17 +00003966 if( p->ctrlFlags & UNIXFILE_PSOW ){
drh537dddf2012-10-26 13:46:24 +00003967 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
drhcb15f352011-12-23 01:04:17 +00003968 }
drh537dddf2012-10-26 13:46:24 +00003969 return rc;
danielk197762079062007-08-15 17:08:46 +00003970}
3971
dan702eec12014-06-23 10:04:58 +00003972#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00003973
dan702eec12014-06-23 10:04:58 +00003974/*
3975** Return the system page size.
3976**
3977** This function should not be called directly by other code in this file.
3978** Instead, it should be called via macro osGetpagesize().
3979*/
3980static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00003981#if OS_VXWORKS
3982 return 1024;
3983#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00003984 return getpagesize();
3985#else
3986 return (int)sysconf(_SC_PAGESIZE);
3987#endif
3988}
3989
3990#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
3991
3992#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00003993
3994/*
drhd91c68f2010-05-14 14:52:25 +00003995** Object used to represent an shared memory buffer.
3996**
3997** When multiple threads all reference the same wal-index, each thread
3998** has its own unixShm object, but they all point to a single instance
3999** of this unixShmNode object. In other words, each wal-index is opened
4000** only once per process.
4001**
4002** Each unixShmNode object is connected to a single unixInodeInfo object.
4003** We could coalesce this object into unixInodeInfo, but that would mean
4004** every open file that does not use shared memory (in other words, most
4005** open files) would have to carry around this extra information. So
4006** the unixInodeInfo object contains a pointer to this unixShmNode object
4007** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004008**
4009** unixMutexHeld() must be true when creating or destroying
4010** this object or while reading or writing the following fields:
4011**
4012** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004013**
4014** The following fields are read-only after the object is created:
4015**
4016** fid
4017** zFilename
4018**
drhd91c68f2010-05-14 14:52:25 +00004019** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004020** unixMutexHeld() is true when reading or writing any other field
4021** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004022*/
drhd91c68f2010-05-14 14:52:25 +00004023struct unixShmNode {
4024 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004025 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004026 char *zFilename; /* Name of the mmapped file */
4027 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004028 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004029 u16 nRegion; /* Size of array apRegion */
4030 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004031 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004032 int nRef; /* Number of unixShm objects pointing to this */
4033 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004034#ifdef SQLITE_DEBUG
4035 u8 exclMask; /* Mask of exclusive locks held */
4036 u8 sharedMask; /* Mask of shared locks held */
4037 u8 nextShmId; /* Next available unixShm.id value */
4038#endif
4039};
4040
4041/*
drhd9e5c4f2010-05-12 18:01:39 +00004042** Structure used internally by this VFS to record the state of an
4043** open shared memory connection.
4044**
drhd91c68f2010-05-14 14:52:25 +00004045** The following fields are initialized when this object is created and
4046** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004047**
drhd91c68f2010-05-14 14:52:25 +00004048** unixShm.pFile
4049** unixShm.id
4050**
4051** All other fields are read/write. The unixShm.pFile->mutex must be held
4052** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004053*/
4054struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004055 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4056 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004057 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004058 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004059 u16 sharedMask; /* Mask of shared locks held */
4060 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004061};
4062
4063/*
drhd9e5c4f2010-05-12 18:01:39 +00004064** Constants used for locking
4065*/
drhbd9676c2010-06-23 17:58:38 +00004066#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004067#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004068
drhd9e5c4f2010-05-12 18:01:39 +00004069/*
drh73b64e42010-05-30 19:55:15 +00004070** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004071**
4072** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4073** otherwise.
4074*/
4075static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004076 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004077 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004078 int ofst, /* First byte of the locking range */
4079 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004080){
drhbbf76ee2015-03-10 20:22:35 +00004081 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4082 struct flock f; /* The posix advisory locking structure */
4083 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004084
drhd91c68f2010-05-14 14:52:25 +00004085 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004086 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004087 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004088
drh73b64e42010-05-30 19:55:15 +00004089 /* Shared locks never span more than one byte */
4090 assert( n==1 || lockType!=F_RDLCK );
4091
4092 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004093 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004094
drh3cb93392011-03-12 18:10:44 +00004095 if( pShmNode->h>=0 ){
4096 /* Initialize the locking parameters */
4097 memset(&f, 0, sizeof(f));
4098 f.l_type = lockType;
4099 f.l_whence = SEEK_SET;
4100 f.l_start = ofst;
4101 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004102
drhdcfb9652015-12-02 00:05:26 +00004103 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004104 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4105 }
drhd9e5c4f2010-05-12 18:01:39 +00004106
4107 /* Update the global lock state and do debug tracing */
4108#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004109 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004110 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004111 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004112 if( rc==SQLITE_OK ){
4113 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004114 OSTRACE(("unlock %d ok", ofst));
4115 pShmNode->exclMask &= ~mask;
4116 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004117 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004118 OSTRACE(("read-lock %d ok", ofst));
4119 pShmNode->exclMask &= ~mask;
4120 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004121 }else{
4122 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004123 OSTRACE(("write-lock %d ok", ofst));
4124 pShmNode->exclMask |= mask;
4125 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004126 }
4127 }else{
4128 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004129 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004130 }else if( lockType==F_RDLCK ){
4131 OSTRACE(("read-lock failed"));
4132 }else{
4133 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004134 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004135 }
4136 }
drh20e1f082010-05-31 16:10:12 +00004137 OSTRACE((" - afterwards %03x,%03x\n",
4138 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004139 }
drhd9e5c4f2010-05-12 18:01:39 +00004140#endif
4141
4142 return rc;
4143}
4144
dan781e34c2014-03-20 08:59:47 +00004145/*
dan781e34c2014-03-20 08:59:47 +00004146** Return the minimum number of 32KB shm regions that should be mapped at
4147** a time, assuming that each mapping must be an integer multiple of the
4148** current system page-size.
4149**
4150** Usually, this is 1. The exception seems to be systems that are configured
4151** to use 64KB pages - in this case each mapping must cover at least two
4152** shm regions.
4153*/
4154static int unixShmRegionPerMap(void){
4155 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004156 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004157 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4158 if( pgsz<shmsz ) return 1;
4159 return pgsz/shmsz;
4160}
drhd9e5c4f2010-05-12 18:01:39 +00004161
4162/*
drhd91c68f2010-05-14 14:52:25 +00004163** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004164**
4165** This is not a VFS shared-memory method; it is a utility function called
4166** by VFS shared-memory methods.
4167*/
drhd91c68f2010-05-14 14:52:25 +00004168static void unixShmPurge(unixFile *pFd){
4169 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004170 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004171 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004172 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004173 int i;
drhd91c68f2010-05-14 14:52:25 +00004174 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004175 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004176 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004177 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004178 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004179 }else{
4180 sqlite3_free(p->apRegion[i]);
4181 }
dan13a3cb82010-06-11 19:04:21 +00004182 }
dan18801912010-06-14 14:07:50 +00004183 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004184 if( p->h>=0 ){
4185 robust_close(pFd, p->h, __LINE__);
4186 p->h = -1;
4187 }
drhd91c68f2010-05-14 14:52:25 +00004188 p->pInode->pShmNode = 0;
4189 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004190 }
4191}
4192
4193/*
danda9fe0c2010-07-13 18:44:03 +00004194** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004195** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004196**
drh7234c6d2010-06-19 15:10:09 +00004197** The file used to implement shared-memory is in the same directory
4198** as the open database file and has the same name as the open database
4199** file with the "-shm" suffix added. For example, if the database file
4200** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004201** for shared memory will be called "/home/user1/config.db-shm".
4202**
4203** Another approach to is to use files in /dev/shm or /dev/tmp or an
4204** some other tmpfs mount. But if a file in a different directory
4205** from the database file is used, then differing access permissions
4206** or a chroot() might cause two different processes on the same
4207** database to end up using different files for shared memory -
4208** meaning that their memory would not really be shared - resulting
4209** in database corruption. Nevertheless, this tmpfs file usage
4210** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4211** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4212** option results in an incompatible build of SQLite; builds of SQLite
4213** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4214** same database file at the same time, database corruption will likely
4215** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4216** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004217**
4218** When opening a new shared-memory file, if no other instances of that
4219** file are currently open, in this process or in other processes, then
4220** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004221**
4222** If the original database file (pDbFd) is using the "unix-excl" VFS
4223** that means that an exclusive lock is held on the database file and
4224** that no other processes are able to read or write the database. In
4225** that case, we do not really need shared memory. No shared memory
4226** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004227*/
danda9fe0c2010-07-13 18:44:03 +00004228static int unixOpenSharedMemory(unixFile *pDbFd){
4229 struct unixShm *p = 0; /* The connection to be opened */
4230 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4231 int rc; /* Result code */
4232 unixInodeInfo *pInode; /* The inode of fd */
4233 char *zShmFilename; /* Name of the file used for SHM */
4234 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004235
danda9fe0c2010-07-13 18:44:03 +00004236 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004237 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004238 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004239 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004240 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004241
danda9fe0c2010-07-13 18:44:03 +00004242 /* Check to see if a unixShmNode object already exists. Reuse an existing
4243 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004244 */
4245 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004246 pInode = pDbFd->pInode;
4247 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004248 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004249 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004250#ifndef SQLITE_SHM_DIRECTORY
4251 const char *zBasePath = pDbFd->zPath;
4252#endif
danddb0ac42010-07-14 14:48:58 +00004253
4254 /* Call fstat() to figure out the permissions on the database file. If
4255 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004256 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004257 */
drhf3b1ed02015-12-02 13:11:03 +00004258 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004259 rc = SQLITE_IOERR_FSTAT;
4260 goto shm_open_err;
4261 }
4262
drha4ced192010-07-15 18:32:40 +00004263#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004264 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004265#else
drh4bf66fd2015-02-19 02:43:02 +00004266 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004267#endif
drhf3cdcdc2015-04-29 16:50:28 +00004268 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004269 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004270 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004271 goto shm_open_err;
4272 }
drh9cb5a0d2012-01-05 21:19:54 +00004273 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004274 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004275#ifdef SQLITE_SHM_DIRECTORY
4276 sqlite3_snprintf(nShmFilename, zShmFilename,
4277 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4278 (u32)sStat.st_ino, (u32)sStat.st_dev);
4279#else
drh4bf66fd2015-02-19 02:43:02 +00004280 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004281 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004282#endif
drhd91c68f2010-05-14 14:52:25 +00004283 pShmNode->h = -1;
4284 pDbFd->pInode->pShmNode = pShmNode;
4285 pShmNode->pInode = pDbFd->pInode;
4286 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4287 if( pShmNode->mutex==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004288 rc = SQLITE_NOMEM_BKPT;
drhd91c68f2010-05-14 14:52:25 +00004289 goto shm_open_err;
4290 }
drhd9e5c4f2010-05-12 18:01:39 +00004291
drh3cb93392011-03-12 18:10:44 +00004292 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004293 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004294 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004295 openFlags = O_RDONLY;
4296 pShmNode->isReadonly = 1;
4297 }
4298 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004299 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004300 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4301 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004302 }
drhac7c3ac2012-02-11 19:23:48 +00004303
4304 /* If this process is running as root, make sure that the SHM file
4305 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004306 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004307 */
drh6226ca22015-11-24 15:06:28 +00004308 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004309
4310 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004311 ** If not, truncate the file to zero length.
4312 */
4313 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004314 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004315 if( robust_ftruncate(pShmNode->h, 0) ){
4316 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004317 }
4318 }
drh66dfec8b2011-06-01 20:01:49 +00004319 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004320 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004321 }
4322 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004323 }
drhd9e5c4f2010-05-12 18:01:39 +00004324 }
4325
drhd91c68f2010-05-14 14:52:25 +00004326 /* Make the new connection a child of the unixShmNode */
4327 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004328#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004329 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004330#endif
drhd91c68f2010-05-14 14:52:25 +00004331 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004332 pDbFd->pShm = p;
4333 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004334
4335 /* The reference count on pShmNode has already been incremented under
4336 ** the cover of the unixEnterMutex() mutex and the pointer from the
4337 ** new (struct unixShm) object to the pShmNode has been set. All that is
4338 ** left to do is to link the new object into the linked list starting
4339 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4340 ** mutex.
4341 */
4342 sqlite3_mutex_enter(pShmNode->mutex);
4343 p->pNext = pShmNode->pFirst;
4344 pShmNode->pFirst = p;
4345 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004346 return SQLITE_OK;
4347
4348 /* Jump here on any error */
4349shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004350 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004351 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004352 unixLeaveMutex();
4353 return rc;
4354}
4355
4356/*
danda9fe0c2010-07-13 18:44:03 +00004357** This function is called to obtain a pointer to region iRegion of the
4358** shared-memory associated with the database file fd. Shared-memory regions
4359** are numbered starting from zero. Each shared-memory region is szRegion
4360** bytes in size.
4361**
4362** If an error occurs, an error code is returned and *pp is set to NULL.
4363**
4364** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4365** region has not been allocated (by any client, including one running in a
4366** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4367** bExtend is non-zero and the requested shared-memory region has not yet
4368** been allocated, it is allocated by this function.
4369**
4370** If the shared-memory region has already been allocated or is allocated by
4371** this call as described above, then it is mapped into this processes
4372** address space (if it is not already), *pp is set to point to the mapped
4373** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004374*/
danda9fe0c2010-07-13 18:44:03 +00004375static int unixShmMap(
4376 sqlite3_file *fd, /* Handle open on database file */
4377 int iRegion, /* Region to retrieve */
4378 int szRegion, /* Size of regions */
4379 int bExtend, /* True to extend file if necessary */
4380 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004381){
danda9fe0c2010-07-13 18:44:03 +00004382 unixFile *pDbFd = (unixFile*)fd;
4383 unixShm *p;
4384 unixShmNode *pShmNode;
4385 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004386 int nShmPerMap = unixShmRegionPerMap();
4387 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004388
danda9fe0c2010-07-13 18:44:03 +00004389 /* If the shared-memory file has not yet been opened, open it now. */
4390 if( pDbFd->pShm==0 ){
4391 rc = unixOpenSharedMemory(pDbFd);
4392 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004393 }
drhd9e5c4f2010-05-12 18:01:39 +00004394
danda9fe0c2010-07-13 18:44:03 +00004395 p = pDbFd->pShm;
4396 pShmNode = p->pShmNode;
4397 sqlite3_mutex_enter(pShmNode->mutex);
4398 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004399 assert( pShmNode->pInode==pDbFd->pInode );
4400 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4401 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004402
dan781e34c2014-03-20 08:59:47 +00004403 /* Minimum number of regions required to be mapped. */
4404 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4405
4406 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004407 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004408 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004409 struct stat sStat; /* Used by fstat() */
4410
4411 pShmNode->szRegion = szRegion;
4412
drh3cb93392011-03-12 18:10:44 +00004413 if( pShmNode->h>=0 ){
4414 /* The requested region is not mapped into this processes address space.
4415 ** Check to see if it has been allocated (i.e. if the wal-index file is
4416 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004417 */
drh3cb93392011-03-12 18:10:44 +00004418 if( osFstat(pShmNode->h, &sStat) ){
4419 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004420 goto shmpage_out;
4421 }
drh3cb93392011-03-12 18:10:44 +00004422
4423 if( sStat.st_size<nByte ){
4424 /* The requested memory region does not exist. If bExtend is set to
4425 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004426 */
dan47a2b4a2013-04-26 16:09:29 +00004427 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004428 goto shmpage_out;
4429 }
dan47a2b4a2013-04-26 16:09:29 +00004430
4431 /* Alternatively, if bExtend is true, extend the file. Do this by
4432 ** writing a single byte to the end of each (OS) page being
4433 ** allocated or extended. Technically, we need only write to the
4434 ** last page in order to extend the file. But writing to all new
4435 ** pages forces the OS to allocate them immediately, which reduces
4436 ** the chances of SIGBUS while accessing the mapped region later on.
4437 */
4438 else{
4439 static const int pgsz = 4096;
4440 int iPg;
4441
4442 /* Write to the last byte of each newly allocated or extended page */
4443 assert( (nByte % pgsz)==0 );
4444 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004445 int x = 0;
4446 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004447 const char *zFile = pShmNode->zFilename;
4448 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4449 goto shmpage_out;
4450 }
4451 }
drh3cb93392011-03-12 18:10:44 +00004452 }
4453 }
danda9fe0c2010-07-13 18:44:03 +00004454 }
4455
4456 /* Map the requested memory region into this processes address space. */
4457 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004458 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004459 );
4460 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004461 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004462 goto shmpage_out;
4463 }
4464 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004465 while( pShmNode->nRegion<nReqRegion ){
4466 int nMap = szRegion*nShmPerMap;
4467 int i;
drh3cb93392011-03-12 18:10:44 +00004468 void *pMem;
4469 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004470 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004471 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004472 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004473 );
4474 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004475 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004476 goto shmpage_out;
4477 }
4478 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004479 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004480 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004481 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004482 goto shmpage_out;
4483 }
4484 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004485 }
dan781e34c2014-03-20 08:59:47 +00004486
4487 for(i=0; i<nShmPerMap; i++){
4488 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4489 }
4490 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004491 }
4492 }
4493
4494shmpage_out:
4495 if( pShmNode->nRegion>iRegion ){
4496 *pp = pShmNode->apRegion[iRegion];
4497 }else{
4498 *pp = 0;
4499 }
drh66dfec8b2011-06-01 20:01:49 +00004500 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004501 sqlite3_mutex_leave(pShmNode->mutex);
4502 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004503}
4504
4505/*
drhd9e5c4f2010-05-12 18:01:39 +00004506** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004507**
4508** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4509** different here than in posix. In xShmLock(), one can go from unlocked
4510** to shared and back or from unlocked to exclusive and back. But one may
4511** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004512*/
4513static int unixShmLock(
4514 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004515 int ofst, /* First lock to acquire or release */
4516 int n, /* Number of locks to acquire or release */
4517 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004518){
drh73b64e42010-05-30 19:55:15 +00004519 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4520 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4521 unixShm *pX; /* For looping over all siblings */
4522 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4523 int rc = SQLITE_OK; /* Result code */
4524 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004525
drhd91c68f2010-05-14 14:52:25 +00004526 assert( pShmNode==pDbFd->pInode->pShmNode );
4527 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004528 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004529 assert( n>=1 );
4530 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4531 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4532 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4533 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4534 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004535 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4536 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004537
drhc99597c2010-05-31 01:41:15 +00004538 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004539 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004540 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004541 if( flags & SQLITE_SHM_UNLOCK ){
4542 u16 allMask = 0; /* Mask of locks held by siblings */
4543
4544 /* See if any siblings hold this same lock */
4545 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4546 if( pX==p ) continue;
4547 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4548 allMask |= pX->sharedMask;
4549 }
4550
4551 /* Unlock the system-level locks */
4552 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004553 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004554 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004555 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004556 }
drh73b64e42010-05-30 19:55:15 +00004557
4558 /* Undo the local locks */
4559 if( rc==SQLITE_OK ){
4560 p->exclMask &= ~mask;
4561 p->sharedMask &= ~mask;
4562 }
4563 }else if( flags & SQLITE_SHM_SHARED ){
4564 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4565
4566 /* Find out which shared locks are already held by sibling connections.
4567 ** If any sibling already holds an exclusive lock, go ahead and return
4568 ** SQLITE_BUSY.
4569 */
4570 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004571 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004572 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004573 break;
4574 }
4575 allShared |= pX->sharedMask;
4576 }
4577
4578 /* Get shared locks at the system level, if necessary */
4579 if( rc==SQLITE_OK ){
4580 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004581 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004582 }else{
drh73b64e42010-05-30 19:55:15 +00004583 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004584 }
drhd9e5c4f2010-05-12 18:01:39 +00004585 }
drh73b64e42010-05-30 19:55:15 +00004586
4587 /* Get the local shared locks */
4588 if( rc==SQLITE_OK ){
4589 p->sharedMask |= mask;
4590 }
4591 }else{
4592 /* Make sure no sibling connections hold locks that will block this
4593 ** lock. If any do, return SQLITE_BUSY right away.
4594 */
4595 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004596 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4597 rc = SQLITE_BUSY;
4598 break;
4599 }
4600 }
4601
4602 /* Get the exclusive locks at the system level. Then if successful
4603 ** also mark the local connection as being locked.
4604 */
4605 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004606 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004607 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004608 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004609 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004610 }
drhd9e5c4f2010-05-12 18:01:39 +00004611 }
4612 }
drhd91c68f2010-05-14 14:52:25 +00004613 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004614 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004615 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004616 return rc;
4617}
4618
drh286a2882010-05-20 23:51:06 +00004619/*
4620** Implement a memory barrier or memory fence on shared memory.
4621**
4622** All loads and stores begun before the barrier must complete before
4623** any load or store begun after the barrier.
4624*/
4625static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004626 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004627){
drhff828942010-06-26 21:34:06 +00004628 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004629 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4630 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004631 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004632}
4633
dan18801912010-06-14 14:07:50 +00004634/*
danda9fe0c2010-07-13 18:44:03 +00004635** Close a connection to shared-memory. Delete the underlying
4636** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004637**
4638** If there is no shared memory associated with the connection then this
4639** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004640*/
danda9fe0c2010-07-13 18:44:03 +00004641static int unixShmUnmap(
4642 sqlite3_file *fd, /* The underlying database file */
4643 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004644){
danda9fe0c2010-07-13 18:44:03 +00004645 unixShm *p; /* The connection to be closed */
4646 unixShmNode *pShmNode; /* The underlying shared-memory file */
4647 unixShm **pp; /* For looping over sibling connections */
4648 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004649
danda9fe0c2010-07-13 18:44:03 +00004650 pDbFd = (unixFile*)fd;
4651 p = pDbFd->pShm;
4652 if( p==0 ) return SQLITE_OK;
4653 pShmNode = p->pShmNode;
4654
4655 assert( pShmNode==pDbFd->pInode->pShmNode );
4656 assert( pShmNode->pInode==pDbFd->pInode );
4657
4658 /* Remove connection p from the set of connections associated
4659 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004660 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004661 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4662 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004663
danda9fe0c2010-07-13 18:44:03 +00004664 /* Free the connection p */
4665 sqlite3_free(p);
4666 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004667 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004668
4669 /* If pShmNode->nRef has reached 0, then close the underlying
4670 ** shared-memory file, too */
4671 unixEnterMutex();
4672 assert( pShmNode->nRef>0 );
4673 pShmNode->nRef--;
4674 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004675 if( deleteFlag && pShmNode->h>=0 ){
4676 osUnlink(pShmNode->zFilename);
4677 }
danda9fe0c2010-07-13 18:44:03 +00004678 unixShmPurge(pDbFd);
4679 }
4680 unixLeaveMutex();
4681
4682 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004683}
drh286a2882010-05-20 23:51:06 +00004684
danda9fe0c2010-07-13 18:44:03 +00004685
drhd9e5c4f2010-05-12 18:01:39 +00004686#else
drh6b017cc2010-06-14 18:01:46 +00004687# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004688# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004689# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004690# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004691#endif /* #ifndef SQLITE_OMIT_WAL */
4692
mistachkine98844f2013-08-24 00:59:24 +00004693#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004694/*
danaef49d72013-03-25 16:28:54 +00004695** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004696*/
danf23da962013-03-23 21:00:41 +00004697static void unixUnmapfile(unixFile *pFd){
4698 assert( pFd->nFetchOut==0 );
4699 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004700 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004701 pFd->pMapRegion = 0;
4702 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004703 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004704 }
4705}
dan5d8a1372013-03-19 19:28:06 +00004706
danaef49d72013-03-25 16:28:54 +00004707/*
dane6ecd662013-04-01 17:56:59 +00004708** Attempt to set the size of the memory mapping maintained by file
4709** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4710**
4711** If successful, this function sets the following variables:
4712**
4713** unixFile.pMapRegion
4714** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004715** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004716**
4717** If unsuccessful, an error message is logged via sqlite3_log() and
4718** the three variables above are zeroed. In this case SQLite should
4719** continue accessing the database using the xRead() and xWrite()
4720** methods.
4721*/
4722static void unixRemapfile(
4723 unixFile *pFd, /* File descriptor object */
4724 i64 nNew /* Required mapping size */
4725){
dan4ff7bc42013-04-02 12:04:09 +00004726 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004727 int h = pFd->h; /* File descriptor open on db file */
4728 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004729 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004730 u8 *pNew = 0; /* Location of new mapping */
4731 int flags = PROT_READ; /* Flags to pass to mmap() */
4732
4733 assert( pFd->nFetchOut==0 );
4734 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004735 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004736 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004737 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004738 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004739
danfe33e392015-11-17 20:56:06 +00004740#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004741 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004742#endif
dane6ecd662013-04-01 17:56:59 +00004743
4744 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004745#if HAVE_MREMAP
4746 i64 nReuse = pFd->mmapSize;
4747#else
danbc760632014-03-20 09:42:09 +00004748 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004749 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004750#endif
dane6ecd662013-04-01 17:56:59 +00004751 u8 *pReq = &pOrig[nReuse];
4752
4753 /* Unmap any pages of the existing mapping that cannot be reused. */
4754 if( nReuse!=nOrig ){
4755 osMunmap(pReq, nOrig-nReuse);
4756 }
4757
4758#if HAVE_MREMAP
4759 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004760 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004761#else
4762 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4763 if( pNew!=MAP_FAILED ){
4764 if( pNew!=pReq ){
4765 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004766 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004767 }else{
4768 pNew = pOrig;
4769 }
4770 }
4771#endif
4772
dan48ccef82013-04-02 20:55:01 +00004773 /* The attempt to extend the existing mapping failed. Free it. */
4774 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004775 osMunmap(pOrig, nReuse);
4776 }
4777 }
4778
4779 /* If pNew is still NULL, try to create an entirely new mapping. */
4780 if( pNew==0 ){
4781 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004782 }
4783
dan4ff7bc42013-04-02 12:04:09 +00004784 if( pNew==MAP_FAILED ){
4785 pNew = 0;
4786 nNew = 0;
4787 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4788
4789 /* If the mmap() above failed, assume that all subsequent mmap() calls
4790 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4791 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004792 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004793 }
dane6ecd662013-04-01 17:56:59 +00004794 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004795 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004796}
4797
4798/*
danaef49d72013-03-25 16:28:54 +00004799** Memory map or remap the file opened by file-descriptor pFd (if the file
4800** is already mapped, the existing mapping is replaced by the new). Or, if
4801** there already exists a mapping for this file, and there are still
4802** outstanding xFetch() references to it, this function is a no-op.
4803**
4804** If parameter nByte is non-negative, then it is the requested size of
4805** the mapping to create. Otherwise, if nByte is less than zero, then the
4806** requested size is the size of the file on disk. The actual size of the
4807** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004808** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004809**
4810** SQLITE_OK is returned if no error occurs (even if the mapping is not
4811** recreated as a result of outstanding references) or an SQLite error
4812** code otherwise.
4813*/
drhf3b1ed02015-12-02 13:11:03 +00004814static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004815 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004816 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004817 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4818
4819 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004820 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004821 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004822 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004823 }
drh3044b512014-06-16 16:41:52 +00004824 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004825 }
drh9b4c59f2013-04-15 17:03:42 +00004826 if( nMap>pFd->mmapSizeMax ){
4827 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004828 }
4829
drh333e6ca2015-12-02 15:44:39 +00004830 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004831 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004832 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004833 }
4834
danf23da962013-03-23 21:00:41 +00004835 return SQLITE_OK;
4836}
mistachkine98844f2013-08-24 00:59:24 +00004837#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004838
danaef49d72013-03-25 16:28:54 +00004839/*
4840** If possible, return a pointer to a mapping of file fd starting at offset
4841** iOff. The mapping must be valid for at least nAmt bytes.
4842**
4843** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4844** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4845** Finally, if an error does occur, return an SQLite error code. The final
4846** value of *pp is undefined in this case.
4847**
4848** If this function does return a pointer, the caller must eventually
4849** release the reference by calling unixUnfetch().
4850*/
danf23da962013-03-23 21:00:41 +00004851static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004852#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004853 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004854#endif
danf23da962013-03-23 21:00:41 +00004855 *pp = 0;
4856
drh9b4c59f2013-04-15 17:03:42 +00004857#if SQLITE_MAX_MMAP_SIZE>0
4858 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004859 if( pFd->pMapRegion==0 ){
4860 int rc = unixMapfile(pFd, -1);
4861 if( rc!=SQLITE_OK ) return rc;
4862 }
4863 if( pFd->mmapSize >= iOff+nAmt ){
4864 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4865 pFd->nFetchOut++;
4866 }
4867 }
drh6e0b6d52013-04-09 16:19:20 +00004868#endif
danf23da962013-03-23 21:00:41 +00004869 return SQLITE_OK;
4870}
4871
danaef49d72013-03-25 16:28:54 +00004872/*
dandf737fe2013-03-25 17:00:24 +00004873** If the third argument is non-NULL, then this function releases a
4874** reference obtained by an earlier call to unixFetch(). The second
4875** argument passed to this function must be the same as the corresponding
4876** argument that was passed to the unixFetch() invocation.
4877**
4878** Or, if the third argument is NULL, then this function is being called
4879** to inform the VFS layer that, according to POSIX, any existing mapping
4880** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004881*/
dandf737fe2013-03-25 17:00:24 +00004882static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004883#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004884 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004885 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004886
danaef49d72013-03-25 16:28:54 +00004887 /* If p==0 (unmap the entire file) then there must be no outstanding
4888 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4889 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004890 assert( (p==0)==(pFd->nFetchOut==0) );
4891
dandf737fe2013-03-25 17:00:24 +00004892 /* If p!=0, it must match the iOff value. */
4893 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4894
danf23da962013-03-23 21:00:41 +00004895 if( p ){
4896 pFd->nFetchOut--;
4897 }else{
4898 unixUnmapfile(pFd);
4899 }
4900
4901 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004902#else
4903 UNUSED_PARAMETER(fd);
4904 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004905 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004906#endif
danf23da962013-03-23 21:00:41 +00004907 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004908}
4909
4910/*
drh734c9862008-11-28 15:37:20 +00004911** Here ends the implementation of all sqlite3_file methods.
4912**
4913********************** End sqlite3_file Methods *******************************
4914******************************************************************************/
4915
4916/*
drh6b9d6dd2008-12-03 19:34:47 +00004917** This division contains definitions of sqlite3_io_methods objects that
4918** implement various file locking strategies. It also contains definitions
4919** of "finder" functions. A finder-function is used to locate the appropriate
4920** sqlite3_io_methods object for a particular database file. The pAppData
4921** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4922** the correct finder-function for that VFS.
4923**
4924** Most finder functions return a pointer to a fixed sqlite3_io_methods
4925** object. The only interesting finder-function is autolockIoFinder, which
4926** looks at the filesystem type and tries to guess the best locking
4927** strategy from that.
4928**
peter.d.reid60ec9142014-09-06 16:39:46 +00004929** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004930**
4931** (1) The real finder-function named "FImpt()".
4932**
dane946c392009-08-22 11:39:46 +00004933** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004934**
4935**
4936** A pointer to the F pointer is used as the pAppData value for VFS
4937** objects. We have to do this instead of letting pAppData point
4938** directly at the finder-function since C90 rules prevent a void*
4939** from be cast into a function pointer.
4940**
drh6b9d6dd2008-12-03 19:34:47 +00004941**
drh7708e972008-11-29 00:56:52 +00004942** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00004943**
drh7708e972008-11-29 00:56:52 +00004944** * A constant sqlite3_io_methods object call METHOD that has locking
4945** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
4946**
4947** * An I/O method finder function called FINDER that returns a pointer
4948** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00004949*/
drhe6d41732015-02-21 00:49:00 +00004950#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00004951static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00004952 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00004953 CLOSE, /* xClose */ \
4954 unixRead, /* xRead */ \
4955 unixWrite, /* xWrite */ \
4956 unixTruncate, /* xTruncate */ \
4957 unixSync, /* xSync */ \
4958 unixFileSize, /* xFileSize */ \
4959 LOCK, /* xLock */ \
4960 UNLOCK, /* xUnlock */ \
4961 CKLOCK, /* xCheckReservedLock */ \
4962 unixFileControl, /* xFileControl */ \
4963 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00004964 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00004965 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00004966 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00004967 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00004968 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00004969 unixFetch, /* xFetch */ \
4970 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00004971}; \
drh0c2694b2009-09-03 16:23:44 +00004972static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
4973 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00004974 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00004975} \
drh0c2694b2009-09-03 16:23:44 +00004976static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00004977 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00004978
4979/*
4980** Here are all of the sqlite3_io_methods objects for each of the
4981** locking strategies. Functions that return pointers to these methods
4982** are also created.
4983*/
4984IOMETHODS(
4985 posixIoFinder, /* Finder function name */
4986 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00004987 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00004988 unixClose, /* xClose method */
4989 unixLock, /* xLock method */
4990 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00004991 unixCheckReservedLock, /* xCheckReservedLock method */
4992 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00004993)
drh7708e972008-11-29 00:56:52 +00004994IOMETHODS(
4995 nolockIoFinder, /* Finder function name */
4996 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00004997 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00004998 nolockClose, /* xClose method */
4999 nolockLock, /* xLock method */
5000 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005001 nolockCheckReservedLock, /* xCheckReservedLock method */
5002 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005003)
drh7708e972008-11-29 00:56:52 +00005004IOMETHODS(
5005 dotlockIoFinder, /* Finder function name */
5006 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005007 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005008 dotlockClose, /* xClose method */
5009 dotlockLock, /* xLock method */
5010 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005011 dotlockCheckReservedLock, /* xCheckReservedLock method */
5012 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005013)
drh7708e972008-11-29 00:56:52 +00005014
drhe89b2912015-03-03 20:42:01 +00005015#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005016IOMETHODS(
5017 flockIoFinder, /* Finder function name */
5018 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005019 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005020 flockClose, /* xClose method */
5021 flockLock, /* xLock method */
5022 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005023 flockCheckReservedLock, /* xCheckReservedLock method */
5024 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005025)
drh7708e972008-11-29 00:56:52 +00005026#endif
5027
drh6c7d5c52008-11-21 20:32:33 +00005028#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005029IOMETHODS(
5030 semIoFinder, /* Finder function name */
5031 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005032 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005033 semXClose, /* xClose method */
5034 semXLock, /* xLock method */
5035 semXUnlock, /* xUnlock method */
5036 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005037 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005038)
aswiftaebf4132008-11-21 00:10:35 +00005039#endif
drh7708e972008-11-29 00:56:52 +00005040
drhd2cb50b2009-01-09 21:41:17 +00005041#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005042IOMETHODS(
5043 afpIoFinder, /* Finder function name */
5044 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005045 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005046 afpClose, /* xClose method */
5047 afpLock, /* xLock method */
5048 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005049 afpCheckReservedLock, /* xCheckReservedLock method */
5050 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005051)
drh715ff302008-12-03 22:32:44 +00005052#endif
5053
5054/*
5055** The proxy locking method is a "super-method" in the sense that it
5056** opens secondary file descriptors for the conch and lock files and
5057** it uses proxy, dot-file, AFP, and flock() locking methods on those
5058** secondary files. For this reason, the division that implements
5059** proxy locking is located much further down in the file. But we need
5060** to go ahead and define the sqlite3_io_methods and finder function
5061** for proxy locking here. So we forward declare the I/O methods.
5062*/
drhd2cb50b2009-01-09 21:41:17 +00005063#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005064static int proxyClose(sqlite3_file*);
5065static int proxyLock(sqlite3_file*, int);
5066static int proxyUnlock(sqlite3_file*, int);
5067static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005068IOMETHODS(
5069 proxyIoFinder, /* Finder function name */
5070 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005071 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005072 proxyClose, /* xClose method */
5073 proxyLock, /* xLock method */
5074 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005075 proxyCheckReservedLock, /* xCheckReservedLock method */
5076 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005077)
aswiftaebf4132008-11-21 00:10:35 +00005078#endif
drh7708e972008-11-29 00:56:52 +00005079
drh7ed97b92010-01-20 13:07:21 +00005080/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5081#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5082IOMETHODS(
5083 nfsIoFinder, /* Finder function name */
5084 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005085 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005086 unixClose, /* xClose method */
5087 unixLock, /* xLock method */
5088 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005089 unixCheckReservedLock, /* xCheckReservedLock method */
5090 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005091)
5092#endif
drh7708e972008-11-29 00:56:52 +00005093
drhd2cb50b2009-01-09 21:41:17 +00005094#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005095/*
drh6b9d6dd2008-12-03 19:34:47 +00005096** This "finder" function attempts to determine the best locking strategy
5097** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005098** object that implements that strategy.
5099**
5100** This is for MacOSX only.
5101*/
drh1875f7a2008-12-08 18:19:17 +00005102static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005103 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005104 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005105){
5106 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005107 const char *zFilesystem; /* Filesystem type name */
5108 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005109 } aMap[] = {
5110 { "hfs", &posixIoMethods },
5111 { "ufs", &posixIoMethods },
5112 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005113 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005114 { "webdav", &nolockIoMethods },
5115 { 0, 0 }
5116 };
5117 int i;
5118 struct statfs fsInfo;
5119 struct flock lockInfo;
5120
5121 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005122 /* If filePath==NULL that means we are dealing with a transient file
5123 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005124 return &nolockIoMethods;
5125 }
5126 if( statfs(filePath, &fsInfo) != -1 ){
5127 if( fsInfo.f_flags & MNT_RDONLY ){
5128 return &nolockIoMethods;
5129 }
5130 for(i=0; aMap[i].zFilesystem; i++){
5131 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5132 return aMap[i].pMethods;
5133 }
5134 }
5135 }
5136
5137 /* Default case. Handles, amongst others, "nfs".
5138 ** Test byte-range lock using fcntl(). If the call succeeds,
5139 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005140 */
drh7708e972008-11-29 00:56:52 +00005141 lockInfo.l_len = 1;
5142 lockInfo.l_start = 0;
5143 lockInfo.l_whence = SEEK_SET;
5144 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005145 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005146 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5147 return &nfsIoMethods;
5148 } else {
5149 return &posixIoMethods;
5150 }
drh7708e972008-11-29 00:56:52 +00005151 }else{
5152 return &dotlockIoMethods;
5153 }
5154}
drh0c2694b2009-09-03 16:23:44 +00005155static const sqlite3_io_methods
5156 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005157
drhd2cb50b2009-01-09 21:41:17 +00005158#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005159
drhe89b2912015-03-03 20:42:01 +00005160#if OS_VXWORKS
5161/*
5162** This "finder" function for VxWorks checks to see if posix advisory
5163** locking works. If it does, then that is what is used. If it does not
5164** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005165*/
drhe89b2912015-03-03 20:42:01 +00005166static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005167 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005168 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005169){
5170 struct flock lockInfo;
5171
5172 if( !filePath ){
5173 /* If filePath==NULL that means we are dealing with a transient file
5174 ** that does not need to be locked. */
5175 return &nolockIoMethods;
5176 }
5177
5178 /* Test if fcntl() is supported and use POSIX style locks.
5179 ** Otherwise fall back to the named semaphore method.
5180 */
5181 lockInfo.l_len = 1;
5182 lockInfo.l_start = 0;
5183 lockInfo.l_whence = SEEK_SET;
5184 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005185 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005186 return &posixIoMethods;
5187 }else{
5188 return &semIoMethods;
5189 }
5190}
drh0c2694b2009-09-03 16:23:44 +00005191static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005192 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005193
drhe89b2912015-03-03 20:42:01 +00005194#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005195
drh7708e972008-11-29 00:56:52 +00005196/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005197** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005198*/
drh0c2694b2009-09-03 16:23:44 +00005199typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005200
aswiftaebf4132008-11-21 00:10:35 +00005201
drh734c9862008-11-28 15:37:20 +00005202/****************************************************************************
5203**************************** sqlite3_vfs methods ****************************
5204**
5205** This division contains the implementation of methods on the
5206** sqlite3_vfs object.
5207*/
5208
danielk1977a3d4c882007-03-23 10:08:38 +00005209/*
danielk1977e339d652008-06-28 11:23:00 +00005210** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005211*/
5212static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005213 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005214 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005215 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005216 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005217 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005218){
drh7708e972008-11-29 00:56:52 +00005219 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005220 unixFile *pNew = (unixFile *)pId;
5221 int rc = SQLITE_OK;
5222
drh8af6c222010-05-14 12:43:01 +00005223 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005224
dan00157392010-10-05 11:33:15 +00005225 /* Usually the path zFilename should not be a relative pathname. The
5226 ** exception is when opening the proxy "conch" file in builds that
5227 ** include the special Apple locking styles.
5228 */
dan00157392010-10-05 11:33:15 +00005229#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005230 assert( zFilename==0 || zFilename[0]=='/'
5231 || pVfs->pAppData==(void*)&autolockIoFinder );
5232#else
5233 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005234#endif
dan00157392010-10-05 11:33:15 +00005235
drhb07028f2011-10-14 21:49:18 +00005236 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005237 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005238
drh308c2a52010-05-14 11:30:18 +00005239 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005240 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005241 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005242 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005243 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005244#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005245 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005246#endif
drhc02a43a2012-01-10 23:18:38 +00005247 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5248 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005249 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005250 }
drh503a6862013-03-01 01:07:17 +00005251 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005252 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005253 }
drh339eb0b2008-03-07 15:34:11 +00005254
drh6c7d5c52008-11-21 20:32:33 +00005255#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005256 pNew->pId = vxworksFindFileId(zFilename);
5257 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005258 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005259 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005260 }
5261#endif
5262
drhc02a43a2012-01-10 23:18:38 +00005263 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005264 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005265 }else{
drh0c2694b2009-09-03 16:23:44 +00005266 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005267#if SQLITE_ENABLE_LOCKING_STYLE
5268 /* Cache zFilename in the locking context (AFP and dotlock override) for
5269 ** proxyLock activation is possible (remote proxy is based on db name)
5270 ** zFilename remains valid until file is closed, to support */
5271 pNew->lockingContext = (void*)zFilename;
5272#endif
drhda0e7682008-07-30 15:27:54 +00005273 }
danielk1977e339d652008-06-28 11:23:00 +00005274
drh7ed97b92010-01-20 13:07:21 +00005275 if( pLockingStyle == &posixIoMethods
5276#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5277 || pLockingStyle == &nfsIoMethods
5278#endif
5279 ){
drh7708e972008-11-29 00:56:52 +00005280 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005281 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005282 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005283 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005284 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005285 ** in two scenarios:
5286 **
5287 ** (a) A call to fstat() failed.
5288 ** (b) A malloc failed.
5289 **
5290 ** Scenario (b) may only occur if the process is holding no other
5291 ** file descriptors open on the same file. If there were other file
5292 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005293 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005294 ** handle h - as it is guaranteed that no posix locks will be released
5295 ** by doing so.
5296 **
5297 ** If scenario (a) caused the error then things are not so safe. The
5298 ** implicit assumption here is that if fstat() fails, things are in
5299 ** such bad shape that dropping a lock or two doesn't matter much.
5300 */
drh0e9365c2011-03-02 02:08:13 +00005301 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005302 h = -1;
5303 }
drh7708e972008-11-29 00:56:52 +00005304 unixLeaveMutex();
5305 }
danielk1977e339d652008-06-28 11:23:00 +00005306
drhd2cb50b2009-01-09 21:41:17 +00005307#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005308 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005309 /* AFP locking uses the file path so it needs to be included in
5310 ** the afpLockingContext.
5311 */
5312 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005313 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005314 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005315 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005316 }else{
5317 /* NB: zFilename exists and remains valid until the file is closed
5318 ** according to requirement F11141. So we do not need to make a
5319 ** copy of the filename. */
5320 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005321 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005322 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005323 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005324 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005325 if( rc!=SQLITE_OK ){
5326 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005327 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005328 h = -1;
5329 }
drh7708e972008-11-29 00:56:52 +00005330 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005331 }
drh7708e972008-11-29 00:56:52 +00005332 }
5333#endif
danielk1977e339d652008-06-28 11:23:00 +00005334
drh7708e972008-11-29 00:56:52 +00005335 else if( pLockingStyle == &dotlockIoMethods ){
5336 /* Dotfile locking uses the file path so it needs to be included in
5337 ** the dotlockLockingContext
5338 */
5339 char *zLockFile;
5340 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005341 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005342 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005343 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005344 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005345 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005346 }else{
5347 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005348 }
drh7708e972008-11-29 00:56:52 +00005349 pNew->lockingContext = zLockFile;
5350 }
danielk1977e339d652008-06-28 11:23:00 +00005351
drh6c7d5c52008-11-21 20:32:33 +00005352#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005353 else if( pLockingStyle == &semIoMethods ){
5354 /* Named semaphore locking uses the file path so it needs to be
5355 ** included in the semLockingContext
5356 */
5357 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005358 rc = findInodeInfo(pNew, &pNew->pInode);
5359 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5360 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005361 int n;
drh2238dcc2009-08-27 17:56:20 +00005362 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005363 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005364 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005365 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005366 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5367 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005368 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005369 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005370 }
chw97185482008-11-17 08:05:31 +00005371 }
drh7708e972008-11-29 00:56:52 +00005372 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005373 }
drh7708e972008-11-29 00:56:52 +00005374#endif
aswift5b1a2562008-08-22 00:22:35 +00005375
drh4bf66fd2015-02-19 02:43:02 +00005376 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005377#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005378 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005379 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005380 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005381 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005382 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005383 }
chw97185482008-11-17 08:05:31 +00005384#endif
danielk1977e339d652008-06-28 11:23:00 +00005385 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005386 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005387 }else{
drh7708e972008-11-29 00:56:52 +00005388 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005389 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005390 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005391 }
danielk1977e339d652008-06-28 11:23:00 +00005392 return rc;
drh054889e2005-11-30 03:20:31 +00005393}
drh9c06c952005-11-26 00:25:00 +00005394
danielk1977ad94b582007-08-20 06:44:22 +00005395/*
drh8b3cf822010-06-01 21:02:51 +00005396** Return the name of a directory in which to put temporary files.
5397** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005398*/
drh7234c6d2010-06-19 15:10:09 +00005399static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005400 static const char *azDirs[] = {
5401 0,
aswiftaebf4132008-11-21 00:10:35 +00005402 0,
danielk197717b90b52008-06-06 11:11:25 +00005403 "/var/tmp",
5404 "/usr/tmp",
5405 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005406 "."
danielk197717b90b52008-06-06 11:11:25 +00005407 };
drh8b3cf822010-06-01 21:02:51 +00005408 unsigned int i;
5409 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005410 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005411
drhb7e50ad2015-11-28 21:49:53 +00005412 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5413 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh19515c82010-06-19 23:53:11 +00005414 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
drh8b3cf822010-06-01 21:02:51 +00005415 if( zDir==0 ) continue;
drh99ab3b12011-03-02 15:09:07 +00005416 if( osStat(zDir, &buf) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005417 if( !S_ISDIR(buf.st_mode) ) continue;
drh99ab3b12011-03-02 15:09:07 +00005418 if( osAccess(zDir, 07) ) continue;
drh8b3cf822010-06-01 21:02:51 +00005419 break;
5420 }
5421 return zDir;
5422}
5423
5424/*
5425** Create a temporary file name in zBuf. zBuf must be allocated
5426** by the calling process and must be big enough to hold at least
5427** pVfs->mxPathname bytes.
5428*/
5429static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005430 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005431 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005432
5433 /* It's odd to simulate an io-error here, but really this is just
5434 ** using the io-error infrastructure to test that SQLite handles this
5435 ** function failing.
5436 */
5437 SimulateIOError( return SQLITE_IOERR );
5438
drh7234c6d2010-06-19 15:10:09 +00005439 zDir = unixTempFileDir();
danielk197717b90b52008-06-06 11:11:25 +00005440 do{
drh970942e2015-11-25 23:13:14 +00005441 u64 r;
5442 sqlite3_randomness(sizeof(r), &r);
5443 assert( nBuf>2 );
5444 zBuf[nBuf-2] = 0;
5445 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5446 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005447 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005448 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005449 return SQLITE_OK;
5450}
5451
drhd2cb50b2009-01-09 21:41:17 +00005452#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005453/*
5454** Routine to transform a unixFile into a proxy-locking unixFile.
5455** Implementation in the proxy-lock division, but used by unixOpen()
5456** if SQLITE_PREFER_PROXY_LOCKING is defined.
5457*/
5458static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005459#endif
drhc66d5b62008-12-03 22:48:32 +00005460
dan08da86a2009-08-21 17:18:03 +00005461/*
5462** Search for an unused file descriptor that was opened on the database
5463** file (not a journal or master-journal file) identified by pathname
5464** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5465** argument to this function.
5466**
5467** Such a file descriptor may exist if a database connection was closed
5468** but the associated file descriptor could not be closed because some
5469** other file descriptor open on the same file is holding a file-lock.
5470** Refer to comments in the unixClose() function and the lengthy comment
5471** describing "Posix Advisory Locking" at the start of this file for
5472** further details. Also, ticket #4018.
5473**
5474** If a suitable file descriptor is found, then it is returned. If no
5475** such file descriptor is located, -1 is returned.
5476*/
dane946c392009-08-22 11:39:46 +00005477static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5478 UnixUnusedFd *pUnused = 0;
5479
5480 /* Do not search for an unused file descriptor on vxworks. Not because
5481 ** vxworks would not benefit from the change (it might, we're not sure),
5482 ** but because no way to test it is currently available. It is better
5483 ** not to risk breaking vxworks support for the sake of such an obscure
5484 ** feature. */
5485#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005486 struct stat sStat; /* Results of stat() call */
5487
5488 /* A stat() call may fail for various reasons. If this happens, it is
5489 ** almost certain that an open() call on the same path will also fail.
5490 ** For this reason, if an error occurs in the stat() call here, it is
5491 ** ignored and -1 is returned. The caller will try to open a new file
5492 ** descriptor on the same path, fail, and return an error to SQLite.
5493 **
5494 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005495 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005496 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005497 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005498
5499 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005500 pInode = inodeList;
5501 while( pInode && (pInode->fileId.dev!=sStat.st_dev
5502 || pInode->fileId.ino!=sStat.st_ino) ){
5503 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005504 }
drh8af6c222010-05-14 12:43:01 +00005505 if( pInode ){
dane946c392009-08-22 11:39:46 +00005506 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005507 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005508 pUnused = *pp;
5509 if( pUnused ){
5510 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005511 }
5512 }
5513 unixLeaveMutex();
5514 }
dane946c392009-08-22 11:39:46 +00005515#endif /* if !OS_VXWORKS */
5516 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005517}
danielk197717b90b52008-06-06 11:11:25 +00005518
5519/*
danddb0ac42010-07-14 14:48:58 +00005520** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005521** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005522** and a value suitable for passing as the third argument to open(2) is
5523** written to *pMode. If an IO error occurs, an SQLite error code is
5524** returned and the value of *pMode is not modified.
5525**
peter.d.reid60ec9142014-09-06 16:39:46 +00005526** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005527** an indication to robust_open() to create the file using
5528** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5529** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005530** this function queries the file-system for the permissions on the
5531** corresponding database file and sets *pMode to this value. Whenever
5532** possible, WAL and journal files are created using the same permissions
5533** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005534**
5535** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5536** original filename is unavailable. But 8_3_NAMES is only used for
5537** FAT filesystems and permissions do not matter there, so just use
5538** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005539*/
5540static int findCreateFileMode(
5541 const char *zPath, /* Path of file (possibly) being created */
5542 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005543 mode_t *pMode, /* OUT: Permissions to open file with */
5544 uid_t *pUid, /* OUT: uid to set on the file */
5545 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005546){
5547 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005548 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005549 *pUid = 0;
5550 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005551 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005552 char zDb[MAX_PATHNAME+1]; /* Database file path */
5553 int nDb; /* Number of valid bytes in zDb */
5554 struct stat sStat; /* Output of stat() on database file */
5555
dana0c989d2010-11-05 18:07:37 +00005556 /* zPath is a path to a WAL or journal file. The following block derives
5557 ** the path to the associated database file from zPath. This block handles
5558 ** the following naming conventions:
5559 **
5560 ** "<path to db>-journal"
5561 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005562 ** "<path to db>-journalNN"
5563 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005564 **
drhd337c5b2011-10-20 18:23:35 +00005565 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005566 ** used by the test_multiplex.c module.
5567 */
5568 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005569 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005570#ifndef SQLITE_ENABLE_8_3_NAMES
5571 /* In the normal case (8+3 filenames disabled) the journal filename
5572 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005573 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005574 assert( sqlite3Isalnum(zPath[nDb]) );
5575#else
5576 /* If 8+3 names are possible, then the journal file might not contain
5577 ** a '-' character. So check for that case and return early. */
5578 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5579#endif
drhc47167a2011-10-05 15:26:13 +00005580 nDb--;
5581 }
danddb0ac42010-07-14 14:48:58 +00005582 memcpy(zDb, zPath, nDb);
5583 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005584
drh58384f12011-07-28 00:14:45 +00005585 if( 0==osStat(zDb, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00005586 *pMode = sStat.st_mode & 0777;
drhac7c3ac2012-02-11 19:23:48 +00005587 *pUid = sStat.st_uid;
5588 *pGid = sStat.st_gid;
danddb0ac42010-07-14 14:48:58 +00005589 }else{
5590 rc = SQLITE_IOERR_FSTAT;
5591 }
5592 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5593 *pMode = 0600;
danddb0ac42010-07-14 14:48:58 +00005594 }
5595 return rc;
5596}
5597
5598/*
danielk1977ad94b582007-08-20 06:44:22 +00005599** Open the file zPath.
5600**
danielk1977b4b47412007-08-17 15:53:36 +00005601** Previously, the SQLite OS layer used three functions in place of this
5602** one:
5603**
5604** sqlite3OsOpenReadWrite();
5605** sqlite3OsOpenReadOnly();
5606** sqlite3OsOpenExclusive();
5607**
5608** These calls correspond to the following combinations of flags:
5609**
5610** ReadWrite() -> (READWRITE | CREATE)
5611** ReadOnly() -> (READONLY)
5612** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5613**
5614** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5615** true, the file was configured to be automatically deleted when the
5616** file handle closed. To achieve the same effect using this new
5617** interface, add the DELETEONCLOSE flag to those specified above for
5618** OpenExclusive().
5619*/
5620static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005621 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5622 const char *zPath, /* Pathname of file to be opened */
5623 sqlite3_file *pFile, /* The file descriptor to be filled in */
5624 int flags, /* Input flags to control the opening */
5625 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005626){
dan08da86a2009-08-21 17:18:03 +00005627 unixFile *p = (unixFile *)pFile;
5628 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005629 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005630 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005631 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005632 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005633 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005634
5635 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5636 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5637 int isCreate = (flags & SQLITE_OPEN_CREATE);
5638 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5639 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005640#if SQLITE_ENABLE_LOCKING_STYLE
5641 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5642#endif
drh3d4435b2011-08-26 20:55:50 +00005643#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5644 struct statfs fsInfo;
5645#endif
danielk1977b4b47412007-08-17 15:53:36 +00005646
danielk1977fee2d252007-08-18 10:59:19 +00005647 /* If creating a master or main-file journal, this function will open
5648 ** a file-descriptor on the directory too. The first time unixSync()
5649 ** is called the directory file descriptor will be fsync()ed and close()d.
5650 */
drh0059eae2011-08-08 23:48:40 +00005651 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005652 eType==SQLITE_OPEN_MASTER_JOURNAL
5653 || eType==SQLITE_OPEN_MAIN_JOURNAL
5654 || eType==SQLITE_OPEN_WAL
5655 ));
danielk1977fee2d252007-08-18 10:59:19 +00005656
danielk197717b90b52008-06-06 11:11:25 +00005657 /* If argument zPath is a NULL pointer, this function is required to open
5658 ** a temporary file. Use this buffer to store the file name in.
5659 */
drhc02a43a2012-01-10 23:18:38 +00005660 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005661 const char *zName = zPath;
5662
danielk1977fee2d252007-08-18 10:59:19 +00005663 /* Check the following statements are true:
5664 **
5665 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5666 ** (b) if CREATE is set, then READWRITE must also be set, and
5667 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005668 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005669 */
danielk1977b4b47412007-08-17 15:53:36 +00005670 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005671 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005672 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005673 assert(isDelete==0 || isCreate);
5674
danddb0ac42010-07-14 14:48:58 +00005675 /* The main DB, main journal, WAL file and master journal are never
5676 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005677 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5678 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5679 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005680 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005681
danielk1977fee2d252007-08-18 10:59:19 +00005682 /* Assert that the upper layer has set one of the "file-type" flags. */
5683 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5684 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5685 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005686 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005687 );
5688
drhb00d8622014-01-01 15:18:36 +00005689 /* Detect a pid change and reset the PRNG. There is a race condition
5690 ** here such that two or more threads all trying to open databases at
5691 ** the same instant might all reset the PRNG. But multiple resets
5692 ** are harmless.
5693 */
drh5ac93652015-03-21 20:59:43 +00005694 if( randomnessPid!=osGetpid(0) ){
5695 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005696 sqlite3_randomness(0,0);
5697 }
5698
dan08da86a2009-08-21 17:18:03 +00005699 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005700
dan08da86a2009-08-21 17:18:03 +00005701 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005702 UnixUnusedFd *pUnused;
5703 pUnused = findReusableFd(zName, flags);
5704 if( pUnused ){
5705 fd = pUnused->fd;
5706 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005707 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005708 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005709 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005710 }
5711 }
5712 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005713
5714 /* Database filenames are double-zero terminated if they are not
5715 ** URIs with parameters. Hence, they can always be passed into
5716 ** sqlite3_uri_parameter(). */
5717 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5718
dan08da86a2009-08-21 17:18:03 +00005719 }else if( !zName ){
5720 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005721 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005722 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005723 if( rc!=SQLITE_OK ){
5724 return rc;
5725 }
5726 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005727
5728 /* Generated temporary filenames are always double-zero terminated
5729 ** for use by sqlite3_uri_parameter(). */
5730 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005731 }
5732
dan08da86a2009-08-21 17:18:03 +00005733 /* Determine the value of the flags parameter passed to POSIX function
5734 ** open(). These must be calculated even if open() is not called, as
5735 ** they may be stored as part of the file handle and used by the
5736 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005737 if( isReadonly ) openFlags |= O_RDONLY;
5738 if( isReadWrite ) openFlags |= O_RDWR;
5739 if( isCreate ) openFlags |= O_CREAT;
5740 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5741 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005742
danielk1977b4b47412007-08-17 15:53:36 +00005743 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005744 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005745 uid_t uid; /* Userid for the file */
5746 gid_t gid; /* Groupid for the file */
5747 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005748 if( rc!=SQLITE_OK ){
5749 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005750 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005751 return rc;
5752 }
drhad4f1e52011-03-04 15:43:57 +00005753 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005754 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005755 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5756 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005757 /* Failed to open the file for read/write access. Try read-only. */
5758 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005759 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005760 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005761 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005762 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005763 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005764 }
5765 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005766 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005767 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005768 }
drhac7c3ac2012-02-11 19:23:48 +00005769
5770 /* If this process is running as root and if creating a new rollback
5771 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005772 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005773 */
5774 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005775 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005776 }
danielk1977b4b47412007-08-17 15:53:36 +00005777 }
dan08da86a2009-08-21 17:18:03 +00005778 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005779 if( pOutFlags ){
5780 *pOutFlags = flags;
5781 }
5782
dane946c392009-08-22 11:39:46 +00005783 if( p->pUnused ){
5784 p->pUnused->fd = fd;
5785 p->pUnused->flags = flags;
5786 }
5787
danielk1977b4b47412007-08-17 15:53:36 +00005788 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005789#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005790 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005791#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5792 zPath = sqlite3_mprintf("%s", zName);
5793 if( zPath==0 ){
5794 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005795 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005796 }
chw97185482008-11-17 08:05:31 +00005797#else
drh036ac7f2011-08-08 23:18:05 +00005798 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005799#endif
danielk1977b4b47412007-08-17 15:53:36 +00005800 }
drh41022642008-11-21 00:24:42 +00005801#if SQLITE_ENABLE_LOCKING_STYLE
5802 else{
dan08da86a2009-08-21 17:18:03 +00005803 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005804 }
5805#endif
5806
drhda0e7682008-07-30 15:27:54 +00005807 noLock = eType!=SQLITE_OPEN_MAIN_DB;
aswiftaebf4132008-11-21 00:10:35 +00005808
drh7ed97b92010-01-20 13:07:21 +00005809
5810#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005811 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005812 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005813 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005814 return SQLITE_IOERR_ACCESS;
5815 }
5816 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5817 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5818 }
drh4bf66fd2015-02-19 02:43:02 +00005819 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5820 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5821 }
drh7ed97b92010-01-20 13:07:21 +00005822#endif
drhc02a43a2012-01-10 23:18:38 +00005823
5824 /* Set up appropriate ctrlFlags */
5825 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5826 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
5827 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5828 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5829 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5830
drh7ed97b92010-01-20 13:07:21 +00005831#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005832#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005833 isAutoProxy = 1;
5834#endif
5835 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005836 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5837 int useProxy = 0;
5838
dan08da86a2009-08-21 17:18:03 +00005839 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5840 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005841 if( envforce!=NULL ){
5842 useProxy = atoi(envforce)>0;
5843 }else{
aswiftaebf4132008-11-21 00:10:35 +00005844 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5845 }
5846 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005847 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005848 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005849 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005850 if( rc!=SQLITE_OK ){
5851 /* Use unixClose to clean up the resources added in fillInUnixFile
5852 ** and clear all the structure's references. Specifically,
5853 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5854 */
5855 unixClose(pFile);
5856 return rc;
5857 }
aswiftaebf4132008-11-21 00:10:35 +00005858 }
dane946c392009-08-22 11:39:46 +00005859 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005860 }
5861 }
5862#endif
5863
drhc02a43a2012-01-10 23:18:38 +00005864 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5865
dane946c392009-08-22 11:39:46 +00005866open_finished:
5867 if( rc!=SQLITE_OK ){
5868 sqlite3_free(p->pUnused);
5869 }
5870 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005871}
5872
dane946c392009-08-22 11:39:46 +00005873
danielk1977b4b47412007-08-17 15:53:36 +00005874/*
danielk1977fee2d252007-08-18 10:59:19 +00005875** Delete the file at zPath. If the dirSync argument is true, fsync()
5876** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005877*/
drh6b9d6dd2008-12-03 19:34:47 +00005878static int unixDelete(
5879 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5880 const char *zPath, /* Name of file to be deleted */
5881 int dirSync /* If true, fsync() directory after deleting file */
5882){
danielk1977fee2d252007-08-18 10:59:19 +00005883 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005884 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005885 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005886 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005887 if( errno==ENOENT
5888#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005889 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005890#endif
5891 ){
dan9fc5b4a2012-11-09 20:17:26 +00005892 rc = SQLITE_IOERR_DELETE_NOENT;
5893 }else{
drhb4308162012-11-09 21:40:02 +00005894 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005895 }
drhb4308162012-11-09 21:40:02 +00005896 return rc;
drh5d4feff2010-07-14 01:45:22 +00005897 }
danielk1977d39fa702008-10-16 13:27:40 +00005898#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005899 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005900 int fd;
drh90315a22011-08-10 01:52:12 +00005901 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005902 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00005903 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00005904 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005905 }
drh0e9365c2011-03-02 02:08:13 +00005906 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005907 }else{
5908 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005909 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005910 }
5911 }
danielk1977d138dd82008-10-15 16:02:48 +00005912#endif
danielk1977fee2d252007-08-18 10:59:19 +00005913 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005914}
5915
danielk197790949c22007-08-17 16:50:38 +00005916/*
mistachkin48864df2013-03-21 21:20:32 +00005917** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00005918** test performed depends on the value of flags:
5919**
5920** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
5921** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
5922** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
5923**
5924** Otherwise return 0.
5925*/
danielk1977861f7452008-06-05 11:39:11 +00005926static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00005927 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
5928 const char *zPath, /* Path of the file to examine */
5929 int flags, /* What do we want to learn about the zPath file? */
5930 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00005931){
danielk1977397d65f2008-11-19 11:35:39 +00005932 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00005933 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00005934 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00005935
drhd260b5b2015-11-25 18:03:33 +00005936 /* The spec says there are three possible values for flags. But only
5937 ** two of them are actually used */
5938 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
5939
5940 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00005941 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00005942 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
5943 }else{
5944 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00005945 }
danielk1977861f7452008-06-05 11:39:11 +00005946 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005947}
5948
danielk1977b4b47412007-08-17 15:53:36 +00005949/*
danielk1977b4b47412007-08-17 15:53:36 +00005950**
danielk1977b4b47412007-08-17 15:53:36 +00005951*/
dane88ec182016-01-25 17:04:48 +00005952static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00005953 const char *zPath, /* Input path */
5954 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00005955 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00005956){
dancaf6b152016-01-25 18:05:49 +00005957 int nPath = sqlite3Strlen30(zPath);
5958 int iOff = 0;
5959 if( zPath[0]!='/' ){
5960 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00005961 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005962 }
dancaf6b152016-01-25 18:05:49 +00005963 iOff = sqlite3Strlen30(zOut);
5964 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00005965 }
dan23496702016-01-26 13:56:42 +00005966 if( (iOff+nPath+1)>nOut ){
5967 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
5968 ** even if it returns an error. */
5969 zOut[iOff] = '\0';
5970 return SQLITE_CANTOPEN_BKPT;
5971 }
dancaf6b152016-01-25 18:05:49 +00005972 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00005973 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00005974}
5975
dane88ec182016-01-25 17:04:48 +00005976/*
5977** Turn a relative pathname into a full pathname. The relative path
5978** is stored as a nul-terminated string in the buffer pointed to by
5979** zPath.
5980**
5981** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
5982** (in this case, MAX_PATHNAME bytes). The full-path is written to
5983** this buffer before returning.
5984*/
5985static int unixFullPathname(
5986 sqlite3_vfs *pVfs, /* Pointer to vfs object */
5987 const char *zPath, /* Possibly relative input path */
5988 int nOut, /* Size of output buffer in bytes */
5989 char *zOut /* Output buffer */
5990){
danaf1b36b2016-01-25 18:43:05 +00005991#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00005992 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00005993#else
5994 int rc = SQLITE_OK;
5995 int nByte;
dancaf6b152016-01-25 18:05:49 +00005996 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00005997 const char *zIn = zPath; /* Input path for each iteration of loop */
5998 char *zDel = 0;
5999
6000 assert( pVfs->mxPathname==MAX_PATHNAME );
6001 UNUSED_PARAMETER(pVfs);
6002
6003 /* It's odd to simulate an io-error here, but really this is just
6004 ** using the io-error infrastructure to test that SQLite handles this
6005 ** function failing. This function could fail if, for example, the
6006 ** current working directory has been unlinked.
6007 */
6008 SimulateIOError( return SQLITE_ERROR );
6009
6010 do {
6011
dancaf6b152016-01-25 18:05:49 +00006012 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6013 ** link, or false otherwise. */
6014 int bLink = 0;
6015 struct stat buf;
6016 if( osLstat(zIn, &buf)!=0 ){
6017 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006018 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006019 }
dane88ec182016-01-25 17:04:48 +00006020 }else{
dancaf6b152016-01-25 18:05:49 +00006021 bLink = S_ISLNK(buf.st_mode);
6022 }
6023
6024 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006025 if( zDel==0 ){
6026 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006027 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006028 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6029 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006030 }
dancaf6b152016-01-25 18:05:49 +00006031
6032 if( rc==SQLITE_OK ){
6033 nByte = osReadlink(zIn, zDel, nOut-1);
6034 if( nByte<0 ){
6035 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006036 }else{
6037 if( zDel[0]!='/' ){
6038 int n;
6039 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6040 if( nByte+n+1>nOut ){
6041 rc = SQLITE_CANTOPEN_BKPT;
6042 }else{
6043 memmove(&zDel[n], zDel, nByte+1);
6044 memcpy(zDel, zIn, n);
6045 nByte += n;
6046 }
dancaf6b152016-01-25 18:05:49 +00006047 }
6048 zDel[nByte] = '\0';
6049 }
6050 }
6051
6052 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006053 }
6054
dan23496702016-01-26 13:56:42 +00006055 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6056 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006057 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006058 }
dancaf6b152016-01-25 18:05:49 +00006059 if( bLink==0 ) break;
6060 zIn = zOut;
6061 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006062
6063 sqlite3_free(zDel);
6064 return rc;
danaf1b36b2016-01-25 18:43:05 +00006065#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006066}
6067
drh0ccebe72005-06-07 22:22:50 +00006068
drh761df872006-12-21 01:29:22 +00006069#ifndef SQLITE_OMIT_LOAD_EXTENSION
6070/*
6071** Interfaces for opening a shared library, finding entry points
6072** within the shared library, and closing the shared library.
6073*/
6074#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006075static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6076 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006077 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6078}
danielk197795c8a542007-09-01 06:51:27 +00006079
6080/*
6081** SQLite calls this function immediately after a call to unixDlSym() or
6082** unixDlOpen() fails (returns a null pointer). If a more detailed error
6083** message is available, it is written to zBufOut. If no error message
6084** is available, zBufOut is left unmodified and SQLite uses a default
6085** error message.
6086*/
danielk1977397d65f2008-11-19 11:35:39 +00006087static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006088 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006089 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006090 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006091 zErr = dlerror();
6092 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006093 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006094 }
drh6c7d5c52008-11-21 20:32:33 +00006095 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006096}
drh1875f7a2008-12-08 18:19:17 +00006097static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6098 /*
6099 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6100 ** cast into a pointer to a function. And yet the library dlsym() routine
6101 ** returns a void* which is really a pointer to a function. So how do we
6102 ** use dlsym() with -pedantic-errors?
6103 **
6104 ** Variable x below is defined to be a pointer to a function taking
6105 ** parameters void* and const char* and returning a pointer to a function.
6106 ** We initialize x by assigning it a pointer to the dlsym() function.
6107 ** (That assignment requires a cast.) Then we call the function that
6108 ** x points to.
6109 **
6110 ** This work-around is unlikely to work correctly on any system where
6111 ** you really cannot cast a function pointer into void*. But then, on the
6112 ** other hand, dlsym() will not work on such a system either, so we have
6113 ** not really lost anything.
6114 */
6115 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006116 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006117 x = (void(*(*)(void*,const char*))(void))dlsym;
6118 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006119}
danielk1977397d65f2008-11-19 11:35:39 +00006120static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6121 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006122 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006123}
danielk1977b4b47412007-08-17 15:53:36 +00006124#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6125 #define unixDlOpen 0
6126 #define unixDlError 0
6127 #define unixDlSym 0
6128 #define unixDlClose 0
6129#endif
6130
6131/*
danielk197790949c22007-08-17 16:50:38 +00006132** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006133*/
danielk1977397d65f2008-11-19 11:35:39 +00006134static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6135 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006136 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006137
drhbbd42a62004-05-22 17:41:58 +00006138 /* We have to initialize zBuf to prevent valgrind from reporting
6139 ** errors. The reports issued by valgrind are incorrect - we would
6140 ** prefer that the randomness be increased by making use of the
6141 ** uninitialized space in zBuf - but valgrind errors tend to worry
6142 ** some users. Rather than argue, it seems easier just to initialize
6143 ** the whole array and silence valgrind, even if that means less randomness
6144 ** in the random seed.
6145 **
6146 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006147 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006148 ** tests repeatable.
6149 */
danielk1977b4b47412007-08-17 15:53:36 +00006150 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006151 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006152#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006153 {
drhb00d8622014-01-01 15:18:36 +00006154 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006155 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006156 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006157 time_t t;
6158 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006159 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006160 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6161 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6162 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006163 }else{
drhc18b4042012-02-10 03:10:27 +00006164 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006165 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006166 }
drhbbd42a62004-05-22 17:41:58 +00006167 }
6168#endif
drh72cbd072008-10-14 17:58:38 +00006169 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006170}
6171
danielk1977b4b47412007-08-17 15:53:36 +00006172
drhbbd42a62004-05-22 17:41:58 +00006173/*
6174** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006175** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006176** The return value is the number of microseconds of sleep actually
6177** requested from the underlying operating system, a number which
6178** might be greater than or equal to the argument, but not less
6179** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006180*/
danielk1977397d65f2008-11-19 11:35:39 +00006181static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006182#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006183 struct timespec sp;
6184
6185 sp.tv_sec = microseconds / 1000000;
6186 sp.tv_nsec = (microseconds % 1000000) * 1000;
6187 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006188 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006189 return microseconds;
6190#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006191 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006192 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006193 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006194#else
danielk1977b4b47412007-08-17 15:53:36 +00006195 int seconds = (microseconds+999999)/1000000;
6196 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006197 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006198 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006199#endif
drh88f474a2006-01-02 20:00:12 +00006200}
6201
6202/*
drh6b9d6dd2008-12-03 19:34:47 +00006203** The following variable, if set to a non-zero value, is interpreted as
6204** the number of seconds since 1970 and is used to set the result of
6205** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006206*/
6207#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006208int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006209#endif
6210
6211/*
drhb7e8ea22010-05-03 14:32:30 +00006212** Find the current time (in Universal Coordinated Time). Write into *piNow
6213** the current time and date as a Julian Day number times 86_400_000. In
6214** other words, write into *piNow the number of milliseconds since the Julian
6215** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6216** proleptic Gregorian calendar.
6217**
drh31702252011-10-12 23:13:43 +00006218** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6219** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006220*/
6221static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6222 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006223 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006224#if defined(NO_GETTOD)
6225 time_t t;
6226 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006227 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006228#elif OS_VXWORKS
6229 struct timespec sNow;
6230 clock_gettime(CLOCK_REALTIME, &sNow);
6231 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6232#else
6233 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006234 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6235 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006236#endif
6237
6238#ifdef SQLITE_TEST
6239 if( sqlite3_current_time ){
6240 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6241 }
6242#endif
6243 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006244 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006245}
6246
drhc3dfa5e2016-01-22 19:44:03 +00006247#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006248/*
drhbbd42a62004-05-22 17:41:58 +00006249** Find the current time (in Universal Coordinated Time). Write the
6250** current time and date as a Julian Day number into *prNow and
6251** return 0. Return 1 if the time and date cannot be found.
6252*/
danielk1977397d65f2008-11-19 11:35:39 +00006253static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006254 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006255 int rc;
drhff828942010-06-26 21:34:06 +00006256 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006257 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006258 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006259 return rc;
drhbbd42a62004-05-22 17:41:58 +00006260}
drh5337dac2015-11-25 15:15:03 +00006261#else
6262# define unixCurrentTime 0
6263#endif
danielk1977b4b47412007-08-17 15:53:36 +00006264
drhc3dfa5e2016-01-22 19:44:03 +00006265#ifndef SQLITE_OMIT_DEPRECATED
drh6b9d6dd2008-12-03 19:34:47 +00006266/*
6267** We added the xGetLastError() method with the intention of providing
6268** better low-level error messages when operating-system problems come up
6269** during SQLite operation. But so far, none of that has been implemented
6270** in the core. So this routine is never called. For now, it is merely
6271** a place-holder.
6272*/
danielk1977397d65f2008-11-19 11:35:39 +00006273static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6274 UNUSED_PARAMETER(NotUsed);
6275 UNUSED_PARAMETER(NotUsed2);
6276 UNUSED_PARAMETER(NotUsed3);
danielk1977bcb97fe2008-06-06 15:49:29 +00006277 return 0;
6278}
drh5337dac2015-11-25 15:15:03 +00006279#else
6280# define unixGetLastError 0
6281#endif
danielk1977bcb97fe2008-06-06 15:49:29 +00006282
drhf2424c52010-04-26 00:04:55 +00006283
6284/*
drh734c9862008-11-28 15:37:20 +00006285************************ End of sqlite3_vfs methods ***************************
6286******************************************************************************/
6287
drh715ff302008-12-03 22:32:44 +00006288/******************************************************************************
6289************************** Begin Proxy Locking ********************************
6290**
6291** Proxy locking is a "uber-locking-method" in this sense: It uses the
6292** other locking methods on secondary lock files. Proxy locking is a
6293** meta-layer over top of the primitive locking implemented above. For
6294** this reason, the division that implements of proxy locking is deferred
6295** until late in the file (here) after all of the other I/O methods have
6296** been defined - so that the primitive locking methods are available
6297** as services to help with the implementation of proxy locking.
6298**
6299****
6300**
6301** The default locking schemes in SQLite use byte-range locks on the
6302** database file to coordinate safe, concurrent access by multiple readers
6303** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6304** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6305** as POSIX read & write locks over fixed set of locations (via fsctl),
6306** on AFP and SMB only exclusive byte-range locks are available via fsctl
6307** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6308** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6309** address in the shared range is taken for a SHARED lock, the entire
6310** shared range is taken for an EXCLUSIVE lock):
6311**
drhf2f105d2012-08-20 15:53:54 +00006312** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006313** RESERVED_BYTE 0x40000001
6314** SHARED_RANGE 0x40000002 -> 0x40000200
6315**
6316** This works well on the local file system, but shows a nearly 100x
6317** slowdown in read performance on AFP because the AFP client disables
6318** the read cache when byte-range locks are present. Enabling the read
6319** cache exposes a cache coherency problem that is present on all OS X
6320** supported network file systems. NFS and AFP both observe the
6321** close-to-open semantics for ensuring cache coherency
6322** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6323** address the requirements for concurrent database access by multiple
6324** readers and writers
6325** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6326**
6327** To address the performance and cache coherency issues, proxy file locking
6328** changes the way database access is controlled by limiting access to a
6329** single host at a time and moving file locks off of the database file
6330** and onto a proxy file on the local file system.
6331**
6332**
6333** Using proxy locks
6334** -----------------
6335**
6336** C APIs
6337**
drh4bf66fd2015-02-19 02:43:02 +00006338** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006339** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006340** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6341** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006342**
6343**
6344** SQL pragmas
6345**
6346** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6347** PRAGMA [database.]lock_proxy_file
6348**
6349** Specifying ":auto:" means that if there is a conch file with a matching
6350** host ID in it, the proxy path in the conch file will be used, otherwise
6351** a proxy path based on the user's temp dir
6352** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6353** actual proxy file name is generated from the name and path of the
6354** database file. For example:
6355**
6356** For database path "/Users/me/foo.db"
6357** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6358**
6359** Once a lock proxy is configured for a database connection, it can not
6360** be removed, however it may be switched to a different proxy path via
6361** the above APIs (assuming the conch file is not being held by another
6362** connection or process).
6363**
6364**
6365** How proxy locking works
6366** -----------------------
6367**
6368** Proxy file locking relies primarily on two new supporting files:
6369**
6370** * conch file to limit access to the database file to a single host
6371** at a time
6372**
6373** * proxy file to act as a proxy for the advisory locks normally
6374** taken on the database
6375**
6376** The conch file - to use a proxy file, sqlite must first "hold the conch"
6377** by taking an sqlite-style shared lock on the conch file, reading the
6378** contents and comparing the host's unique host ID (see below) and lock
6379** proxy path against the values stored in the conch. The conch file is
6380** stored in the same directory as the database file and the file name
6381** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006382** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006383** host ID and/or proxy path, then the lock is escalated to an exclusive
6384** lock and the conch file contents is updated with the host ID and proxy
6385** path and the lock is downgraded to a shared lock again. If the conch
6386** is held by another process (with a shared lock), the exclusive lock
6387** will fail and SQLITE_BUSY is returned.
6388**
6389** The proxy file - a single-byte file used for all advisory file locks
6390** normally taken on the database file. This allows for safe sharing
6391** of the database file for multiple readers and writers on the same
6392** host (the conch ensures that they all use the same local lock file).
6393**
drh715ff302008-12-03 22:32:44 +00006394** Requesting the lock proxy does not immediately take the conch, it is
6395** only taken when the first request to lock database file is made.
6396** This matches the semantics of the traditional locking behavior, where
6397** opening a connection to a database file does not take a lock on it.
6398** The shared lock and an open file descriptor are maintained until
6399** the connection to the database is closed.
6400**
6401** The proxy file and the lock file are never deleted so they only need
6402** to be created the first time they are used.
6403**
6404** Configuration options
6405** ---------------------
6406**
6407** SQLITE_PREFER_PROXY_LOCKING
6408**
6409** Database files accessed on non-local file systems are
6410** automatically configured for proxy locking, lock files are
6411** named automatically using the same logic as
6412** PRAGMA lock_proxy_file=":auto:"
6413**
6414** SQLITE_PROXY_DEBUG
6415**
6416** Enables the logging of error messages during host id file
6417** retrieval and creation
6418**
drh715ff302008-12-03 22:32:44 +00006419** LOCKPROXYDIR
6420**
6421** Overrides the default directory used for lock proxy files that
6422** are named automatically via the ":auto:" setting
6423**
6424** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6425**
6426** Permissions to use when creating a directory for storing the
6427** lock proxy files, only used when LOCKPROXYDIR is not set.
6428**
6429**
6430** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6431** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6432** force proxy locking to be used for every database file opened, and 0
6433** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006434** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006435** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6436*/
6437
6438/*
6439** Proxy locking is only available on MacOSX
6440*/
drhd2cb50b2009-01-09 21:41:17 +00006441#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006442
drh715ff302008-12-03 22:32:44 +00006443/*
6444** The proxyLockingContext has the path and file structures for the remote
6445** and local proxy files in it
6446*/
6447typedef struct proxyLockingContext proxyLockingContext;
6448struct proxyLockingContext {
6449 unixFile *conchFile; /* Open conch file */
6450 char *conchFilePath; /* Name of the conch file */
6451 unixFile *lockProxy; /* Open proxy lock file */
6452 char *lockProxyPath; /* Name of the proxy lock file */
6453 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006454 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006455 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006456 void *oldLockingContext; /* Original lockingcontext to restore on close */
6457 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6458};
6459
drh7ed97b92010-01-20 13:07:21 +00006460/*
6461** The proxy lock file path for the database at dbPath is written into lPath,
6462** which must point to valid, writable memory large enough for a maxLen length
6463** file path.
drh715ff302008-12-03 22:32:44 +00006464*/
drh715ff302008-12-03 22:32:44 +00006465static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6466 int len;
6467 int dbLen;
6468 int i;
6469
6470#ifdef LOCKPROXYDIR
6471 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6472#else
6473# ifdef _CS_DARWIN_USER_TEMP_DIR
6474 {
drh7ed97b92010-01-20 13:07:21 +00006475 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006476 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006477 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006478 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006479 }
drh7ed97b92010-01-20 13:07:21 +00006480 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006481 }
6482# else
6483 len = strlcpy(lPath, "/tmp/", maxLen);
6484# endif
6485#endif
6486
6487 if( lPath[len-1]!='/' ){
6488 len = strlcat(lPath, "/", maxLen);
6489 }
6490
6491 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006492 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006493 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006494 char c = dbPath[i];
6495 lPath[i+len] = (c=='/')?'_':c;
6496 }
6497 lPath[i+len]='\0';
6498 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006499 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006500 return SQLITE_OK;
6501}
6502
drh7ed97b92010-01-20 13:07:21 +00006503/*
6504 ** Creates the lock file and any missing directories in lockPath
6505 */
6506static int proxyCreateLockPath(const char *lockPath){
6507 int i, len;
6508 char buf[MAXPATHLEN];
6509 int start = 0;
6510
6511 assert(lockPath!=NULL);
6512 /* try to create all the intermediate directories */
6513 len = (int)strlen(lockPath);
6514 buf[0] = lockPath[0];
6515 for( i=1; i<len; i++ ){
6516 if( lockPath[i] == '/' && (i - start > 0) ){
6517 /* only mkdir if leaf dir != "." or "/" or ".." */
6518 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6519 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6520 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006521 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006522 int err=errno;
6523 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006524 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006525 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006526 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006527 return err;
6528 }
6529 }
6530 }
6531 start=i+1;
6532 }
6533 buf[i] = lockPath[i];
6534 }
drh62aaa6c2015-11-21 17:27:42 +00006535 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006536 return 0;
6537}
6538
drh715ff302008-12-03 22:32:44 +00006539/*
6540** Create a new VFS file descriptor (stored in memory obtained from
6541** sqlite3_malloc) and open the file named "path" in the file descriptor.
6542**
6543** The caller is responsible not only for closing the file descriptor
6544** but also for freeing the memory associated with the file descriptor.
6545*/
drh7ed97b92010-01-20 13:07:21 +00006546static int proxyCreateUnixFile(
6547 const char *path, /* path for the new unixFile */
6548 unixFile **ppFile, /* unixFile created and returned by ref */
6549 int islockfile /* if non zero missing dirs will be created */
6550) {
6551 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006552 unixFile *pNew;
6553 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006554 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006555 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006556 int terrno = 0;
6557 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006558
drh7ed97b92010-01-20 13:07:21 +00006559 /* 1. first try to open/create the file
6560 ** 2. if that fails, and this is a lock file (not-conch), try creating
6561 ** the parent directories and then try again.
6562 ** 3. if that fails, try to open the file read-only
6563 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6564 */
6565 pUnused = findReusableFd(path, openFlags);
6566 if( pUnused ){
6567 fd = pUnused->fd;
6568 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006569 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006570 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006571 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006572 }
6573 }
6574 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006575 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006576 terrno = errno;
6577 if( fd<0 && errno==ENOENT && islockfile ){
6578 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006579 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006580 }
6581 }
6582 }
6583 if( fd<0 ){
6584 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006585 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006586 terrno = errno;
6587 }
6588 if( fd<0 ){
6589 if( islockfile ){
6590 return SQLITE_BUSY;
6591 }
6592 switch (terrno) {
6593 case EACCES:
6594 return SQLITE_PERM;
6595 case EIO:
6596 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6597 default:
drh9978c972010-02-23 17:36:32 +00006598 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006599 }
6600 }
6601
drhf3cdcdc2015-04-29 16:50:28 +00006602 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006603 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006604 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006605 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006606 }
6607 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006608 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006609 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006610 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006611 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006612 pUnused->fd = fd;
6613 pUnused->flags = openFlags;
6614 pNew->pUnused = pUnused;
6615
drhc02a43a2012-01-10 23:18:38 +00006616 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006617 if( rc==SQLITE_OK ){
6618 *ppFile = pNew;
6619 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006620 }
drh7ed97b92010-01-20 13:07:21 +00006621end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006622 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006623 sqlite3_free(pNew);
6624 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006625 return rc;
6626}
6627
drh7ed97b92010-01-20 13:07:21 +00006628#ifdef SQLITE_TEST
6629/* simulate multiple hosts by creating unique hostid file paths */
6630int sqlite3_hostid_num = 0;
6631#endif
6632
6633#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6634
drh6bca6512015-04-13 23:05:28 +00006635#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006636/* Not always defined in the headers as it ought to be */
6637extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006638#endif
drh0ab216a2010-07-02 17:10:40 +00006639
drh7ed97b92010-01-20 13:07:21 +00006640/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6641** bytes of writable memory.
6642*/
6643static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006644 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6645 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006646#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006647 {
drh4bf66fd2015-02-19 02:43:02 +00006648 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006649 if( gethostuuid(pHostID, &timeout) ){
6650 int err = errno;
6651 if( pError ){
6652 *pError = err;
6653 }
6654 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006655 }
drh7ed97b92010-01-20 13:07:21 +00006656 }
drh3d4435b2011-08-26 20:55:50 +00006657#else
6658 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006659#endif
drh7ed97b92010-01-20 13:07:21 +00006660#ifdef SQLITE_TEST
6661 /* simulate multiple hosts by creating unique hostid file paths */
6662 if( sqlite3_hostid_num != 0){
6663 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6664 }
6665#endif
6666
6667 return SQLITE_OK;
6668}
6669
6670/* The conch file contains the header, host id and lock file path
6671 */
6672#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6673#define PROXY_HEADERLEN 1 /* conch file header length */
6674#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6675#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6676
6677/*
6678** Takes an open conch file, copies the contents to a new path and then moves
6679** it back. The newly created file's file descriptor is assigned to the
6680** conch file structure and finally the original conch file descriptor is
6681** closed. Returns zero if successful.
6682*/
6683static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6684 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6685 unixFile *conchFile = pCtx->conchFile;
6686 char tPath[MAXPATHLEN];
6687 char buf[PROXY_MAXCONCHLEN];
6688 char *cPath = pCtx->conchFilePath;
6689 size_t readLen = 0;
6690 size_t pathLen = 0;
6691 char errmsg[64] = "";
6692 int fd = -1;
6693 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006694 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006695
6696 /* create a new path by replace the trailing '-conch' with '-break' */
6697 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6698 if( pathLen>MAXPATHLEN || pathLen<6 ||
6699 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006700 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006701 goto end_breaklock;
6702 }
6703 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006704 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006705 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006706 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006707 goto end_breaklock;
6708 }
6709 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006710 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006711 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006712 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006713 goto end_breaklock;
6714 }
drhe562be52011-03-02 18:01:10 +00006715 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006716 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006717 goto end_breaklock;
6718 }
6719 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006720 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006721 goto end_breaklock;
6722 }
6723 rc = 0;
6724 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006725 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006726 conchFile->h = fd;
6727 conchFile->openFlags = O_RDWR | O_CREAT;
6728
6729end_breaklock:
6730 if( rc ){
6731 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006732 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006733 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006734 }
6735 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6736 }
6737 return rc;
6738}
6739
6740/* Take the requested lock on the conch file and break a stale lock if the
6741** host id matches.
6742*/
6743static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6744 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6745 unixFile *conchFile = pCtx->conchFile;
6746 int rc = SQLITE_OK;
6747 int nTries = 0;
6748 struct timespec conchModTime;
6749
drh3d4435b2011-08-26 20:55:50 +00006750 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006751 do {
6752 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6753 nTries ++;
6754 if( rc==SQLITE_BUSY ){
6755 /* If the lock failed (busy):
6756 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6757 * 2nd try: fail if the mod time changed or host id is different, wait
6758 * 10 sec and try again
6759 * 3rd try: break the lock unless the mod time has changed.
6760 */
6761 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006762 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006763 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006764 return SQLITE_IOERR_LOCK;
6765 }
6766
6767 if( nTries==1 ){
6768 conchModTime = buf.st_mtimespec;
6769 usleep(500000); /* wait 0.5 sec and try the lock again*/
6770 continue;
6771 }
6772
6773 assert( nTries>1 );
6774 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6775 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6776 return SQLITE_BUSY;
6777 }
6778
6779 if( nTries==2 ){
6780 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006781 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006782 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006783 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006784 return SQLITE_IOERR_LOCK;
6785 }
6786 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6787 /* don't break the lock if the host id doesn't match */
6788 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6789 return SQLITE_BUSY;
6790 }
6791 }else{
6792 /* don't break the lock on short read or a version mismatch */
6793 return SQLITE_BUSY;
6794 }
6795 usleep(10000000); /* wait 10 sec and try the lock again */
6796 continue;
6797 }
6798
6799 assert( nTries==3 );
6800 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6801 rc = SQLITE_OK;
6802 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006803 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006804 }
6805 if( !rc ){
6806 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6807 }
6808 }
6809 }
6810 } while( rc==SQLITE_BUSY && nTries<3 );
6811
6812 return rc;
6813}
6814
6815/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006816** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6817** lockPath means that the lockPath in the conch file will be used if the
6818** host IDs match, or a new lock path will be generated automatically
6819** and written to the conch file.
6820*/
6821static int proxyTakeConch(unixFile *pFile){
6822 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6823
drh7ed97b92010-01-20 13:07:21 +00006824 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006825 return SQLITE_OK;
6826 }else{
6827 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006828 uuid_t myHostID;
6829 int pError = 0;
6830 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006831 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006832 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006833 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006834 int createConch = 0;
6835 int hostIdMatch = 0;
6836 int readLen = 0;
6837 int tryOldLockPath = 0;
6838 int forceNewLockPath = 0;
6839
drh308c2a52010-05-14 11:30:18 +00006840 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006841 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006842 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006843
drh7ed97b92010-01-20 13:07:21 +00006844 rc = proxyGetHostID(myHostID, &pError);
6845 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006846 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006847 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006848 }
drh7ed97b92010-01-20 13:07:21 +00006849 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006850 if( rc!=SQLITE_OK ){
6851 goto end_takeconch;
6852 }
drh7ed97b92010-01-20 13:07:21 +00006853 /* read the existing conch file */
6854 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6855 if( readLen<0 ){
6856 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006857 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006858 rc = SQLITE_IOERR_READ;
6859 goto end_takeconch;
6860 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6861 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6862 /* a short read or version format mismatch means we need to create a new
6863 ** conch file.
6864 */
6865 createConch = 1;
6866 }
6867 /* if the host id matches and the lock path already exists in the conch
6868 ** we'll try to use the path there, if we can't open that path, we'll
6869 ** retry with a new auto-generated path
6870 */
6871 do { /* in case we need to try again for an :auto: named lock file */
6872
6873 if( !createConch && !forceNewLockPath ){
6874 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6875 PROXY_HOSTIDLEN);
6876 /* if the conch has data compare the contents */
6877 if( !pCtx->lockProxyPath ){
6878 /* for auto-named local lock file, just check the host ID and we'll
6879 ** use the local lock file path that's already in there
6880 */
6881 if( hostIdMatch ){
6882 size_t pathLen = (readLen - PROXY_PATHINDEX);
6883
6884 if( pathLen>=MAXPATHLEN ){
6885 pathLen=MAXPATHLEN-1;
6886 }
6887 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6888 lockPath[pathLen] = 0;
6889 tempLockPath = lockPath;
6890 tryOldLockPath = 1;
6891 /* create a copy of the lock path if the conch is taken */
6892 goto end_takeconch;
6893 }
6894 }else if( hostIdMatch
6895 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6896 readLen-PROXY_PATHINDEX)
6897 ){
6898 /* conch host and lock path match */
6899 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006900 }
drh7ed97b92010-01-20 13:07:21 +00006901 }
6902
6903 /* if the conch isn't writable and doesn't match, we can't take it */
6904 if( (conchFile->openFlags&O_RDWR) == 0 ){
6905 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006906 goto end_takeconch;
6907 }
drh7ed97b92010-01-20 13:07:21 +00006908
6909 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006910 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006911 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6912 tempLockPath = lockPath;
6913 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006914 }
drh7ed97b92010-01-20 13:07:21 +00006915
6916 /* update conch with host and path (this will fail if other process
6917 ** has a shared lock already), if the host id matches, use the big
6918 ** stick.
drh715ff302008-12-03 22:32:44 +00006919 */
drh7ed97b92010-01-20 13:07:21 +00006920 futimes(conchFile->h, NULL);
6921 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00006922 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00006923 /* We are trying for an exclusive lock but another thread in this
6924 ** same process is still holding a shared lock. */
6925 rc = SQLITE_BUSY;
6926 } else {
6927 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006928 }
drh715ff302008-12-03 22:32:44 +00006929 }else{
drh4bf66fd2015-02-19 02:43:02 +00006930 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00006931 }
drh7ed97b92010-01-20 13:07:21 +00006932 if( rc==SQLITE_OK ){
6933 char writeBuffer[PROXY_MAXCONCHLEN];
6934 int writeSize = 0;
6935
6936 writeBuffer[0] = (char)PROXY_CONCHVERSION;
6937 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
6938 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00006939 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
6940 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00006941 }else{
6942 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
6943 }
6944 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00006945 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00006946 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00006947 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00006948 /* If we created a new conch file (not just updated the contents of a
6949 ** valid conch file), try to match the permissions of the database
6950 */
6951 if( rc==SQLITE_OK && createConch ){
6952 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006953 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00006954 if( err==0 ){
6955 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
6956 S_IROTH|S_IWOTH);
6957 /* try to match the database file R/W permissions, ignore failure */
6958#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00006959 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00006960#else
drhff812312011-02-23 13:33:46 +00006961 do{
drhe562be52011-03-02 18:01:10 +00006962 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00006963 }while( rc==(-1) && errno==EINTR );
6964 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00006965 int code = errno;
6966 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
6967 cmode, code, strerror(code));
6968 } else {
6969 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
6970 }
6971 }else{
6972 int code = errno;
6973 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
6974 err, code, strerror(code));
6975#endif
6976 }
drh715ff302008-12-03 22:32:44 +00006977 }
6978 }
drh7ed97b92010-01-20 13:07:21 +00006979 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
6980
6981 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00006982 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00006983 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00006984 int fd;
drh7ed97b92010-01-20 13:07:21 +00006985 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00006986 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006987 }
6988 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00006989 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00006990 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00006991 if( fd>=0 ){
6992 pFile->h = fd;
6993 }else{
drh9978c972010-02-23 17:36:32 +00006994 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00006995 during locking */
6996 }
6997 }
6998 if( rc==SQLITE_OK && !pCtx->lockProxy ){
6999 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7000 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7001 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7002 /* we couldn't create the proxy lock file with the old lock file path
7003 ** so try again via auto-naming
7004 */
7005 forceNewLockPath = 1;
7006 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007007 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007008 }
7009 }
7010 if( rc==SQLITE_OK ){
7011 /* Need to make a copy of path if we extracted the value
7012 ** from the conch file or the path was allocated on the stack
7013 */
7014 if( tempLockPath ){
7015 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7016 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007017 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007018 }
7019 }
7020 }
7021 if( rc==SQLITE_OK ){
7022 pCtx->conchHeld = 1;
7023
7024 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7025 afpLockingContext *afpCtx;
7026 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7027 afpCtx->dbPath = pCtx->lockProxyPath;
7028 }
7029 } else {
7030 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7031 }
drh308c2a52010-05-14 11:30:18 +00007032 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7033 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007034 return rc;
drh308c2a52010-05-14 11:30:18 +00007035 } while (1); /* in case we need to retry the :auto: lock file -
7036 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007037 }
7038}
7039
7040/*
7041** If pFile holds a lock on a conch file, then release that lock.
7042*/
7043static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007044 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007045 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7046 unixFile *conchFile; /* Name of the conch file */
7047
7048 pCtx = (proxyLockingContext *)pFile->lockingContext;
7049 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007050 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007051 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007052 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007053 if( pCtx->conchHeld>0 ){
7054 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7055 }
drh715ff302008-12-03 22:32:44 +00007056 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007057 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7058 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007059 return rc;
7060}
7061
7062/*
7063** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007064** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007065** Make *pConchPath point to the new name. Return SQLITE_OK on success
7066** or SQLITE_NOMEM if unable to obtain memory.
7067**
7068** The caller is responsible for ensuring that the allocated memory
7069** space is eventually freed.
7070**
7071** *pConchPath is set to NULL if a memory allocation error occurs.
7072*/
7073static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7074 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007075 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007076 char *conchPath; /* buffer in which to construct conch name */
7077
7078 /* Allocate space for the conch filename and initialize the name to
7079 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007080 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007081 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007082 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007083 }
7084 memcpy(conchPath, dbPath, len+1);
7085
7086 /* now insert a "." before the last / character */
7087 for( i=(len-1); i>=0; i-- ){
7088 if( conchPath[i]=='/' ){
7089 i++;
7090 break;
7091 }
7092 }
7093 conchPath[i]='.';
7094 while ( i<len ){
7095 conchPath[i+1]=dbPath[i];
7096 i++;
7097 }
7098
7099 /* append the "-conch" suffix to the file */
7100 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007101 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007102
7103 return SQLITE_OK;
7104}
7105
7106
7107/* Takes a fully configured proxy locking-style unix file and switches
7108** the local lock file path
7109*/
7110static int switchLockProxyPath(unixFile *pFile, const char *path) {
7111 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7112 char *oldPath = pCtx->lockProxyPath;
7113 int rc = SQLITE_OK;
7114
drh308c2a52010-05-14 11:30:18 +00007115 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007116 return SQLITE_BUSY;
7117 }
7118
7119 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7120 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7121 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7122 return SQLITE_OK;
7123 }else{
7124 unixFile *lockProxy = pCtx->lockProxy;
7125 pCtx->lockProxy=NULL;
7126 pCtx->conchHeld = 0;
7127 if( lockProxy!=NULL ){
7128 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7129 if( rc ) return rc;
7130 sqlite3_free(lockProxy);
7131 }
7132 sqlite3_free(oldPath);
7133 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7134 }
7135
7136 return rc;
7137}
7138
7139/*
7140** pFile is a file that has been opened by a prior xOpen call. dbPath
7141** is a string buffer at least MAXPATHLEN+1 characters in size.
7142**
7143** This routine find the filename associated with pFile and writes it
7144** int dbPath.
7145*/
7146static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007147#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007148 if( pFile->pMethod == &afpIoMethods ){
7149 /* afp style keeps a reference to the db path in the filePath field
7150 ** of the struct */
drhea678832008-12-10 19:26:22 +00007151 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007152 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7153 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007154 } else
drh715ff302008-12-03 22:32:44 +00007155#endif
7156 if( pFile->pMethod == &dotlockIoMethods ){
7157 /* dot lock style uses the locking context to store the dot lock
7158 ** file path */
7159 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7160 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7161 }else{
7162 /* all other styles use the locking context to store the db file path */
7163 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007164 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007165 }
7166 return SQLITE_OK;
7167}
7168
7169/*
7170** Takes an already filled in unix file and alters it so all file locking
7171** will be performed on the local proxy lock file. The following fields
7172** are preserved in the locking context so that they can be restored and
7173** the unix structure properly cleaned up at close time:
7174** ->lockingContext
7175** ->pMethod
7176*/
7177static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7178 proxyLockingContext *pCtx;
7179 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7180 char *lockPath=NULL;
7181 int rc = SQLITE_OK;
7182
drh308c2a52010-05-14 11:30:18 +00007183 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007184 return SQLITE_BUSY;
7185 }
7186 proxyGetDbPathForUnixFile(pFile, dbPath);
7187 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7188 lockPath=NULL;
7189 }else{
7190 lockPath=(char *)path;
7191 }
7192
drh308c2a52010-05-14 11:30:18 +00007193 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007194 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007195
drhf3cdcdc2015-04-29 16:50:28 +00007196 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007197 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007198 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007199 }
7200 memset(pCtx, 0, sizeof(*pCtx));
7201
7202 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7203 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007204 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7205 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7206 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7207 ** (c) the file system is read-only, then enable no-locking access.
7208 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7209 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7210 */
7211 struct statfs fsInfo;
7212 struct stat conchInfo;
7213 int goLockless = 0;
7214
drh99ab3b12011-03-02 15:09:07 +00007215 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007216 int err = errno;
7217 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7218 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7219 }
7220 }
7221 if( goLockless ){
7222 pCtx->conchHeld = -1; /* read only FS/ lockless */
7223 rc = SQLITE_OK;
7224 }
7225 }
drh715ff302008-12-03 22:32:44 +00007226 }
7227 if( rc==SQLITE_OK && lockPath ){
7228 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7229 }
7230
7231 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007232 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7233 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007234 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007235 }
7236 }
7237 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007238 /* all memory is allocated, proxys are created and assigned,
7239 ** switch the locking context and pMethod then return.
7240 */
drh715ff302008-12-03 22:32:44 +00007241 pCtx->oldLockingContext = pFile->lockingContext;
7242 pFile->lockingContext = pCtx;
7243 pCtx->pOldMethod = pFile->pMethod;
7244 pFile->pMethod = &proxyIoMethods;
7245 }else{
7246 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007247 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007248 sqlite3_free(pCtx->conchFile);
7249 }
drhd56b1212010-08-11 06:14:15 +00007250 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007251 sqlite3_free(pCtx->conchFilePath);
7252 sqlite3_free(pCtx);
7253 }
drh308c2a52010-05-14 11:30:18 +00007254 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7255 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007256 return rc;
7257}
7258
7259
7260/*
7261** This routine handles sqlite3_file_control() calls that are specific
7262** to proxy locking.
7263*/
7264static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7265 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007266 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007267 unixFile *pFile = (unixFile*)id;
7268 if( pFile->pMethod == &proxyIoMethods ){
7269 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7270 proxyTakeConch(pFile);
7271 if( pCtx->lockProxyPath ){
7272 *(const char **)pArg = pCtx->lockProxyPath;
7273 }else{
7274 *(const char **)pArg = ":auto: (not held)";
7275 }
7276 } else {
7277 *(const char **)pArg = NULL;
7278 }
7279 return SQLITE_OK;
7280 }
drh4bf66fd2015-02-19 02:43:02 +00007281 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007282 unixFile *pFile = (unixFile*)id;
7283 int rc = SQLITE_OK;
7284 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7285 if( pArg==NULL || (const char *)pArg==0 ){
7286 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007287 /* turn off proxy locking - not supported. If support is added for
7288 ** switching proxy locking mode off then it will need to fail if
7289 ** the journal mode is WAL mode.
7290 */
drh715ff302008-12-03 22:32:44 +00007291 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7292 }else{
7293 /* turn off proxy locking - already off - NOOP */
7294 rc = SQLITE_OK;
7295 }
7296 }else{
7297 const char *proxyPath = (const char *)pArg;
7298 if( isProxyStyle ){
7299 proxyLockingContext *pCtx =
7300 (proxyLockingContext*)pFile->lockingContext;
7301 if( !strcmp(pArg, ":auto:")
7302 || (pCtx->lockProxyPath &&
7303 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7304 ){
7305 rc = SQLITE_OK;
7306 }else{
7307 rc = switchLockProxyPath(pFile, proxyPath);
7308 }
7309 }else{
7310 /* turn on proxy file locking */
7311 rc = proxyTransformUnixFile(pFile, proxyPath);
7312 }
7313 }
7314 return rc;
7315 }
7316 default: {
7317 assert( 0 ); /* The call assures that only valid opcodes are sent */
7318 }
7319 }
7320 /*NOTREACHED*/
7321 return SQLITE_ERROR;
7322}
7323
7324/*
7325** Within this division (the proxying locking implementation) the procedures
7326** above this point are all utilities. The lock-related methods of the
7327** proxy-locking sqlite3_io_method object follow.
7328*/
7329
7330
7331/*
7332** This routine checks if there is a RESERVED lock held on the specified
7333** file by this or any other process. If such a lock is held, set *pResOut
7334** to a non-zero value otherwise *pResOut is set to zero. The return value
7335** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7336*/
7337static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7338 unixFile *pFile = (unixFile*)id;
7339 int rc = proxyTakeConch(pFile);
7340 if( rc==SQLITE_OK ){
7341 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007342 if( pCtx->conchHeld>0 ){
7343 unixFile *proxy = pCtx->lockProxy;
7344 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7345 }else{ /* conchHeld < 0 is lockless */
7346 pResOut=0;
7347 }
drh715ff302008-12-03 22:32:44 +00007348 }
7349 return rc;
7350}
7351
7352/*
drh308c2a52010-05-14 11:30:18 +00007353** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007354** of the following:
7355**
7356** (1) SHARED_LOCK
7357** (2) RESERVED_LOCK
7358** (3) PENDING_LOCK
7359** (4) EXCLUSIVE_LOCK
7360**
7361** Sometimes when requesting one lock state, additional lock states
7362** are inserted in between. The locking might fail on one of the later
7363** transitions leaving the lock state different from what it started but
7364** still short of its goal. The following chart shows the allowed
7365** transitions and the inserted intermediate states:
7366**
7367** UNLOCKED -> SHARED
7368** SHARED -> RESERVED
7369** SHARED -> (PENDING) -> EXCLUSIVE
7370** RESERVED -> (PENDING) -> EXCLUSIVE
7371** PENDING -> EXCLUSIVE
7372**
7373** This routine will only increase a lock. Use the sqlite3OsUnlock()
7374** routine to lower a locking level.
7375*/
drh308c2a52010-05-14 11:30:18 +00007376static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007377 unixFile *pFile = (unixFile*)id;
7378 int rc = proxyTakeConch(pFile);
7379 if( rc==SQLITE_OK ){
7380 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007381 if( pCtx->conchHeld>0 ){
7382 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007383 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7384 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007385 }else{
7386 /* conchHeld < 0 is lockless */
7387 }
drh715ff302008-12-03 22:32:44 +00007388 }
7389 return rc;
7390}
7391
7392
7393/*
drh308c2a52010-05-14 11:30:18 +00007394** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007395** must be either NO_LOCK or SHARED_LOCK.
7396**
7397** If the locking level of the file descriptor is already at or below
7398** the requested locking level, this routine is a no-op.
7399*/
drh308c2a52010-05-14 11:30:18 +00007400static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007401 unixFile *pFile = (unixFile*)id;
7402 int rc = proxyTakeConch(pFile);
7403 if( rc==SQLITE_OK ){
7404 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007405 if( pCtx->conchHeld>0 ){
7406 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007407 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7408 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007409 }else{
7410 /* conchHeld < 0 is lockless */
7411 }
drh715ff302008-12-03 22:32:44 +00007412 }
7413 return rc;
7414}
7415
7416/*
7417** Close a file that uses proxy locks.
7418*/
7419static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007420 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007421 unixFile *pFile = (unixFile*)id;
7422 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7423 unixFile *lockProxy = pCtx->lockProxy;
7424 unixFile *conchFile = pCtx->conchFile;
7425 int rc = SQLITE_OK;
7426
7427 if( lockProxy ){
7428 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7429 if( rc ) return rc;
7430 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7431 if( rc ) return rc;
7432 sqlite3_free(lockProxy);
7433 pCtx->lockProxy = 0;
7434 }
7435 if( conchFile ){
7436 if( pCtx->conchHeld ){
7437 rc = proxyReleaseConch(pFile);
7438 if( rc ) return rc;
7439 }
7440 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7441 if( rc ) return rc;
7442 sqlite3_free(conchFile);
7443 }
drhd56b1212010-08-11 06:14:15 +00007444 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007445 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007446 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007447 /* restore the original locking context and pMethod then close it */
7448 pFile->lockingContext = pCtx->oldLockingContext;
7449 pFile->pMethod = pCtx->pOldMethod;
7450 sqlite3_free(pCtx);
7451 return pFile->pMethod->xClose(id);
7452 }
7453 return SQLITE_OK;
7454}
7455
7456
7457
drhd2cb50b2009-01-09 21:41:17 +00007458#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007459/*
7460** The proxy locking style is intended for use with AFP filesystems.
7461** And since AFP is only supported on MacOSX, the proxy locking is also
7462** restricted to MacOSX.
7463**
7464**
7465******************* End of the proxy lock implementation **********************
7466******************************************************************************/
7467
drh734c9862008-11-28 15:37:20 +00007468/*
danielk1977e339d652008-06-28 11:23:00 +00007469** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007470**
7471** This routine registers all VFS implementations for unix-like operating
7472** systems. This routine, and the sqlite3_os_end() routine that follows,
7473** should be the only routines in this file that are visible from other
7474** files.
drh6b9d6dd2008-12-03 19:34:47 +00007475**
7476** This routine is called once during SQLite initialization and by a
7477** single thread. The memory allocation and mutex subsystems have not
7478** necessarily been initialized when this routine is called, and so they
7479** should not be used.
drh153c62c2007-08-24 03:51:33 +00007480*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007481int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007482 /*
7483 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007484 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7485 ** to the "finder" function. (pAppData is a pointer to a pointer because
7486 ** silly C90 rules prohibit a void* from being cast to a function pointer
7487 ** and so we have to go through the intermediate pointer to avoid problems
7488 ** when compiling with -pedantic-errors on GCC.)
7489 **
7490 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007491 ** finder-function. The finder-function returns a pointer to the
7492 ** sqlite_io_methods object that implements the desired locking
7493 ** behaviors. See the division above that contains the IOMETHODS
7494 ** macro for addition information on finder-functions.
7495 **
7496 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7497 ** object. But the "autolockIoFinder" available on MacOSX does a little
7498 ** more than that; it looks at the filesystem type that hosts the
7499 ** database file and tries to choose an locking method appropriate for
7500 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007501 */
drh7708e972008-11-29 00:56:52 +00007502 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007503 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007504 sizeof(unixFile), /* szOsFile */ \
7505 MAX_PATHNAME, /* mxPathname */ \
7506 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007507 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007508 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007509 unixOpen, /* xOpen */ \
7510 unixDelete, /* xDelete */ \
7511 unixAccess, /* xAccess */ \
7512 unixFullPathname, /* xFullPathname */ \
7513 unixDlOpen, /* xDlOpen */ \
7514 unixDlError, /* xDlError */ \
7515 unixDlSym, /* xDlSym */ \
7516 unixDlClose, /* xDlClose */ \
7517 unixRandomness, /* xRandomness */ \
7518 unixSleep, /* xSleep */ \
7519 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007520 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007521 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007522 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007523 unixGetSystemCall, /* xGetSystemCall */ \
7524 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007525 }
7526
drh6b9d6dd2008-12-03 19:34:47 +00007527 /*
7528 ** All default VFSes for unix are contained in the following array.
7529 **
7530 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7531 ** by the SQLite core when the VFS is registered. So the following
7532 ** array cannot be const.
7533 */
danielk1977e339d652008-06-28 11:23:00 +00007534 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007535#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007536 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007537#elif OS_VXWORKS
7538 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007539#else
7540 UNIXVFS("unix", posixIoFinder ),
7541#endif
7542 UNIXVFS("unix-none", nolockIoFinder ),
7543 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007544 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007545#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007546 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007547#endif
drhe89b2912015-03-03 20:42:01 +00007548#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007549 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007550#endif
drhe89b2912015-03-03 20:42:01 +00007551#if SQLITE_ENABLE_LOCKING_STYLE
7552 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007553#endif
drhd2cb50b2009-01-09 21:41:17 +00007554#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007555 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007556 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007557 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007558#endif
drh153c62c2007-08-24 03:51:33 +00007559 };
drh6b9d6dd2008-12-03 19:34:47 +00007560 unsigned int i; /* Loop counter */
7561
drh2aa5a002011-04-13 13:42:25 +00007562 /* Double-check that the aSyscall[] array has been constructed
7563 ** correctly. See ticket [bb3a86e890c8e96ab] */
dancaf6b152016-01-25 18:05:49 +00007564 assert( ArraySize(aSyscall)==28 );
drh2aa5a002011-04-13 13:42:25 +00007565
drh6b9d6dd2008-12-03 19:34:47 +00007566 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007567 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007568 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007569 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007570 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007571}
danielk1977e339d652008-06-28 11:23:00 +00007572
7573/*
drh6b9d6dd2008-12-03 19:34:47 +00007574** Shutdown the operating system interface.
7575**
7576** Some operating systems might need to do some cleanup in this routine,
7577** to release dynamically allocated objects. But not on unix.
7578** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007579*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007580int sqlite3_os_end(void){
7581 return SQLITE_OK;
7582}
drhdce8bdb2007-08-16 13:01:44 +00007583
danielk197729bafea2008-06-26 10:41:19 +00007584#endif /* SQLITE_OS_UNIX */