blob: 3397b3a2138cdc19a2a62d10eb811171a8de8fa2 [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 */
drh79a2ca32016-03-04 03:14:39 +000075#if defined(__APPLE__)
76# define HAVE_PREAD 1
77# define HAVE_PWRITE 1
78#endif
drhe32a2562016-03-04 02:38:00 +000079#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
80# undef USE_PREAD
drhe32a2562016-03-04 02:38:00 +000081# define USE_PREAD64 1
drhe32a2562016-03-04 02:38:00 +000082#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
drh79a2ca32016-03-04 03:14:39 +000083# undef USE_PREAD64
84# define USE_PREAD 1
drhe32a2562016-03-04 02:38:00 +000085#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>
danefe16972017-07-20 19:49:14 +000093#include <sys/ioctl.h>
drh9cbe6352005-11-29 03:13:21 +000094#include <unistd.h>
drhbbd42a62004-05-22 17:41:58 +000095#include <time.h>
drh19e2d372005-08-29 23:00:03 +000096#include <sys/time.h>
drhbbd42a62004-05-22 17:41:58 +000097#include <errno.h>
dan32c12fe2013-05-02 17:37:31 +000098#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drh91be7dc2014-08-11 13:53:30 +000099# include <sys/mman.h>
drhb469f462010-12-22 21:48:50 +0000100#endif
drh1da88f02011-12-17 16:09:16 +0000101
drhe89b2912015-03-03 20:42:01 +0000102#if SQLITE_ENABLE_LOCKING_STYLE
danielk1977c70dfc42008-11-19 13:52:30 +0000103# include <sys/ioctl.h>
drhe89b2912015-03-03 20:42:01 +0000104# include <sys/file.h>
105# include <sys/param.h>
drhbfe66312006-10-03 17:40:40 +0000106#endif /* SQLITE_ENABLE_LOCKING_STYLE */
drh9cbe6352005-11-29 03:13:21 +0000107
drh6bca6512015-04-13 23:05:28 +0000108#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
109 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
110# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
111 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
112# define HAVE_GETHOSTUUID 1
113# else
114# warning "gethostuuid() is disabled."
115# endif
116#endif
117
118
drhe89b2912015-03-03 20:42:01 +0000119#if OS_VXWORKS
120# include <sys/ioctl.h>
121# include <semaphore.h>
122# include <limits.h>
123#endif /* OS_VXWORKS */
124
125#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000126# include <sys/mount.h>
127#endif
128
drhdbe4b882011-06-20 18:00:17 +0000129#ifdef HAVE_UTIME
130# include <utime.h>
131#endif
132
drh9cbe6352005-11-29 03:13:21 +0000133/*
drh7ed97b92010-01-20 13:07:21 +0000134** Allowed values of unixFile.fsFlags
135*/
136#define SQLITE_FSFLAGS_IS_MSDOS 0x1
137
138/*
drhf1a221e2006-01-15 17:27:17 +0000139** If we are to be thread-safe, include the pthreads header and define
140** the SQLITE_UNIX_THREADS macro.
drh9cbe6352005-11-29 03:13:21 +0000141*/
drhd677b3d2007-08-20 22:48:41 +0000142#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000143# include <pthread.h>
144# define SQLITE_UNIX_THREADS 1
145#endif
146
147/*
148** Default permissions when creating a new file
149*/
150#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
151# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
152#endif
153
danielk1977b4b47412007-08-17 15:53:36 +0000154/*
drh5adc60b2012-04-14 13:25:11 +0000155** Default permissions when creating auto proxy dir
156*/
aswiftaebf4132008-11-21 00:10:35 +0000157#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
158# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
159#endif
160
161/*
danielk1977b4b47412007-08-17 15:53:36 +0000162** Maximum supported path-length.
163*/
164#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000165
dane88ec182016-01-25 17:04:48 +0000166/*
167** Maximum supported symbolic links
168*/
169#define SQLITE_MAX_SYMLINKS 100
170
drh91eb93c2015-03-03 19:56:20 +0000171/* Always cast the getpid() return type for compatibility with
172** kernel modules in VxWorks. */
173#define osGetpid(X) (pid_t)getpid()
174
drh734c9862008-11-28 15:37:20 +0000175/*
drh734c9862008-11-28 15:37:20 +0000176** Only set the lastErrno if the error code is a real error and not
177** a normal expected return code of SQLITE_BUSY or SQLITE_OK
178*/
179#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
180
drhd91c68f2010-05-14 14:52:25 +0000181/* Forward references */
182typedef struct unixShm unixShm; /* Connection shared memory */
183typedef struct unixShmNode unixShmNode; /* Shared memory instance */
184typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
185typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000186
187/*
dane946c392009-08-22 11:39:46 +0000188** Sometimes, after a file handle is closed by SQLite, the file descriptor
189** cannot be closed immediately. In these cases, instances of the following
190** structure are used to store the file descriptor while waiting for an
191** opportunity to either close or reuse it.
192*/
dane946c392009-08-22 11:39:46 +0000193struct UnixUnusedFd {
194 int fd; /* File descriptor to close */
195 int flags; /* Flags this file descriptor was opened with */
196 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
197};
198
199/*
drh9b35ea62008-11-29 02:20:26 +0000200** The unixFile structure is subclass of sqlite3_file specific to the unix
201** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000202*/
drh054889e2005-11-30 03:20:31 +0000203typedef struct unixFile unixFile;
204struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000205 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000206 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000207 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000208 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000209 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000210 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000211 int lastErrno; /* The unix errno from last I/O error */
212 void *lockingContext; /* Locking style specific state */
213 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000214 const char *zPath; /* Name of the file */
215 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000216 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000217#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000218 int nFetchOut; /* Number of outstanding xFetch refs */
219 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000220 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
221 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000222 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000223#endif
drh537dddf2012-10-26 13:46:24 +0000224 int sectorSize; /* Device sector size */
225 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000226#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000227 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000228#endif
drh7ed97b92010-01-20 13:07:21 +0000229#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000230 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000231#endif
232#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000233 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000234#endif
drhd3d8c042012-05-29 17:02:40 +0000235#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000236 /* The next group of variables are used to track whether or not the
237 ** transaction counter in bytes 24-27 of database files are updated
238 ** whenever any part of the database changes. An assertion fault will
239 ** occur if a file is updated without also updating the transaction
240 ** counter. This test is made to avoid new problems similar to the
241 ** one described by ticket #3584.
242 */
243 unsigned char transCntrChng; /* True if the transaction counter changed */
244 unsigned char dbUpdate; /* True if any part of database file changed */
245 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000246
drh8f941bc2009-01-14 23:03:40 +0000247#endif
danf23da962013-03-23 21:00:41 +0000248
danielk1977967a4a12007-08-20 14:23:44 +0000249#ifdef SQLITE_TEST
250 /* In test mode, increase the size of this structure a bit so that
251 ** it is larger than the struct CrashFile defined in test6.c.
252 */
253 char aPadding[32];
254#endif
drh9cbe6352005-11-29 03:13:21 +0000255};
256
drhb00d8622014-01-01 15:18:36 +0000257/* This variable holds the process id (pid) from when the xRandomness()
258** method was called. If xOpen() is called from a different process id,
259** indicating that a fork() has occurred, the PRNG will be reset.
260*/
drh8cd5b252015-03-02 22:06:43 +0000261static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000262
drh0ccebe72005-06-07 22:22:50 +0000263/*
drha7e61d82011-03-12 17:02:57 +0000264** Allowed values for the unixFile.ctrlFlags bitmask:
265*/
drhf0b190d2011-07-26 16:03:07 +0000266#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
267#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
268#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000269#ifndef SQLITE_DISABLE_DIRSYNC
270# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
271#else
272# define UNIXFILE_DIRSYNC 0x00
273#endif
drhcb15f352011-12-23 01:04:17 +0000274#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000275#define UNIXFILE_DELETE 0x20 /* Delete on close */
276#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
277#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000278
279/*
drh198bf392006-01-06 21:52:49 +0000280** Include code that is common to all os_*.c files
281*/
282#include "os_common.h"
283
284/*
drh0ccebe72005-06-07 22:22:50 +0000285** Define various macros that are missing from some systems.
286*/
drhbbd42a62004-05-22 17:41:58 +0000287#ifndef O_LARGEFILE
288# define O_LARGEFILE 0
289#endif
290#ifdef SQLITE_DISABLE_LFS
291# undef O_LARGEFILE
292# define O_LARGEFILE 0
293#endif
294#ifndef O_NOFOLLOW
295# define O_NOFOLLOW 0
296#endif
297#ifndef O_BINARY
298# define O_BINARY 0
299#endif
300
301/*
drh2b4b5962005-06-15 17:47:55 +0000302** The threadid macro resolves to the thread-id or to 0. Used for
303** testing and debugging only.
304*/
drhd677b3d2007-08-20 22:48:41 +0000305#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000306#define threadid pthread_self()
307#else
308#define threadid 0
309#endif
310
drh99ab3b12011-03-02 15:09:07 +0000311/*
dane6ecd662013-04-01 17:56:59 +0000312** HAVE_MREMAP defaults to true on Linux and false everywhere else.
313*/
314#if !defined(HAVE_MREMAP)
315# if defined(__linux__) && defined(_GNU_SOURCE)
316# define HAVE_MREMAP 1
317# else
318# define HAVE_MREMAP 0
319# endif
320#endif
321
322/*
dan2ee53412014-09-06 16:49:40 +0000323** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
324** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
325*/
326#ifdef __ANDROID__
327# define lseek lseek64
328#endif
329
danefe16972017-07-20 19:49:14 +0000330#define F2FS_IOCTL_MAGIC 0xf5
331#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
332#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
333#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
334#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
335
336
dan2ee53412014-09-06 16:49:40 +0000337/*
drh9a3baf12011-04-25 18:01:27 +0000338** Different Unix systems declare open() in different ways. Same use
339** open(const char*,int,mode_t). Others use open(const char*,int,...).
340** The difference is important when using a pointer to the function.
341**
342** The safest way to deal with the problem is to always use this wrapper
343** which always has the same well-defined interface.
344*/
345static int posixOpen(const char *zFile, int flags, int mode){
346 return open(zFile, flags, mode);
347}
348
drh90315a22011-08-10 01:52:12 +0000349/* Forward reference */
350static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000351static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000352
drh9a3baf12011-04-25 18:01:27 +0000353/*
drh99ab3b12011-03-02 15:09:07 +0000354** Many system calls are accessed through pointer-to-functions so that
355** they may be overridden at runtime to facilitate fault injection during
356** testing and sandboxing. The following array holds the names and pointers
357** to all overrideable system calls.
358*/
359static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000360 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000361 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
362 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000363} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000364 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
365#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000366
drh58ad5802011-03-23 22:02:23 +0000367 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000368#define osClose ((int(*)(int))aSyscall[1].pCurrent)
369
drh58ad5802011-03-23 22:02:23 +0000370 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000371#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
372
drh58ad5802011-03-23 22:02:23 +0000373 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000374#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
375
drh58ad5802011-03-23 22:02:23 +0000376 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000377#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
378
379/*
380** The DJGPP compiler environment looks mostly like Unix, but it
381** lacks the fcntl() system call. So redefine fcntl() to be something
382** that always succeeds. This means that locking does not occur under
383** DJGPP. But it is DOS - what did you expect?
384*/
385#ifdef __DJGPP__
386 { "fstat", 0, 0 },
387#define osFstat(a,b,c) 0
388#else
drh58ad5802011-03-23 22:02:23 +0000389 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000390#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
391#endif
392
drh58ad5802011-03-23 22:02:23 +0000393 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000394#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
395
drh58ad5802011-03-23 22:02:23 +0000396 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000397#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000398
drh58ad5802011-03-23 22:02:23 +0000399 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000400#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
401
drhe89b2912015-03-03 20:42:01 +0000402#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000403 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000404#else
drh58ad5802011-03-23 22:02:23 +0000405 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000406#endif
407#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
408
409#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000410 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000411#else
drh58ad5802011-03-23 22:02:23 +0000412 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000413#endif
drhf9986d92016-04-18 13:09:55 +0000414#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000415
drh58ad5802011-03-23 22:02:23 +0000416 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000417#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
418
drhe89b2912015-03-03 20:42:01 +0000419#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000420 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000421#else
drh58ad5802011-03-23 22:02:23 +0000422 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000423#endif
424#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
425 aSyscall[12].pCurrent)
426
427#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000428 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000429#else
drh58ad5802011-03-23 22:02:23 +0000430 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000431#endif
drhf9986d92016-04-18 13:09:55 +0000432#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000433 aSyscall[13].pCurrent)
434
drh6226ca22015-11-24 15:06:28 +0000435 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000436#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000437
438#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000439 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000440#else
drh58ad5802011-03-23 22:02:23 +0000441 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000442#endif
dan0fd7d862011-03-29 10:04:23 +0000443#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000444
drh036ac7f2011-08-08 23:18:05 +0000445 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
446#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
447
drh90315a22011-08-10 01:52:12 +0000448 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
449#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
450
drh9ef6bc42011-11-04 02:24:02 +0000451 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
452#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
453
454 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
455#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
456
drhe2258a22016-01-12 00:37:55 +0000457#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000458 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000459#else
460 { "fchown", (sqlite3_syscall_ptr)0, 0 },
461#endif
dand3eaebd2012-02-13 08:50:23 +0000462#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000463
drh6226ca22015-11-24 15:06:28 +0000464 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
465#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
466
dan4dd51442013-08-26 14:30:25 +0000467#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000468 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
469#else
470 { "mmap", (sqlite3_syscall_ptr)0, 0 },
471#endif
drh6226ca22015-11-24 15:06:28 +0000472#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000473
drhe4a08f92016-01-08 19:17:30 +0000474#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000475 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000476#else
drha8299922016-01-08 22:31:00 +0000477 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000478#endif
drh6226ca22015-11-24 15:06:28 +0000479#define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000480
drhe4a08f92016-01-08 19:17:30 +0000481#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000482 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
483#else
484 { "mremap", (sqlite3_syscall_ptr)0, 0 },
485#endif
drh6226ca22015-11-24 15:06:28 +0000486#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
487
drh24dbeae2016-01-08 22:18:00 +0000488#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000489 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000490#else
491 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
492#endif
drh6226ca22015-11-24 15:06:28 +0000493#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000494
drhe2258a22016-01-12 00:37:55 +0000495#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000496 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000497#else
498 { "readlink", (sqlite3_syscall_ptr)0, 0 },
499#endif
drh6226ca22015-11-24 15:06:28 +0000500#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000501
danaf1b36b2016-01-25 18:43:05 +0000502#if defined(HAVE_LSTAT)
503 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
504#else
505 { "lstat", (sqlite3_syscall_ptr)0, 0 },
506#endif
dancaf6b152016-01-25 18:05:49 +0000507#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000508
danefe16972017-07-20 19:49:14 +0000509 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
510#define osIoctl ((int(*)(int,int))aSyscall[28].pCurrent)
511
drhe562be52011-03-02 18:01:10 +0000512}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000513
drh6226ca22015-11-24 15:06:28 +0000514
515/*
516** On some systems, calls to fchown() will trigger a message in a security
517** log if they come from non-root processes. So avoid calling fchown() if
518** we are not running as root.
519*/
520static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000521#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000522 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000523#else
524 return 0;
drh6226ca22015-11-24 15:06:28 +0000525#endif
526}
527
drh99ab3b12011-03-02 15:09:07 +0000528/*
529** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000530** "unix" VFSes. Return SQLITE_OK opon successfully updating the
531** system call pointer, or SQLITE_NOTFOUND if there is no configurable
532** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000533*/
534static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000535 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
536 const char *zName, /* Name of system call to override */
537 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000538){
drh58ad5802011-03-23 22:02:23 +0000539 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000540 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000541
542 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000543 if( zName==0 ){
544 /* If no zName is given, restore all system calls to their default
545 ** settings and return NULL
546 */
dan51438a72011-04-02 17:00:47 +0000547 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000548 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
549 if( aSyscall[i].pDefault ){
550 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000551 }
552 }
553 }else{
554 /* If zName is specified, operate on only the one system call
555 ** specified.
556 */
557 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
558 if( strcmp(zName, aSyscall[i].zName)==0 ){
559 if( aSyscall[i].pDefault==0 ){
560 aSyscall[i].pDefault = aSyscall[i].pCurrent;
561 }
drh1df30962011-03-02 19:06:42 +0000562 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000563 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
564 aSyscall[i].pCurrent = pNewFunc;
565 break;
566 }
567 }
568 }
569 return rc;
570}
571
drh1df30962011-03-02 19:06:42 +0000572/*
573** Return the value of a system call. Return NULL if zName is not a
574** recognized system call name. NULL is also returned if the system call
575** is currently undefined.
576*/
drh58ad5802011-03-23 22:02:23 +0000577static sqlite3_syscall_ptr unixGetSystemCall(
578 sqlite3_vfs *pNotUsed,
579 const char *zName
580){
581 unsigned int i;
582
583 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000584 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
585 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
586 }
587 return 0;
588}
589
590/*
591** Return the name of the first system call after zName. If zName==NULL
592** then return the name of the first system call. Return NULL if zName
593** is the last system call or if zName is not the name of a valid
594** system call.
595*/
596static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000597 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000598
599 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000600 if( zName ){
601 for(i=0; i<ArraySize(aSyscall)-1; i++){
602 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000603 }
604 }
dan0fd7d862011-03-29 10:04:23 +0000605 for(i++; i<ArraySize(aSyscall); i++){
606 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000607 }
608 return 0;
609}
610
drhad4f1e52011-03-04 15:43:57 +0000611/*
drh77a3fdc2013-08-30 14:24:12 +0000612** Do not accept any file descriptor less than this value, in order to avoid
613** opening database file using file descriptors that are commonly used for
614** standard input, output, and error.
615*/
616#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
617# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
618#endif
619
620/*
drh8c815d12012-02-13 20:16:37 +0000621** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000622** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000623**
624** If the file creation mode "m" is 0 then set it to the default for
625** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
626** 0644) as modified by the system umask. If m is not 0, then
627** make the file creation mode be exactly m ignoring the umask.
628**
629** The m parameter will be non-zero only when creating -wal, -journal,
630** and -shm files. We want those files to have *exactly* the same
631** permissions as their original database, unadulterated by the umask.
632** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
633** transaction crashes and leaves behind hot journals, then any
634** process that is able to write to the database will also be able to
635** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000636*/
drh8c815d12012-02-13 20:16:37 +0000637static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000638 int fd;
drhe1186ab2013-01-04 20:45:13 +0000639 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000640 while(1){
drh5adc60b2012-04-14 13:25:11 +0000641#if defined(O_CLOEXEC)
642 fd = osOpen(z,f|O_CLOEXEC,m2);
643#else
644 fd = osOpen(z,f,m2);
645#endif
drh5128d002013-08-30 06:20:23 +0000646 if( fd<0 ){
647 if( errno==EINTR ) continue;
648 break;
649 }
drh77a3fdc2013-08-30 14:24:12 +0000650 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000651 osClose(fd);
652 sqlite3_log(SQLITE_WARNING,
653 "attempt to open \"%s\" as file descriptor %d", z, fd);
654 fd = -1;
655 if( osOpen("/dev/null", f, m)<0 ) break;
656 }
drhe1186ab2013-01-04 20:45:13 +0000657 if( fd>=0 ){
658 if( m!=0 ){
659 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000660 if( osFstat(fd, &statbuf)==0
661 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000662 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000663 ){
drhe1186ab2013-01-04 20:45:13 +0000664 osFchmod(fd, m);
665 }
666 }
drh5adc60b2012-04-14 13:25:11 +0000667#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000668 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000669#endif
drhe1186ab2013-01-04 20:45:13 +0000670 }
drh5adc60b2012-04-14 13:25:11 +0000671 return fd;
drhad4f1e52011-03-04 15:43:57 +0000672}
danielk197713adf8a2004-06-03 16:08:41 +0000673
drh107886a2008-11-21 22:21:50 +0000674/*
dan9359c7b2009-08-21 08:29:10 +0000675** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000676** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000677** vxworksFileId objects used by this file, all of which may be
678** shared by multiple threads.
679**
680** Function unixMutexHeld() is used to assert() that the global mutex
681** is held when required. This function is only used as part of assert()
682** statements. e.g.
683**
684** unixEnterMutex()
685** assert( unixMutexHeld() );
686** unixEnterLeave()
drh107886a2008-11-21 22:21:50 +0000687*/
688static void unixEnterMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000689 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000690}
691static void unixLeaveMutex(void){
mistachkin93de6532015-07-03 21:38:09 +0000692 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
drh107886a2008-11-21 22:21:50 +0000693}
dan9359c7b2009-08-21 08:29:10 +0000694#ifdef SQLITE_DEBUG
695static int unixMutexHeld(void) {
mistachkin93de6532015-07-03 21:38:09 +0000696 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
dan9359c7b2009-08-21 08:29:10 +0000697}
698#endif
drh107886a2008-11-21 22:21:50 +0000699
drh734c9862008-11-28 15:37:20 +0000700
mistachkinfb383e92015-04-16 03:24:38 +0000701#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000702/*
703** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000704** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000705** integer lock-type.
706*/
drh308c2a52010-05-14 11:30:18 +0000707static const char *azFileLock(int eFileLock){
708 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000709 case NO_LOCK: return "NONE";
710 case SHARED_LOCK: return "SHARED";
711 case RESERVED_LOCK: return "RESERVED";
712 case PENDING_LOCK: return "PENDING";
713 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000714 }
715 return "ERROR";
716}
717#endif
718
719#ifdef SQLITE_LOCK_TRACE
720/*
721** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000722**
drh734c9862008-11-28 15:37:20 +0000723** This routine is used for troubleshooting locks on multithreaded
724** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
725** command-line option on the compiler. This code is normally
726** turned off.
727*/
728static int lockTrace(int fd, int op, struct flock *p){
729 char *zOpName, *zType;
730 int s;
731 int savedErrno;
732 if( op==F_GETLK ){
733 zOpName = "GETLK";
734 }else if( op==F_SETLK ){
735 zOpName = "SETLK";
736 }else{
drh99ab3b12011-03-02 15:09:07 +0000737 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000738 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
739 return s;
740 }
741 if( p->l_type==F_RDLCK ){
742 zType = "RDLCK";
743 }else if( p->l_type==F_WRLCK ){
744 zType = "WRLCK";
745 }else if( p->l_type==F_UNLCK ){
746 zType = "UNLCK";
747 }else{
748 assert( 0 );
749 }
750 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000751 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000752 savedErrno = errno;
753 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
754 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
755 (int)p->l_pid, s);
756 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
757 struct flock l2;
758 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000759 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000760 if( l2.l_type==F_RDLCK ){
761 zType = "RDLCK";
762 }else if( l2.l_type==F_WRLCK ){
763 zType = "WRLCK";
764 }else if( l2.l_type==F_UNLCK ){
765 zType = "UNLCK";
766 }else{
767 assert( 0 );
768 }
769 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
770 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
771 }
772 errno = savedErrno;
773 return s;
774}
drh99ab3b12011-03-02 15:09:07 +0000775#undef osFcntl
776#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000777#endif /* SQLITE_LOCK_TRACE */
778
drhff812312011-02-23 13:33:46 +0000779/*
780** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000781**
drhe6d41732015-02-21 00:49:00 +0000782** All calls to ftruncate() within this file should be made through
783** this wrapper. On the Android platform, bypassing the logic below
784** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000785*/
drhff812312011-02-23 13:33:46 +0000786static int robust_ftruncate(int h, sqlite3_int64 sz){
787 int rc;
dan2ee53412014-09-06 16:49:40 +0000788#ifdef __ANDROID__
789 /* On Android, ftruncate() always uses 32-bit offsets, even if
790 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000791 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000792 ** such attempts. */
793 if( sz>(sqlite3_int64)0x7FFFFFFF ){
794 rc = SQLITE_OK;
795 }else
796#endif
drh99ab3b12011-03-02 15:09:07 +0000797 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000798 return rc;
799}
drh734c9862008-11-28 15:37:20 +0000800
801/*
802** This routine translates a standard POSIX errno code into something
803** useful to the clients of the sqlite3 functions. Specifically, it is
804** intended to translate a variety of "try again" errors into SQLITE_BUSY
805** and a variety of "please close the file descriptor NOW" errors into
806** SQLITE_IOERR
807**
808** Errors during initialization of locks, or file system support for locks,
809** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
810*/
811static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000812 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
813 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
814 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
815 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000816 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000817 case EACCES:
drh734c9862008-11-28 15:37:20 +0000818 case EAGAIN:
819 case ETIMEDOUT:
820 case EBUSY:
821 case EINTR:
822 case ENOLCK:
823 /* random NFS retry error, unless during file system support
824 * introspection, in which it actually means what it says */
825 return SQLITE_BUSY;
826
drh734c9862008-11-28 15:37:20 +0000827 case EPERM:
828 return SQLITE_PERM;
829
drh734c9862008-11-28 15:37:20 +0000830 default:
831 return sqliteIOErr;
832 }
833}
834
835
drh734c9862008-11-28 15:37:20 +0000836/******************************************************************************
837****************** Begin Unique File ID Utility Used By VxWorks ***************
838**
839** On most versions of unix, we can get a unique ID for a file by concatenating
840** the device number and the inode number. But this does not work on VxWorks.
841** On VxWorks, a unique file id must be based on the canonical filename.
842**
843** A pointer to an instance of the following structure can be used as a
844** unique file ID in VxWorks. Each instance of this structure contains
845** a copy of the canonical filename. There is also a reference count.
846** The structure is reclaimed when the number of pointers to it drops to
847** zero.
848**
849** There are never very many files open at one time and lookups are not
850** a performance-critical path, so it is sufficient to put these
851** structures on a linked list.
852*/
853struct vxworksFileId {
854 struct vxworksFileId *pNext; /* Next in a list of them all */
855 int nRef; /* Number of references to this one */
856 int nName; /* Length of the zCanonicalName[] string */
857 char *zCanonicalName; /* Canonical filename */
858};
859
860#if OS_VXWORKS
861/*
drh9b35ea62008-11-29 02:20:26 +0000862** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000863** variable:
864*/
865static struct vxworksFileId *vxworksFileList = 0;
866
867/*
868** Simplify a filename into its canonical form
869** by making the following changes:
870**
871** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000872** * convert /./ into just /
873** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000874**
875** Changes are made in-place. Return the new name length.
876**
877** The original filename is in z[0..n-1]. Return the number of
878** characters in the simplified name.
879*/
880static int vxworksSimplifyName(char *z, int n){
881 int i, j;
882 while( n>1 && z[n-1]=='/' ){ n--; }
883 for(i=j=0; i<n; i++){
884 if( z[i]=='/' ){
885 if( z[i+1]=='/' ) continue;
886 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
887 i += 1;
888 continue;
889 }
890 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
891 while( j>0 && z[j-1]!='/' ){ j--; }
892 if( j>0 ){ j--; }
893 i += 2;
894 continue;
895 }
896 }
897 z[j++] = z[i];
898 }
899 z[j] = 0;
900 return j;
901}
902
903/*
904** Find a unique file ID for the given absolute pathname. Return
905** a pointer to the vxworksFileId object. This pointer is the unique
906** file ID.
907**
908** The nRef field of the vxworksFileId object is incremented before
909** the object is returned. A new vxworksFileId object is created
910** and added to the global list if necessary.
911**
912** If a memory allocation error occurs, return NULL.
913*/
914static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
915 struct vxworksFileId *pNew; /* search key and new file ID */
916 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
917 int n; /* Length of zAbsoluteName string */
918
919 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000920 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000921 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000922 if( pNew==0 ) return 0;
923 pNew->zCanonicalName = (char*)&pNew[1];
924 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
925 n = vxworksSimplifyName(pNew->zCanonicalName, n);
926
927 /* Search for an existing entry that matching the canonical name.
928 ** If found, increment the reference count and return a pointer to
929 ** the existing file ID.
930 */
931 unixEnterMutex();
932 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
933 if( pCandidate->nName==n
934 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
935 ){
936 sqlite3_free(pNew);
937 pCandidate->nRef++;
938 unixLeaveMutex();
939 return pCandidate;
940 }
941 }
942
943 /* No match was found. We will make a new file ID */
944 pNew->nRef = 1;
945 pNew->nName = n;
946 pNew->pNext = vxworksFileList;
947 vxworksFileList = pNew;
948 unixLeaveMutex();
949 return pNew;
950}
951
952/*
953** Decrement the reference count on a vxworksFileId object. Free
954** the object when the reference count reaches zero.
955*/
956static void vxworksReleaseFileId(struct vxworksFileId *pId){
957 unixEnterMutex();
958 assert( pId->nRef>0 );
959 pId->nRef--;
960 if( pId->nRef==0 ){
961 struct vxworksFileId **pp;
962 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
963 assert( *pp==pId );
964 *pp = pId->pNext;
965 sqlite3_free(pId);
966 }
967 unixLeaveMutex();
968}
969#endif /* OS_VXWORKS */
970/*************** End of Unique File ID Utility Used By VxWorks ****************
971******************************************************************************/
972
973
974/******************************************************************************
975*************************** Posix Advisory Locking ****************************
976**
drh9b35ea62008-11-29 02:20:26 +0000977** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +0000978** section 6.5.2.2 lines 483 through 490 specify that when a process
979** sets or clears a lock, that operation overrides any prior locks set
980** by the same process. It does not explicitly say so, but this implies
981** that it overrides locks set by the same process using a different
982** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +0000983**
984** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +0000985** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
986**
987** Suppose ./file1 and ./file2 are really the same file (because
988** one is a hard or symbolic link to the other) then if you set
989** an exclusive lock on fd1, then try to get an exclusive lock
990** on fd2, it works. I would have expected the second lock to
991** fail since there was already a lock on the file due to fd1.
992** But not so. Since both locks came from the same process, the
993** second overrides the first, even though they were on different
994** file descriptors opened on different file names.
995**
drh734c9862008-11-28 15:37:20 +0000996** This means that we cannot use POSIX locks to synchronize file access
997** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +0000998** to synchronize access for threads in separate processes, but not
999** threads within the same process.
1000**
1001** To work around the problem, SQLite has to manage file locks internally
1002** on its own. Whenever a new database is opened, we have to find the
1003** specific inode of the database file (the inode is determined by the
1004** st_dev and st_ino fields of the stat structure that fstat() fills in)
1005** and check for locks already existing on that inode. When locks are
1006** created or removed, we have to look at our own internal record of the
1007** locks to see if another thread has previously set a lock on that same
1008** inode.
1009**
drh9b35ea62008-11-29 02:20:26 +00001010** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1011** For VxWorks, we have to use the alternative unique ID system based on
1012** canonical filename and implemented in the previous division.)
1013**
danielk1977ad94b582007-08-20 06:44:22 +00001014** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001015** descriptor. It is now a structure that holds the integer file
1016** descriptor and a pointer to a structure that describes the internal
1017** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001018** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001019** point to the same locking structure. The locking structure keeps
1020** a reference count (so we will know when to delete it) and a "cnt"
1021** field that tells us its internal lock status. cnt==0 means the
1022** file is unlocked. cnt==-1 means the file has an exclusive lock.
1023** cnt>0 means there are cnt shared locks on the file.
1024**
1025** Any attempt to lock or unlock a file first checks the locking
1026** structure. The fcntl() system call is only invoked to set a
1027** POSIX lock if the internal lock structure transitions between
1028** a locked and an unlocked state.
1029**
drh734c9862008-11-28 15:37:20 +00001030** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001031**
1032** If you close a file descriptor that points to a file that has locks,
1033** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001034** released. To work around this problem, each unixInodeInfo object
1035** maintains a count of the number of pending locks on tha inode.
1036** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001037** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001038** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001039** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001040** be closed and that list is walked (and cleared) when the last lock
1041** clears.
1042**
drh9b35ea62008-11-29 02:20:26 +00001043** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001044**
drh9b35ea62008-11-29 02:20:26 +00001045** Many older versions of linux use the LinuxThreads library which is
1046** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001047** A cannot be modified or overridden by a different thread B.
1048** Only thread A can modify the lock. Locking behavior is correct
1049** if the appliation uses the newer Native Posix Thread Library (NPTL)
1050** on linux - with NPTL a lock created by thread A can override locks
1051** in thread B. But there is no way to know at compile-time which
1052** threading library is being used. So there is no way to know at
1053** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001054** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001055** current process.
drh5fdae772004-06-29 03:29:00 +00001056**
drh8af6c222010-05-14 12:43:01 +00001057** SQLite used to support LinuxThreads. But support for LinuxThreads
1058** was dropped beginning with version 3.7.0. SQLite will still work with
1059** LinuxThreads provided that (1) there is no more than one connection
1060** per database file in the same process and (2) database connections
1061** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001062*/
1063
1064/*
1065** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001066** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001067*/
1068struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001069 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001070#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001071 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001072#else
drh25ef7f52016-12-05 20:06:45 +00001073 /* We are told that some versions of Android contain a bug that
1074 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1075 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1076 ** To work around this, always allocate 64-bits for the inode number.
1077 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1078 ** but that should not be a big deal. */
1079 /* WAS: ino_t ino; */
1080 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001081#endif
1082};
1083
1084/*
drhbbd42a62004-05-22 17:41:58 +00001085** An instance of the following structure is allocated for each open
drh9b35ea62008-11-29 02:20:26 +00001086** inode. Or, on LinuxThreads, there is one of these structures for
1087** each inode opened by each thread.
drhbbd42a62004-05-22 17:41:58 +00001088**
danielk1977ad94b582007-08-20 06:44:22 +00001089** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001090** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001091** object keeps a count of the number of unixFile pointing to it.
drhbbd42a62004-05-22 17:41:58 +00001092*/
drh8af6c222010-05-14 12:43:01 +00001093struct unixInodeInfo {
1094 struct unixFileId fileId; /* The lookup key */
drh308c2a52010-05-14 11:30:18 +00001095 int nShared; /* Number of SHARED locks held */
drha7e61d82011-03-12 17:02:57 +00001096 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1097 unsigned char bProcessLock; /* An exclusive process lock is held */
drh734c9862008-11-28 15:37:20 +00001098 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001099 unixShmNode *pShmNode; /* Shared memory associated with this inode */
1100 int nLock; /* Number of outstanding file locks */
1101 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
1102 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1103 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001104#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001105 unsigned long long sharedByte; /* for AFP simulated shared lock */
1106#endif
drh6c7d5c52008-11-21 20:32:33 +00001107#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001108 sem_t *pSem; /* Named POSIX semaphore */
1109 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001110#endif
drhbbd42a62004-05-22 17:41:58 +00001111};
1112
drhda0e7682008-07-30 15:27:54 +00001113/*
drh8af6c222010-05-14 12:43:01 +00001114** A lists of all unixInodeInfo objects.
drhbbd42a62004-05-22 17:41:58 +00001115*/
drhd91c68f2010-05-14 14:52:25 +00001116static unixInodeInfo *inodeList = 0;
drh5fdae772004-06-29 03:29:00 +00001117
drh5fdae772004-06-29 03:29:00 +00001118/*
dane18d4952011-02-21 11:46:24 +00001119**
drhaaeaa182015-11-24 15:12:47 +00001120** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001121** unixLogError().
1122**
1123** It is invoked after an error occurs in an OS function and errno has been
1124** set. It logs a message using sqlite3_log() containing the current value of
1125** errno and, if possible, the human-readable equivalent from strerror() or
1126** strerror_r().
1127**
1128** The first argument passed to the macro should be the error code that
1129** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1130** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001131** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001132** if any.
1133*/
drh0e9365c2011-03-02 02:08:13 +00001134#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1135static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001136 int errcode, /* SQLite error code */
1137 const char *zFunc, /* Name of OS function that failed */
1138 const char *zPath, /* File path associated with error */
1139 int iLine /* Source line number where error occurred */
1140){
1141 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001142 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001143
1144 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1145 ** the strerror() function to obtain the human-readable error message
1146 ** equivalent to errno. Otherwise, use strerror_r().
1147 */
1148#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1149 char aErr[80];
1150 memset(aErr, 0, sizeof(aErr));
1151 zErr = aErr;
1152
1153 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001154 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001155 ** returns a pointer to a buffer containing the error message. That pointer
1156 ** may point to aErr[], or it may point to some static storage somewhere.
1157 ** Otherwise, assume that the system provides the POSIX version of
1158 ** strerror_r(), which always writes an error message into aErr[].
1159 **
1160 ** If the code incorrectly assumes that it is the POSIX version that is
1161 ** available, the error message will often be an empty string. Not a
1162 ** huge problem. Incorrectly concluding that the GNU version is available
1163 ** could lead to a segfault though.
1164 */
1165#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1166 zErr =
1167# endif
drh0e9365c2011-03-02 02:08:13 +00001168 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001169
1170#elif SQLITE_THREADSAFE
1171 /* This is a threadsafe build, but strerror_r() is not available. */
1172 zErr = "";
1173#else
1174 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001175 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001176#endif
1177
drh0e9365c2011-03-02 02:08:13 +00001178 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001179 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001180 "os_unix.c:%d: (%d) %s(%s) - %s",
1181 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001182 );
1183
1184 return errcode;
1185}
1186
drh0e9365c2011-03-02 02:08:13 +00001187/*
1188** Close a file descriptor.
1189**
1190** We assume that close() almost always works, since it is only in a
1191** very sick application or on a very sick platform that it might fail.
1192** If it does fail, simply leak the file descriptor, but do log the
1193** error.
1194**
1195** Note that it is not safe to retry close() after EINTR since the
1196** file descriptor might have already been reused by another thread.
1197** So we don't even try to recover from an EINTR. Just log the error
1198** and move on.
1199*/
1200static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001201 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001202 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1203 pFile ? pFile->zPath : 0, lineno);
1204 }
1205}
dane18d4952011-02-21 11:46:24 +00001206
1207/*
drhe6d41732015-02-21 00:49:00 +00001208** Set the pFile->lastErrno. Do this in a subroutine as that provides
1209** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001210*/
1211static void storeLastErrno(unixFile *pFile, int error){
1212 pFile->lastErrno = error;
1213}
1214
1215/*
danb0ac3e32010-06-16 10:55:42 +00001216** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001217*/
drh0e9365c2011-03-02 02:08:13 +00001218static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001219 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001220 UnixUnusedFd *p;
1221 UnixUnusedFd *pNext;
1222 for(p=pInode->pUnused; p; p=pNext){
1223 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001224 robust_close(pFile, p->fd, __LINE__);
1225 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001226 }
drh0e9365c2011-03-02 02:08:13 +00001227 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001228}
1229
1230/*
drh8af6c222010-05-14 12:43:01 +00001231** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001232**
1233** The mutex entered using the unixEnterMutex() function must be held
1234** when this function is called.
drh6c7d5c52008-11-21 20:32:33 +00001235*/
danb0ac3e32010-06-16 10:55:42 +00001236static void releaseInodeInfo(unixFile *pFile){
1237 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001238 assert( unixMutexHeld() );
dan661d71a2011-03-30 19:08:03 +00001239 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001240 pInode->nRef--;
1241 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001242 assert( pInode->pShmNode==0 );
danb0ac3e32010-06-16 10:55:42 +00001243 closePendingFds(pFile);
drh8af6c222010-05-14 12:43:01 +00001244 if( pInode->pPrev ){
1245 assert( pInode->pPrev->pNext==pInode );
1246 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001247 }else{
drh8af6c222010-05-14 12:43:01 +00001248 assert( inodeList==pInode );
1249 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001250 }
drh8af6c222010-05-14 12:43:01 +00001251 if( pInode->pNext ){
1252 assert( pInode->pNext->pPrev==pInode );
1253 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001254 }
drh8af6c222010-05-14 12:43:01 +00001255 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001256 }
drhbbd42a62004-05-22 17:41:58 +00001257 }
1258}
1259
1260/*
drh8af6c222010-05-14 12:43:01 +00001261** Given a file descriptor, locate the unixInodeInfo object that
1262** describes that file descriptor. Create a new one if necessary. The
1263** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001264**
dan9359c7b2009-08-21 08:29:10 +00001265** The mutex entered using the unixEnterMutex() function must be held
1266** when this function is called.
1267**
drh6c7d5c52008-11-21 20:32:33 +00001268** Return an appropriate error code.
1269*/
drh8af6c222010-05-14 12:43:01 +00001270static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001271 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001272 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001273){
1274 int rc; /* System call return code */
1275 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001276 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1277 struct stat statbuf; /* Low-level file information */
1278 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001279
dan9359c7b2009-08-21 08:29:10 +00001280 assert( unixMutexHeld() );
1281
drh6c7d5c52008-11-21 20:32:33 +00001282 /* Get low-level information about the file that we can used to
1283 ** create a unique name for the file.
1284 */
1285 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001286 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001287 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001288 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001289#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001290 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1291#endif
1292 return SQLITE_IOERR;
1293 }
1294
drheb0d74f2009-02-03 15:27:02 +00001295#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001296 /* On OS X on an msdos filesystem, the inode number is reported
1297 ** incorrectly for zero-size files. See ticket #3260. To work
1298 ** around this problem (we consider it a bug in OS X, not SQLite)
1299 ** we always increase the file size to 1 by writing a single byte
1300 ** prior to accessing the inode number. The one byte written is
1301 ** an ASCII 'S' character which also happens to be the first byte
1302 ** in the header of every SQLite database. In this way, if there
1303 ** is a race condition such that another thread has already populated
1304 ** the first page of the database, no damage is done.
1305 */
drh7ed97b92010-01-20 13:07:21 +00001306 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001307 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001308 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001309 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001310 return SQLITE_IOERR;
1311 }
drh99ab3b12011-03-02 15:09:07 +00001312 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001313 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001314 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001315 return SQLITE_IOERR;
1316 }
1317 }
drheb0d74f2009-02-03 15:27:02 +00001318#endif
drh6c7d5c52008-11-21 20:32:33 +00001319
drh8af6c222010-05-14 12:43:01 +00001320 memset(&fileId, 0, sizeof(fileId));
1321 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001322#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001323 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001324#else
drh25ef7f52016-12-05 20:06:45 +00001325 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001326#endif
drh8af6c222010-05-14 12:43:01 +00001327 pInode = inodeList;
1328 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1329 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001330 }
drh8af6c222010-05-14 12:43:01 +00001331 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001332 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001333 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001334 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001335 }
drh8af6c222010-05-14 12:43:01 +00001336 memset(pInode, 0, sizeof(*pInode));
1337 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1338 pInode->nRef = 1;
1339 pInode->pNext = inodeList;
1340 pInode->pPrev = 0;
1341 if( inodeList ) inodeList->pPrev = pInode;
1342 inodeList = pInode;
1343 }else{
1344 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001345 }
drh8af6c222010-05-14 12:43:01 +00001346 *ppInode = pInode;
1347 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001348}
drh6c7d5c52008-11-21 20:32:33 +00001349
drhb959a012013-12-07 12:29:22 +00001350/*
1351** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1352*/
1353static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001354#if OS_VXWORKS
1355 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1356#else
drhb959a012013-12-07 12:29:22 +00001357 struct stat buf;
1358 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001359 (osStat(pFile->zPath, &buf)!=0
1360 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001361#endif
drhb959a012013-12-07 12:29:22 +00001362}
1363
aswift5b1a2562008-08-22 00:22:35 +00001364
1365/*
drhfbc7e882013-04-11 01:16:15 +00001366** Check a unixFile that is a database. Verify the following:
1367**
1368** (1) There is exactly one hard link on the file
1369** (2) The file is not a symbolic link
1370** (3) The file has not been renamed or unlinked
1371**
1372** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1373*/
1374static void verifyDbFile(unixFile *pFile){
1375 struct stat buf;
1376 int rc;
drh86151e82015-12-08 14:37:16 +00001377
1378 /* These verifications occurs for the main database only */
1379 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1380
drhfbc7e882013-04-11 01:16:15 +00001381 rc = osFstat(pFile->h, &buf);
1382 if( rc!=0 ){
1383 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001384 return;
1385 }
drh6369bc32016-03-21 16:06:42 +00001386 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001387 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001388 return;
1389 }
1390 if( buf.st_nlink>1 ){
1391 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001392 return;
1393 }
drhb959a012013-12-07 12:29:22 +00001394 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001395 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001396 return;
1397 }
1398}
1399
1400
1401/*
danielk197713adf8a2004-06-03 16:08:41 +00001402** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001403** file by this or any other process. If such a lock is held, set *pResOut
1404** to a non-zero value otherwise *pResOut is set to zero. The return value
1405** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001406*/
danielk1977861f7452008-06-05 11:39:11 +00001407static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001408 int rc = SQLITE_OK;
1409 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001410 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001411
danielk1977861f7452008-06-05 11:39:11 +00001412 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1413
drh054889e2005-11-30 03:20:31 +00001414 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001415 assert( pFile->eFileLock<=SHARED_LOCK );
drh8af6c222010-05-14 12:43:01 +00001416 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
danielk197713adf8a2004-06-03 16:08:41 +00001417
1418 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001419 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001420 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001421 }
1422
drh2ac3ee92004-06-07 16:27:46 +00001423 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001424 */
danielk197709480a92009-02-09 05:32:32 +00001425#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001426 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001427 struct flock lock;
1428 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001429 lock.l_start = RESERVED_BYTE;
1430 lock.l_len = 1;
1431 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001432 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1433 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001434 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001435 } else if( lock.l_type!=F_UNLCK ){
1436 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001437 }
1438 }
danielk197709480a92009-02-09 05:32:32 +00001439#endif
danielk197713adf8a2004-06-03 16:08:41 +00001440
drh6c7d5c52008-11-21 20:32:33 +00001441 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001442 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001443
aswift5b1a2562008-08-22 00:22:35 +00001444 *pResOut = reserved;
1445 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001446}
1447
1448/*
drha7e61d82011-03-12 17:02:57 +00001449** Attempt to set a system-lock on the file pFile. The lock is
1450** described by pLock.
1451**
drh77197112011-03-15 19:08:48 +00001452** If the pFile was opened read/write from unix-excl, then the only lock
1453** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001454** the first time any lock is attempted. All subsequent system locking
1455** operations become no-ops. Locking operations still happen internally,
1456** in order to coordinate access between separate database connections
1457** within this process, but all of that is handled in memory and the
1458** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001459**
1460** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1461** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1462** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001463**
1464** Zero is returned if the call completes successfully, or -1 if a call
1465** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001466*/
1467static int unixFileLock(unixFile *pFile, struct flock *pLock){
1468 int rc;
drh3cb93392011-03-12 18:10:44 +00001469 unixInodeInfo *pInode = pFile->pInode;
drha7e61d82011-03-12 17:02:57 +00001470 assert( unixMutexHeld() );
drh3cb93392011-03-12 18:10:44 +00001471 assert( pInode!=0 );
drh50358ad2015-12-02 01:04:33 +00001472 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001473 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001474 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001475 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001476 lock.l_whence = SEEK_SET;
1477 lock.l_start = SHARED_FIRST;
1478 lock.l_len = SHARED_SIZE;
1479 lock.l_type = F_WRLCK;
1480 rc = osFcntl(pFile->h, F_SETLK, &lock);
1481 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001482 pInode->bProcessLock = 1;
1483 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001484 }else{
1485 rc = 0;
1486 }
1487 }else{
1488 rc = osFcntl(pFile->h, F_SETLK, pLock);
1489 }
1490 return rc;
1491}
1492
1493/*
drh308c2a52010-05-14 11:30:18 +00001494** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001495** of the following:
1496**
drh2ac3ee92004-06-07 16:27:46 +00001497** (1) SHARED_LOCK
1498** (2) RESERVED_LOCK
1499** (3) PENDING_LOCK
1500** (4) EXCLUSIVE_LOCK
1501**
drhb3e04342004-06-08 00:47:47 +00001502** Sometimes when requesting one lock state, additional lock states
1503** are inserted in between. The locking might fail on one of the later
1504** transitions leaving the lock state different from what it started but
1505** still short of its goal. The following chart shows the allowed
1506** transitions and the inserted intermediate states:
1507**
1508** UNLOCKED -> SHARED
1509** SHARED -> RESERVED
1510** SHARED -> (PENDING) -> EXCLUSIVE
1511** RESERVED -> (PENDING) -> EXCLUSIVE
1512** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001513**
drha6abd042004-06-09 17:37:22 +00001514** This routine will only increase a lock. Use the sqlite3OsUnlock()
1515** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001516*/
drh308c2a52010-05-14 11:30:18 +00001517static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001518 /* The following describes the implementation of the various locks and
1519 ** lock transitions in terms of the POSIX advisory shared and exclusive
1520 ** lock primitives (called read-locks and write-locks below, to avoid
1521 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001522 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001523 ** accessing the same database file, in case that is ever required.
1524 **
1525 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1526 ** byte', each single bytes at well known offsets, and the 'shared byte
1527 ** range', a range of 510 bytes at a well known offset.
1528 **
1529 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001530 ** byte'. If this is successful, 'shared byte range' is read-locked
1531 ** and the lock on the 'pending byte' released. (Legacy note: When
1532 ** SQLite was first developed, Windows95 systems were still very common,
1533 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1534 ** single randomly selected by from the 'shared byte range' is locked.
1535 ** Windows95 is now pretty much extinct, but this work-around for the
1536 ** lack of shared-locks on Windows95 lives on, for backwards
1537 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001538 **
danielk197790ba3bd2004-06-25 08:32:25 +00001539 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1540 ** A RESERVED lock is implemented by grabbing a write-lock on the
1541 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001542 **
1543 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001544 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1545 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1546 ** obtained, but existing SHARED locks are allowed to persist. A process
1547 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1548 ** This property is used by the algorithm for rolling back a journal file
1549 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001550 **
danielk197790ba3bd2004-06-25 08:32:25 +00001551 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1552 ** implemented by obtaining a write-lock on the entire 'shared byte
1553 ** range'. Since all other locks require a read-lock on one of the bytes
1554 ** within this range, this ensures that no other locks are held on the
1555 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001556 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001557 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001558 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001559 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001560 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001561 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001562
drh054889e2005-11-30 03:20:31 +00001563 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001564 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1565 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001566 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001567 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001568
1569 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001570 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001571 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001572 */
drh308c2a52010-05-14 11:30:18 +00001573 if( pFile->eFileLock>=eFileLock ){
1574 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1575 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001576 return SQLITE_OK;
1577 }
1578
drh0c2694b2009-09-03 16:23:44 +00001579 /* Make sure the locking sequence is correct.
1580 ** (1) We never move from unlocked to anything higher than shared lock.
1581 ** (2) SQLite never explicitly requests a pendig lock.
1582 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001583 */
drh308c2a52010-05-14 11:30:18 +00001584 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1585 assert( eFileLock!=PENDING_LOCK );
1586 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001587
drh8af6c222010-05-14 12:43:01 +00001588 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001589 */
drh6c7d5c52008-11-21 20:32:33 +00001590 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001591 pInode = pFile->pInode;
drh029b44b2006-01-15 00:13:15 +00001592
danielk1977ad94b582007-08-20 06:44:22 +00001593 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001594 ** handle that precludes the requested lock, return BUSY.
1595 */
drh8af6c222010-05-14 12:43:01 +00001596 if( (pFile->eFileLock!=pInode->eFileLock &&
1597 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001598 ){
1599 rc = SQLITE_BUSY;
1600 goto end_lock;
1601 }
1602
1603 /* If a SHARED lock is requested, and some thread using this PID already
1604 ** has a SHARED or RESERVED lock, then increment reference counts and
1605 ** return SQLITE_OK.
1606 */
drh308c2a52010-05-14 11:30:18 +00001607 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001608 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001609 assert( eFileLock==SHARED_LOCK );
1610 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001611 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001612 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001613 pInode->nShared++;
1614 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001615 goto end_lock;
1616 }
1617
danielk19779a1d0ab2004-06-01 14:09:28 +00001618
drh3cde3bb2004-06-12 02:17:14 +00001619 /* A PENDING lock is needed before acquiring a SHARED lock and before
1620 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1621 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001622 */
drh0c2694b2009-09-03 16:23:44 +00001623 lock.l_len = 1L;
1624 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001625 if( eFileLock==SHARED_LOCK
1626 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001627 ){
drh308c2a52010-05-14 11:30:18 +00001628 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001629 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001630 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001631 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001632 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001633 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001634 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001635 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001636 goto end_lock;
1637 }
drh3cde3bb2004-06-12 02:17:14 +00001638 }
1639
1640
1641 /* If control gets to this point, then actually go ahead and make
1642 ** operating system calls for the specified lock.
1643 */
drh308c2a52010-05-14 11:30:18 +00001644 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001645 assert( pInode->nShared==0 );
1646 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001647 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001648
drh2ac3ee92004-06-07 16:27:46 +00001649 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001650 lock.l_start = SHARED_FIRST;
1651 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001652 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001653 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001654 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001655 }
dan661d71a2011-03-30 19:08:03 +00001656
drh2ac3ee92004-06-07 16:27:46 +00001657 /* Drop the temporary PENDING lock */
1658 lock.l_start = PENDING_BYTE;
1659 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001660 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001661 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1662 /* This could happen with a network mount */
1663 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001664 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001665 }
dan661d71a2011-03-30 19:08:03 +00001666
1667 if( rc ){
1668 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001669 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001670 }
dan661d71a2011-03-30 19:08:03 +00001671 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001672 }else{
drh308c2a52010-05-14 11:30:18 +00001673 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001674 pInode->nLock++;
1675 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001676 }
drh8af6c222010-05-14 12:43:01 +00001677 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001678 /* We are trying for an exclusive lock but another thread in this
1679 ** same process is still holding a shared lock. */
1680 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001681 }else{
drh3cde3bb2004-06-12 02:17:14 +00001682 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001683 ** assumed that there is a SHARED or greater lock on the file
1684 ** already.
1685 */
drh308c2a52010-05-14 11:30:18 +00001686 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001687 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001688
1689 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1690 if( eFileLock==RESERVED_LOCK ){
1691 lock.l_start = RESERVED_BYTE;
1692 lock.l_len = 1L;
1693 }else{
1694 lock.l_start = SHARED_FIRST;
1695 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001696 }
dan661d71a2011-03-30 19:08:03 +00001697
1698 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001699 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001700 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001701 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001702 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001703 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001704 }
drhbbd42a62004-05-22 17:41:58 +00001705 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001706
drh8f941bc2009-01-14 23:03:40 +00001707
drhd3d8c042012-05-29 17:02:40 +00001708#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001709 /* Set up the transaction-counter change checking flags when
1710 ** transitioning from a SHARED to a RESERVED lock. The change
1711 ** from SHARED to RESERVED marks the beginning of a normal
1712 ** write operation (not a hot journal rollback).
1713 */
1714 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001715 && pFile->eFileLock<=SHARED_LOCK
1716 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001717 ){
1718 pFile->transCntrChng = 0;
1719 pFile->dbUpdate = 0;
1720 pFile->inNormalWrite = 1;
1721 }
1722#endif
1723
1724
danielk1977ecb2a962004-06-02 06:30:16 +00001725 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001726 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001727 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001728 }else if( eFileLock==EXCLUSIVE_LOCK ){
1729 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001730 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001731 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001732
1733end_lock:
drh6c7d5c52008-11-21 20:32:33 +00001734 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001735 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1736 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001737 return rc;
1738}
1739
1740/*
dan08da86a2009-08-21 17:18:03 +00001741** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001742** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001743*/
1744static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001745 unixInodeInfo *pInode = pFile->pInode;
dane946c392009-08-22 11:39:46 +00001746 UnixUnusedFd *p = pFile->pUnused;
drh8af6c222010-05-14 12:43:01 +00001747 p->pNext = pInode->pUnused;
1748 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001749 pFile->h = -1;
1750 pFile->pUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001751}
1752
1753/*
drh308c2a52010-05-14 11:30:18 +00001754** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001755** must be either NO_LOCK or SHARED_LOCK.
1756**
1757** If the locking level of the file descriptor is already at or below
1758** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001759**
1760** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1761** the byte range is divided into 2 parts and the first part is unlocked then
1762** set to a read lock, then the other part is simply unlocked. This works
1763** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1764** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001765*/
drha7e61d82011-03-12 17:02:57 +00001766static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001767 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001768 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001769 struct flock lock;
1770 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001771
drh054889e2005-11-30 03:20:31 +00001772 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001773 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001774 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001775 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001776
drh308c2a52010-05-14 11:30:18 +00001777 assert( eFileLock<=SHARED_LOCK );
1778 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001779 return SQLITE_OK;
1780 }
drh6c7d5c52008-11-21 20:32:33 +00001781 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00001782 pInode = pFile->pInode;
1783 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001784 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001785 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001786
drhd3d8c042012-05-29 17:02:40 +00001787#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001788 /* When reducing a lock such that other processes can start
1789 ** reading the database file again, make sure that the
1790 ** transaction counter was updated if any part of the database
1791 ** file changed. If the transaction counter is not updated,
1792 ** other connections to the same file might not realize that
1793 ** the file has changed and hence might not know to flush their
1794 ** cache. The use of a stale cache can lead to database corruption.
1795 */
drh8f941bc2009-01-14 23:03:40 +00001796 pFile->inNormalWrite = 0;
1797#endif
1798
drh7ed97b92010-01-20 13:07:21 +00001799 /* downgrading to a shared lock on NFS involves clearing the write lock
1800 ** before establishing the readlock - to avoid a race condition we downgrade
1801 ** the lock in 2 blocks, so that part of the range will be covered by a
1802 ** write lock until the rest is covered by a read lock:
1803 ** 1: [WWWWW]
1804 ** 2: [....W]
1805 ** 3: [RRRRW]
1806 ** 4: [RRRR.]
1807 */
drh308c2a52010-05-14 11:30:18 +00001808 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001809#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001810 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001811 assert( handleNFSUnlock==0 );
1812#endif
1813#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001814 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001815 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001816 off_t divSize = SHARED_SIZE - 1;
1817
1818 lock.l_type = F_UNLCK;
1819 lock.l_whence = SEEK_SET;
1820 lock.l_start = SHARED_FIRST;
1821 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +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;
aswift5b1a2562008-08-22 00:22:35 +00001827 }
drh7ed97b92010-01-20 13:07:21 +00001828 lock.l_type = F_RDLCK;
1829 lock.l_whence = SEEK_SET;
1830 lock.l_start = SHARED_FIRST;
1831 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001832 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001833 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001834 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1835 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001836 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001837 }
1838 goto end_unlock;
1839 }
1840 lock.l_type = F_UNLCK;
1841 lock.l_whence = SEEK_SET;
1842 lock.l_start = SHARED_FIRST+divSize;
1843 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001844 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001845 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001846 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001847 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001848 goto end_unlock;
1849 }
drh30f776f2011-02-25 03:25:07 +00001850 }else
1851#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1852 {
drh7ed97b92010-01-20 13:07:21 +00001853 lock.l_type = F_RDLCK;
1854 lock.l_whence = SEEK_SET;
1855 lock.l_start = SHARED_FIRST;
1856 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001857 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001858 /* In theory, the call to unixFileLock() cannot fail because another
1859 ** process is holding an incompatible lock. If it does, this
1860 ** indicates that the other process is not following the locking
1861 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1862 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1863 ** an assert to fail). */
1864 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001865 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001866 goto end_unlock;
1867 }
drh9c105bb2004-10-02 20:38:28 +00001868 }
1869 }
drhbbd42a62004-05-22 17:41:58 +00001870 lock.l_type = F_UNLCK;
1871 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001872 lock.l_start = PENDING_BYTE;
1873 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001874 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001875 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001876 }else{
danea83bc62011-04-01 11:56:32 +00001877 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001878 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001879 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00001880 }
drhbbd42a62004-05-22 17:41:58 +00001881 }
drh308c2a52010-05-14 11:30:18 +00001882 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00001883 /* Decrement the shared lock counter. Release the lock using an
1884 ** OS call only when all threads in this same process have released
1885 ** the lock.
1886 */
drh8af6c222010-05-14 12:43:01 +00001887 pInode->nShared--;
1888 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00001889 lock.l_type = F_UNLCK;
1890 lock.l_whence = SEEK_SET;
1891 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00001892 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001893 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001894 }else{
danea83bc62011-04-01 11:56:32 +00001895 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001896 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00001897 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00001898 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001899 }
drha6abd042004-06-09 17:37:22 +00001900 }
1901
drhbbd42a62004-05-22 17:41:58 +00001902 /* Decrement the count of locks against this same file. When the
1903 ** count reaches zero, close any other file descriptors whose close
1904 ** was deferred because of outstanding locks.
1905 */
drh8af6c222010-05-14 12:43:01 +00001906 pInode->nLock--;
1907 assert( pInode->nLock>=0 );
1908 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00001909 closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00001910 }
1911 }
drhf2f105d2012-08-20 15:53:54 +00001912
aswift5b1a2562008-08-22 00:22:35 +00001913end_unlock:
drh6c7d5c52008-11-21 20:32:33 +00001914 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00001915 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drh9c105bb2004-10-02 20:38:28 +00001916 return rc;
drhbbd42a62004-05-22 17:41:58 +00001917}
1918
1919/*
drh308c2a52010-05-14 11:30:18 +00001920** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00001921** must be either NO_LOCK or SHARED_LOCK.
1922**
1923** If the locking level of the file descriptor is already at or below
1924** the requested locking level, this routine is a no-op.
1925*/
drh308c2a52010-05-14 11:30:18 +00001926static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00001927#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00001928 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00001929#endif
drha7e61d82011-03-12 17:02:57 +00001930 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00001931}
1932
mistachkine98844f2013-08-24 00:59:24 +00001933#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001934static int unixMapfile(unixFile *pFd, i64 nByte);
1935static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00001936#endif
danf23da962013-03-23 21:00:41 +00001937
drh7ed97b92010-01-20 13:07:21 +00001938/*
danielk1977e339d652008-06-28 11:23:00 +00001939** This function performs the parts of the "close file" operation
1940** common to all locking schemes. It closes the directory and file
1941** handles, if they are valid, and sets all fields of the unixFile
1942** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00001943**
1944** It is *not* necessary to hold the mutex when this routine is called,
1945** even on VxWorks. A mutex will be acquired on VxWorks by the
1946** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00001947*/
1948static int closeUnixFile(sqlite3_file *id){
1949 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00001950#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00001951 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00001952#endif
dan661d71a2011-03-30 19:08:03 +00001953 if( pFile->h>=0 ){
1954 robust_close(pFile, pFile->h, __LINE__);
1955 pFile->h = -1;
1956 }
1957#if OS_VXWORKS
1958 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00001959 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00001960 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00001961 }
1962 vxworksReleaseFileId(pFile->pId);
1963 pFile->pId = 0;
1964 }
1965#endif
drh0bdbc902014-06-16 18:35:06 +00001966#ifdef SQLITE_UNLINK_AFTER_CLOSE
1967 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
1968 osUnlink(pFile->zPath);
1969 sqlite3_free(*(char**)&pFile->zPath);
1970 pFile->zPath = 0;
1971 }
1972#endif
dan661d71a2011-03-30 19:08:03 +00001973 OSTRACE(("CLOSE %-3d\n", pFile->h));
1974 OpenCounter(-1);
1975 sqlite3_free(pFile->pUnused);
1976 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00001977 return SQLITE_OK;
1978}
1979
1980/*
danielk1977e3026632004-06-22 11:29:02 +00001981** Close a file.
1982*/
danielk197762079062007-08-15 17:08:46 +00001983static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00001984 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00001985 unixFile *pFile = (unixFile *)id;
drhfbc7e882013-04-11 01:16:15 +00001986 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00001987 unixUnlock(id, NO_LOCK);
1988 unixEnterMutex();
1989
1990 /* unixFile.pInode is always valid here. Otherwise, a different close
1991 ** routine (e.g. nolockClose()) would be called instead.
1992 */
1993 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
1994 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
1995 /* If there are outstanding locks, do not actually close the file just
1996 ** yet because that would clear those locks. Instead, add the file
1997 ** descriptor to pInode->pUnused list. It will be automatically closed
1998 ** when the last lock is cleared.
1999 */
2000 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002001 }
dan661d71a2011-03-30 19:08:03 +00002002 releaseInodeInfo(pFile);
2003 rc = closeUnixFile(id);
2004 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002005 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002006}
2007
drh734c9862008-11-28 15:37:20 +00002008/************** End of the posix advisory lock implementation *****************
2009******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002010
drh734c9862008-11-28 15:37:20 +00002011/******************************************************************************
2012****************************** No-op Locking **********************************
2013**
2014** Of the various locking implementations available, this is by far the
2015** simplest: locking is ignored. No attempt is made to lock the database
2016** file for reading or writing.
2017**
2018** This locking mode is appropriate for use on read-only databases
2019** (ex: databases that are burned into CD-ROM, for example.) It can
2020** also be used if the application employs some external mechanism to
2021** prevent simultaneous access of the same database by two or more
2022** database connections. But there is a serious risk of database
2023** corruption if this locking mode is used in situations where multiple
2024** database connections are accessing the same database file at the same
2025** time and one or more of those connections are writing.
2026*/
drhbfe66312006-10-03 17:40:40 +00002027
drh734c9862008-11-28 15:37:20 +00002028static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2029 UNUSED_PARAMETER(NotUsed);
2030 *pResOut = 0;
2031 return SQLITE_OK;
2032}
drh734c9862008-11-28 15:37:20 +00002033static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2034 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2035 return SQLITE_OK;
2036}
drh734c9862008-11-28 15:37:20 +00002037static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2038 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2039 return SQLITE_OK;
2040}
2041
2042/*
drh9b35ea62008-11-29 02:20:26 +00002043** Close the file.
drh734c9862008-11-28 15:37:20 +00002044*/
2045static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002046 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002047}
2048
2049/******************* End of the no-op lock implementation *********************
2050******************************************************************************/
2051
2052/******************************************************************************
2053************************* Begin dot-file Locking ******************************
2054**
mistachkin48864df2013-03-21 21:20:32 +00002055** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002056** files (really a directory) to control access to the database. This works
2057** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002058**
2059** (1) There is zero concurrency. A single reader blocks all other
2060** connections from reading or writing the database.
2061**
2062** (2) An application crash or power loss can leave stale lock files
2063** sitting around that need to be cleared manually.
2064**
2065** Nevertheless, a dotlock is an appropriate locking mode for use if no
2066** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002067**
drh9ef6bc42011-11-04 02:24:02 +00002068** Dotfile locking works by creating a subdirectory in the same directory as
2069** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002070** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002071** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002072*/
2073
2074/*
2075** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002076** lock directory.
drh734c9862008-11-28 15:37:20 +00002077*/
2078#define DOTLOCK_SUFFIX ".lock"
2079
drh7708e972008-11-29 00:56:52 +00002080/*
2081** This routine checks if there is a RESERVED lock held on the specified
2082** file by this or any other process. If such a lock is held, set *pResOut
2083** to a non-zero value otherwise *pResOut is set to zero. The return value
2084** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2085**
2086** In dotfile locking, either a lock exists or it does not. So in this
2087** variation of CheckReservedLock(), *pResOut is set to true if any lock
2088** is held on the file and false if the file is unlocked.
2089*/
drh734c9862008-11-28 15:37:20 +00002090static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2091 int rc = SQLITE_OK;
2092 int reserved = 0;
2093 unixFile *pFile = (unixFile*)id;
2094
2095 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2096
2097 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002098 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002099 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002100 *pResOut = reserved;
2101 return rc;
2102}
2103
drh7708e972008-11-29 00:56:52 +00002104/*
drh308c2a52010-05-14 11:30:18 +00002105** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002106** of the following:
2107**
2108** (1) SHARED_LOCK
2109** (2) RESERVED_LOCK
2110** (3) PENDING_LOCK
2111** (4) EXCLUSIVE_LOCK
2112**
2113** Sometimes when requesting one lock state, additional lock states
2114** are inserted in between. The locking might fail on one of the later
2115** transitions leaving the lock state different from what it started but
2116** still short of its goal. The following chart shows the allowed
2117** transitions and the inserted intermediate states:
2118**
2119** UNLOCKED -> SHARED
2120** SHARED -> RESERVED
2121** SHARED -> (PENDING) -> EXCLUSIVE
2122** RESERVED -> (PENDING) -> EXCLUSIVE
2123** PENDING -> EXCLUSIVE
2124**
2125** This routine will only increase a lock. Use the sqlite3OsUnlock()
2126** routine to lower a locking level.
2127**
2128** With dotfile locking, we really only support state (4): EXCLUSIVE.
2129** But we track the other locking levels internally.
2130*/
drh308c2a52010-05-14 11:30:18 +00002131static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002132 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002133 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002134 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002135
drh7708e972008-11-29 00:56:52 +00002136
2137 /* If we have any lock, then the lock file already exists. All we have
2138 ** to do is adjust our internal record of the lock level.
2139 */
drh308c2a52010-05-14 11:30:18 +00002140 if( pFile->eFileLock > NO_LOCK ){
2141 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002142 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002143#ifdef HAVE_UTIME
2144 utime(zLockFile, NULL);
2145#else
drh734c9862008-11-28 15:37:20 +00002146 utimes(zLockFile, NULL);
2147#endif
drh7708e972008-11-29 00:56:52 +00002148 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002149 }
2150
2151 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002152 rc = osMkdir(zLockFile, 0777);
2153 if( rc<0 ){
2154 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002155 int tErrno = errno;
2156 if( EEXIST == tErrno ){
2157 rc = SQLITE_BUSY;
2158 } else {
2159 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002160 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002161 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002162 }
2163 }
drh7708e972008-11-29 00:56:52 +00002164 return rc;
drh734c9862008-11-28 15:37:20 +00002165 }
drh734c9862008-11-28 15:37:20 +00002166
2167 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002168 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002169 return rc;
2170}
2171
drh7708e972008-11-29 00:56:52 +00002172/*
drh308c2a52010-05-14 11:30:18 +00002173** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002174** must be either NO_LOCK or SHARED_LOCK.
2175**
2176** If the locking level of the file descriptor is already at or below
2177** the requested locking level, this routine is a no-op.
2178**
2179** When the locking level reaches NO_LOCK, delete the lock file.
2180*/
drh308c2a52010-05-14 11:30:18 +00002181static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002182 unixFile *pFile = (unixFile*)id;
2183 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002184 int rc;
drh734c9862008-11-28 15:37:20 +00002185
2186 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002187 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002188 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002189 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002190
2191 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002192 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002193 return SQLITE_OK;
2194 }
drh7708e972008-11-29 00:56:52 +00002195
2196 /* To downgrade to shared, simply update our internal notion of the
2197 ** lock state. No need to mess with the file on disk.
2198 */
drh308c2a52010-05-14 11:30:18 +00002199 if( eFileLock==SHARED_LOCK ){
2200 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002201 return SQLITE_OK;
2202 }
2203
drh7708e972008-11-29 00:56:52 +00002204 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002205 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002206 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002207 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002208 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002209 if( tErrno==ENOENT ){
2210 rc = SQLITE_OK;
2211 }else{
danea83bc62011-04-01 11:56:32 +00002212 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002213 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002214 }
2215 return rc;
2216 }
drh308c2a52010-05-14 11:30:18 +00002217 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002218 return SQLITE_OK;
2219}
2220
2221/*
drh9b35ea62008-11-29 02:20:26 +00002222** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002223*/
2224static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002225 unixFile *pFile = (unixFile*)id;
2226 assert( id!=0 );
2227 dotlockUnlock(id, NO_LOCK);
2228 sqlite3_free(pFile->lockingContext);
2229 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002230}
2231/****************** End of the dot-file lock implementation *******************
2232******************************************************************************/
2233
2234/******************************************************************************
2235************************** Begin flock Locking ********************************
2236**
2237** Use the flock() system call to do file locking.
2238**
drh6b9d6dd2008-12-03 19:34:47 +00002239** flock() locking is like dot-file locking in that the various
2240** fine-grain locking levels supported by SQLite are collapsed into
2241** a single exclusive lock. In other words, SHARED, RESERVED, and
2242** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2243** still works when you do this, but concurrency is reduced since
2244** only a single process can be reading the database at a time.
2245**
drhe89b2912015-03-03 20:42:01 +00002246** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002247*/
drhe89b2912015-03-03 20:42:01 +00002248#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002249
drh6b9d6dd2008-12-03 19:34:47 +00002250/*
drhff812312011-02-23 13:33:46 +00002251** Retry flock() calls that fail with EINTR
2252*/
2253#ifdef EINTR
2254static int robust_flock(int fd, int op){
2255 int rc;
2256 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2257 return rc;
2258}
2259#else
drh5c819272011-02-23 14:00:12 +00002260# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002261#endif
2262
2263
2264/*
drh6b9d6dd2008-12-03 19:34:47 +00002265** This routine checks if there is a RESERVED lock held on the specified
2266** file by this or any other process. If such a lock is held, set *pResOut
2267** to a non-zero value otherwise *pResOut is set to zero. The return value
2268** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2269*/
drh734c9862008-11-28 15:37:20 +00002270static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2271 int rc = SQLITE_OK;
2272 int reserved = 0;
2273 unixFile *pFile = (unixFile*)id;
2274
2275 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2276
2277 assert( pFile );
2278
2279 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002280 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002281 reserved = 1;
2282 }
2283
2284 /* Otherwise see if some other process holds it. */
2285 if( !reserved ){
2286 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002287 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002288 if( !lrc ){
2289 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002290 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002291 if ( lrc ) {
2292 int tErrno = errno;
2293 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002294 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002295 storeLastErrno(pFile, tErrno);
2296 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002297 }
2298 } else {
2299 int tErrno = errno;
2300 reserved = 1;
2301 /* someone else might have it reserved */
2302 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2303 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002304 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002305 rc = lrc;
2306 }
2307 }
2308 }
drh308c2a52010-05-14 11:30:18 +00002309 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002310
2311#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2312 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2313 rc = SQLITE_OK;
2314 reserved=1;
2315 }
2316#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2317 *pResOut = reserved;
2318 return rc;
2319}
2320
drh6b9d6dd2008-12-03 19:34:47 +00002321/*
drh308c2a52010-05-14 11:30:18 +00002322** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002323** of the following:
2324**
2325** (1) SHARED_LOCK
2326** (2) RESERVED_LOCK
2327** (3) PENDING_LOCK
2328** (4) EXCLUSIVE_LOCK
2329**
2330** Sometimes when requesting one lock state, additional lock states
2331** are inserted in between. The locking might fail on one of the later
2332** transitions leaving the lock state different from what it started but
2333** still short of its goal. The following chart shows the allowed
2334** transitions and the inserted intermediate states:
2335**
2336** UNLOCKED -> SHARED
2337** SHARED -> RESERVED
2338** SHARED -> (PENDING) -> EXCLUSIVE
2339** RESERVED -> (PENDING) -> EXCLUSIVE
2340** PENDING -> EXCLUSIVE
2341**
2342** flock() only really support EXCLUSIVE locks. We track intermediate
2343** lock states in the sqlite3_file structure, but all locks SHARED or
2344** above are really EXCLUSIVE locks and exclude all other processes from
2345** access the file.
2346**
2347** This routine will only increase a lock. Use the sqlite3OsUnlock()
2348** routine to lower a locking level.
2349*/
drh308c2a52010-05-14 11:30:18 +00002350static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002351 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002352 unixFile *pFile = (unixFile*)id;
2353
2354 assert( pFile );
2355
2356 /* if we already have a lock, it is exclusive.
2357 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002358 if (pFile->eFileLock > NO_LOCK) {
2359 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002360 return SQLITE_OK;
2361 }
2362
2363 /* grab an exclusive lock */
2364
drhff812312011-02-23 13:33:46 +00002365 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002366 int tErrno = errno;
2367 /* didn't get, must be busy */
2368 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2369 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002370 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002371 }
2372 } else {
2373 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002374 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002375 }
drh308c2a52010-05-14 11:30:18 +00002376 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2377 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002378#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2379 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2380 rc = SQLITE_BUSY;
2381 }
2382#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2383 return rc;
2384}
2385
drh6b9d6dd2008-12-03 19:34:47 +00002386
2387/*
drh308c2a52010-05-14 11:30:18 +00002388** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002389** must be either NO_LOCK or SHARED_LOCK.
2390**
2391** If the locking level of the file descriptor is already at or below
2392** the requested locking level, this routine is a no-op.
2393*/
drh308c2a52010-05-14 11:30:18 +00002394static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002395 unixFile *pFile = (unixFile*)id;
2396
2397 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002398 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002399 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002400 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002401
2402 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002403 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002404 return SQLITE_OK;
2405 }
2406
2407 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002408 if (eFileLock==SHARED_LOCK) {
2409 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002410 return SQLITE_OK;
2411 }
2412
2413 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002414 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002415#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002416 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002417#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002418 return SQLITE_IOERR_UNLOCK;
2419 }else{
drh308c2a52010-05-14 11:30:18 +00002420 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002421 return SQLITE_OK;
2422 }
2423}
2424
2425/*
2426** Close a file.
2427*/
2428static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002429 assert( id!=0 );
2430 flockUnlock(id, NO_LOCK);
2431 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002432}
2433
2434#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2435
2436/******************* End of the flock lock implementation *********************
2437******************************************************************************/
2438
2439/******************************************************************************
2440************************ Begin Named Semaphore Locking ************************
2441**
2442** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002443**
2444** Semaphore locking is like dot-lock and flock in that it really only
2445** supports EXCLUSIVE locking. Only a single process can read or write
2446** the database file at a time. This reduces potential concurrency, but
2447** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002448*/
2449#if OS_VXWORKS
2450
drh6b9d6dd2008-12-03 19:34:47 +00002451/*
2452** This routine checks if there is a RESERVED lock held on the specified
2453** file by this or any other process. If such a lock is held, set *pResOut
2454** to a non-zero value otherwise *pResOut is set to zero. The return value
2455** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2456*/
drh8cd5b252015-03-02 22:06:43 +00002457static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002458 int rc = SQLITE_OK;
2459 int reserved = 0;
2460 unixFile *pFile = (unixFile*)id;
2461
2462 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2463
2464 assert( pFile );
2465
2466 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002467 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002468 reserved = 1;
2469 }
2470
2471 /* Otherwise see if some other process holds it. */
2472 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002473 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002474
2475 if( sem_trywait(pSem)==-1 ){
2476 int tErrno = errno;
2477 if( EAGAIN != tErrno ){
2478 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002479 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002480 } else {
2481 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002482 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002483 }
2484 }else{
2485 /* we could have it if we want it */
2486 sem_post(pSem);
2487 }
2488 }
drh308c2a52010-05-14 11:30:18 +00002489 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002490
2491 *pResOut = reserved;
2492 return rc;
2493}
2494
drh6b9d6dd2008-12-03 19:34:47 +00002495/*
drh308c2a52010-05-14 11:30:18 +00002496** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002497** of the following:
2498**
2499** (1) SHARED_LOCK
2500** (2) RESERVED_LOCK
2501** (3) PENDING_LOCK
2502** (4) EXCLUSIVE_LOCK
2503**
2504** Sometimes when requesting one lock state, additional lock states
2505** are inserted in between. The locking might fail on one of the later
2506** transitions leaving the lock state different from what it started but
2507** still short of its goal. The following chart shows the allowed
2508** transitions and the inserted intermediate states:
2509**
2510** UNLOCKED -> SHARED
2511** SHARED -> RESERVED
2512** SHARED -> (PENDING) -> EXCLUSIVE
2513** RESERVED -> (PENDING) -> EXCLUSIVE
2514** PENDING -> EXCLUSIVE
2515**
2516** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2517** lock states in the sqlite3_file structure, but all locks SHARED or
2518** above are really EXCLUSIVE locks and exclude all other processes from
2519** access the file.
2520**
2521** This routine will only increase a lock. Use the sqlite3OsUnlock()
2522** routine to lower a locking level.
2523*/
drh8cd5b252015-03-02 22:06:43 +00002524static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002525 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002526 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002527 int rc = SQLITE_OK;
2528
2529 /* if we already have a lock, it is exclusive.
2530 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002531 if (pFile->eFileLock > NO_LOCK) {
2532 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002533 rc = SQLITE_OK;
2534 goto sem_end_lock;
2535 }
2536
2537 /* lock semaphore now but bail out when already locked. */
2538 if( sem_trywait(pSem)==-1 ){
2539 rc = SQLITE_BUSY;
2540 goto sem_end_lock;
2541 }
2542
2543 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002544 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002545
2546 sem_end_lock:
2547 return rc;
2548}
2549
drh6b9d6dd2008-12-03 19:34:47 +00002550/*
drh308c2a52010-05-14 11:30:18 +00002551** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002552** must be either NO_LOCK or SHARED_LOCK.
2553**
2554** If the locking level of the file descriptor is already at or below
2555** the requested locking level, this routine is a no-op.
2556*/
drh8cd5b252015-03-02 22:06:43 +00002557static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002558 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002559 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002560
2561 assert( pFile );
2562 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002563 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002564 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002565 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002566
2567 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002568 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002569 return SQLITE_OK;
2570 }
2571
2572 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002573 if (eFileLock==SHARED_LOCK) {
2574 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002575 return SQLITE_OK;
2576 }
2577
2578 /* no, really unlock. */
2579 if ( sem_post(pSem)==-1 ) {
2580 int rc, tErrno = errno;
2581 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2582 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002583 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002584 }
2585 return rc;
2586 }
drh308c2a52010-05-14 11:30:18 +00002587 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002588 return SQLITE_OK;
2589}
2590
2591/*
2592 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002593 */
drh8cd5b252015-03-02 22:06:43 +00002594static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002595 if( id ){
2596 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002597 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002598 assert( pFile );
2599 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002600 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002601 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002602 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002603 }
2604 return SQLITE_OK;
2605}
2606
2607#endif /* OS_VXWORKS */
2608/*
2609** Named semaphore locking is only available on VxWorks.
2610**
2611*************** End of the named semaphore lock implementation ****************
2612******************************************************************************/
2613
2614
2615/******************************************************************************
2616*************************** Begin AFP Locking *********************************
2617**
2618** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2619** on Apple Macintosh computers - both OS9 and OSX.
2620**
2621** Third-party implementations of AFP are available. But this code here
2622** only works on OSX.
2623*/
2624
drhd2cb50b2009-01-09 21:41:17 +00002625#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002626/*
2627** The afpLockingContext structure contains all afp lock specific state
2628*/
drhbfe66312006-10-03 17:40:40 +00002629typedef struct afpLockingContext afpLockingContext;
2630struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002631 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002632 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002633};
2634
2635struct ByteRangeLockPB2
2636{
2637 unsigned long long offset; /* offset to first byte to lock */
2638 unsigned long long length; /* nbr of bytes to lock */
2639 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2640 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2641 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2642 int fd; /* file desc to assoc this lock with */
2643};
2644
drhfd131da2007-08-07 17:13:03 +00002645#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002646
drh6b9d6dd2008-12-03 19:34:47 +00002647/*
2648** This is a utility for setting or clearing a bit-range lock on an
2649** AFP filesystem.
2650**
2651** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2652*/
2653static int afpSetLock(
2654 const char *path, /* Name of the file to be locked or unlocked */
2655 unixFile *pFile, /* Open file descriptor on path */
2656 unsigned long long offset, /* First byte to be locked */
2657 unsigned long long length, /* Number of bytes to lock */
2658 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002659){
drh6b9d6dd2008-12-03 19:34:47 +00002660 struct ByteRangeLockPB2 pb;
2661 int err;
drhbfe66312006-10-03 17:40:40 +00002662
2663 pb.unLockFlag = setLockFlag ? 0 : 1;
2664 pb.startEndFlag = 0;
2665 pb.offset = offset;
2666 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002667 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002668
drh308c2a52010-05-14 11:30:18 +00002669 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002670 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002671 offset, length));
drhbfe66312006-10-03 17:40:40 +00002672 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2673 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002674 int rc;
2675 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002676 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2677 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002678#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2679 rc = SQLITE_BUSY;
2680#else
drh734c9862008-11-28 15:37:20 +00002681 rc = sqliteErrorFromPosixError(tErrno,
2682 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002683#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002684 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002685 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002686 }
2687 return rc;
drhbfe66312006-10-03 17:40:40 +00002688 } else {
aswift5b1a2562008-08-22 00:22:35 +00002689 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002690 }
2691}
2692
drh6b9d6dd2008-12-03 19:34:47 +00002693/*
2694** This routine checks if there is a RESERVED lock held on the specified
2695** file by this or any other process. If such a lock is held, set *pResOut
2696** to a non-zero value otherwise *pResOut is set to zero. The return value
2697** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2698*/
danielk1977e339d652008-06-28 11:23:00 +00002699static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002700 int rc = SQLITE_OK;
2701 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002702 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002703 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002704
aswift5b1a2562008-08-22 00:22:35 +00002705 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2706
2707 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002708 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002709 if( context->reserved ){
2710 *pResOut = 1;
2711 return SQLITE_OK;
2712 }
drh8af6c222010-05-14 12:43:01 +00002713 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
drhbfe66312006-10-03 17:40:40 +00002714
2715 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002716 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002717 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002718 }
2719
2720 /* Otherwise see if some other process holds it.
2721 */
aswift5b1a2562008-08-22 00:22:35 +00002722 if( !reserved ){
2723 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002724 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002725 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002726 /* if we succeeded in taking the reserved lock, unlock it to restore
2727 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002728 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002729 } else {
2730 /* if we failed to get the lock then someone else must have it */
2731 reserved = 1;
2732 }
2733 if( IS_LOCK_ERROR(lrc) ){
2734 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002735 }
2736 }
drhbfe66312006-10-03 17:40:40 +00002737
drh7ed97b92010-01-20 13:07:21 +00002738 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002739 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002740
2741 *pResOut = reserved;
2742 return rc;
drhbfe66312006-10-03 17:40:40 +00002743}
2744
drh6b9d6dd2008-12-03 19:34:47 +00002745/*
drh308c2a52010-05-14 11:30:18 +00002746** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002747** of the following:
2748**
2749** (1) SHARED_LOCK
2750** (2) RESERVED_LOCK
2751** (3) PENDING_LOCK
2752** (4) EXCLUSIVE_LOCK
2753**
2754** Sometimes when requesting one lock state, additional lock states
2755** are inserted in between. The locking might fail on one of the later
2756** transitions leaving the lock state different from what it started but
2757** still short of its goal. The following chart shows the allowed
2758** transitions and the inserted intermediate states:
2759**
2760** UNLOCKED -> SHARED
2761** SHARED -> RESERVED
2762** SHARED -> (PENDING) -> EXCLUSIVE
2763** RESERVED -> (PENDING) -> EXCLUSIVE
2764** PENDING -> EXCLUSIVE
2765**
2766** This routine will only increase a lock. Use the sqlite3OsUnlock()
2767** routine to lower a locking level.
2768*/
drh308c2a52010-05-14 11:30:18 +00002769static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002770 int rc = SQLITE_OK;
2771 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002772 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002773 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002774
2775 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002776 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2777 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002778 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002779
drhbfe66312006-10-03 17:40:40 +00002780 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002781 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002782 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002783 */
drh308c2a52010-05-14 11:30:18 +00002784 if( pFile->eFileLock>=eFileLock ){
2785 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2786 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002787 return SQLITE_OK;
2788 }
2789
2790 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002791 ** (1) We never move from unlocked to anything higher than shared lock.
2792 ** (2) SQLite never explicitly requests a pendig lock.
2793 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002794 */
drh308c2a52010-05-14 11:30:18 +00002795 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2796 assert( eFileLock!=PENDING_LOCK );
2797 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002798
drh8af6c222010-05-14 12:43:01 +00002799 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002800 */
drh6c7d5c52008-11-21 20:32:33 +00002801 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002802 pInode = pFile->pInode;
drh7ed97b92010-01-20 13:07:21 +00002803
2804 /* If some thread using this PID has a lock via a different unixFile*
2805 ** handle that precludes the requested lock, return BUSY.
2806 */
drh8af6c222010-05-14 12:43:01 +00002807 if( (pFile->eFileLock!=pInode->eFileLock &&
2808 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002809 ){
2810 rc = SQLITE_BUSY;
2811 goto afp_end_lock;
2812 }
2813
2814 /* If a SHARED lock is requested, and some thread using this PID already
2815 ** has a SHARED or RESERVED lock, then increment reference counts and
2816 ** return SQLITE_OK.
2817 */
drh308c2a52010-05-14 11:30:18 +00002818 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002819 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002820 assert( eFileLock==SHARED_LOCK );
2821 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002822 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002823 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002824 pInode->nShared++;
2825 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002826 goto afp_end_lock;
2827 }
drhbfe66312006-10-03 17:40:40 +00002828
2829 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002830 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2831 ** be released.
2832 */
drh308c2a52010-05-14 11:30:18 +00002833 if( eFileLock==SHARED_LOCK
2834 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002835 ){
2836 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002837 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002838 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002839 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002840 goto afp_end_lock;
2841 }
2842 }
2843
2844 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002845 ** operating system calls for the specified lock.
2846 */
drh308c2a52010-05-14 11:30:18 +00002847 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002848 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002849 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002850
drh8af6c222010-05-14 12:43:01 +00002851 assert( pInode->nShared==0 );
2852 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002853
2854 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002855 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002856 /* note that the quality of the randomness doesn't matter that much */
2857 lk = random();
drh8af6c222010-05-14 12:43:01 +00002858 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002859 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002860 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002861 if( IS_LOCK_ERROR(lrc1) ){
2862 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002863 }
aswift5b1a2562008-08-22 00:22:35 +00002864 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002865 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002866
aswift5b1a2562008-08-22 00:22:35 +00002867 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002868 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002869 rc = lrc1;
2870 goto afp_end_lock;
2871 } else if( IS_LOCK_ERROR(lrc2) ){
2872 rc = lrc2;
2873 goto afp_end_lock;
2874 } else if( lrc1 != SQLITE_OK ) {
2875 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00002876 } else {
drh308c2a52010-05-14 11:30:18 +00002877 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002878 pInode->nLock++;
2879 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00002880 }
drh8af6c222010-05-14 12:43:01 +00002881 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00002882 /* We are trying for an exclusive lock but another thread in this
2883 ** same process is still holding a shared lock. */
2884 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00002885 }else{
2886 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2887 ** assumed that there is a SHARED or greater lock on the file
2888 ** already.
2889 */
2890 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00002891 assert( 0!=pFile->eFileLock );
2892 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002893 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00002894 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00002895 if( !failed ){
2896 context->reserved = 1;
2897 }
drhbfe66312006-10-03 17:40:40 +00002898 }
drh308c2a52010-05-14 11:30:18 +00002899 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00002900 /* Acquire an EXCLUSIVE lock */
2901
2902 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00002903 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00002904 */
drh6b9d6dd2008-12-03 19:34:47 +00002905 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00002906 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00002907 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002908 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00002909 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00002910 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00002911 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002912 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00002913 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2914 ** a critical I/O error
2915 */
2916 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2917 SQLITE_IOERR_LOCK;
2918 goto afp_end_lock;
2919 }
2920 }else{
aswift5b1a2562008-08-22 00:22:35 +00002921 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002922 }
2923 }
aswift5b1a2562008-08-22 00:22:35 +00002924 if( failed ){
2925 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002926 }
2927 }
2928
2929 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00002930 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00002931 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00002932 }else if( eFileLock==EXCLUSIVE_LOCK ){
2933 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00002934 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00002935 }
2936
2937afp_end_lock:
drh6c7d5c52008-11-21 20:32:33 +00002938 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00002939 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2940 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00002941 return rc;
2942}
2943
2944/*
drh308c2a52010-05-14 11:30:18 +00002945** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00002946** must be either NO_LOCK or SHARED_LOCK.
2947**
2948** If the locking level of the file descriptor is already at or below
2949** the requested locking level, this routine is a no-op.
2950*/
drh308c2a52010-05-14 11:30:18 +00002951static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00002952 int rc = SQLITE_OK;
2953 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002954 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00002955 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2956 int skipShared = 0;
2957#ifdef SQLITE_TEST
2958 int h = pFile->h;
2959#endif
drhbfe66312006-10-03 17:40:40 +00002960
2961 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002962 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00002963 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00002964 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00002965
drh308c2a52010-05-14 11:30:18 +00002966 assert( eFileLock<=SHARED_LOCK );
2967 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00002968 return SQLITE_OK;
2969 }
drh6c7d5c52008-11-21 20:32:33 +00002970 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00002971 pInode = pFile->pInode;
2972 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00002973 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00002974 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00002975 SimulateIOErrorBenign(1);
2976 SimulateIOError( h=(-1) )
2977 SimulateIOErrorBenign(0);
2978
drhd3d8c042012-05-29 17:02:40 +00002979#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00002980 /* When reducing a lock such that other processes can start
2981 ** reading the database file again, make sure that the
2982 ** transaction counter was updated if any part of the database
2983 ** file changed. If the transaction counter is not updated,
2984 ** other connections to the same file might not realize that
2985 ** the file has changed and hence might not know to flush their
2986 ** cache. The use of a stale cache can lead to database corruption.
2987 */
2988 assert( pFile->inNormalWrite==0
2989 || pFile->dbUpdate==0
2990 || pFile->transCntrChng==1 );
2991 pFile->inNormalWrite = 0;
2992#endif
aswiftaebf4132008-11-21 00:10:35 +00002993
drh308c2a52010-05-14 11:30:18 +00002994 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00002995 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00002996 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00002997 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00002998 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00002999 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3000 } else {
3001 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003002 }
3003 }
drh308c2a52010-05-14 11:30:18 +00003004 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003005 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003006 }
drh308c2a52010-05-14 11:30:18 +00003007 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003008 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3009 if( !rc ){
3010 context->reserved = 0;
3011 }
aswiftaebf4132008-11-21 00:10:35 +00003012 }
drh8af6c222010-05-14 12:43:01 +00003013 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3014 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003015 }
aswiftaebf4132008-11-21 00:10:35 +00003016 }
drh308c2a52010-05-14 11:30:18 +00003017 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003018
drh7ed97b92010-01-20 13:07:21 +00003019 /* Decrement the shared lock counter. Release the lock using an
3020 ** OS call only when all threads in this same process have released
3021 ** the lock.
3022 */
drh8af6c222010-05-14 12:43:01 +00003023 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3024 pInode->nShared--;
3025 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003026 SimulateIOErrorBenign(1);
3027 SimulateIOError( h=(-1) )
3028 SimulateIOErrorBenign(0);
3029 if( !skipShared ){
3030 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3031 }
3032 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003033 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003034 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003035 }
3036 }
3037 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003038 pInode->nLock--;
3039 assert( pInode->nLock>=0 );
3040 if( pInode->nLock==0 ){
drh0e9365c2011-03-02 02:08:13 +00003041 closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003042 }
3043 }
drhbfe66312006-10-03 17:40:40 +00003044 }
drh7ed97b92010-01-20 13:07:21 +00003045
drh6c7d5c52008-11-21 20:32:33 +00003046 unixLeaveMutex();
drh308c2a52010-05-14 11:30:18 +00003047 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
drhbfe66312006-10-03 17:40:40 +00003048 return rc;
3049}
3050
3051/*
drh339eb0b2008-03-07 15:34:11 +00003052** Close a file & cleanup AFP specific locking context
3053*/
danielk1977e339d652008-06-28 11:23:00 +00003054static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003055 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003056 unixFile *pFile = (unixFile*)id;
3057 assert( id!=0 );
3058 afpUnlock(id, NO_LOCK);
3059 unixEnterMutex();
3060 if( pFile->pInode && pFile->pInode->nLock ){
3061 /* If there are outstanding locks, do not actually close the file just
3062 ** yet because that would clear those locks. Instead, add the file
3063 ** descriptor to pInode->aPending. It will be automatically closed when
3064 ** the last lock is cleared.
3065 */
3066 setPendingFd(pFile);
danielk1977e339d652008-06-28 11:23:00 +00003067 }
drha8de1e12015-11-30 00:05:39 +00003068 releaseInodeInfo(pFile);
3069 sqlite3_free(pFile->lockingContext);
3070 rc = closeUnixFile(id);
3071 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003072 return rc;
drhbfe66312006-10-03 17:40:40 +00003073}
3074
drhd2cb50b2009-01-09 21:41:17 +00003075#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003076/*
3077** The code above is the AFP lock implementation. The code is specific
3078** to MacOSX and does not work on other unix platforms. No alternative
3079** is available. If you don't compile for a mac, then the "unix-afp"
3080** VFS is not available.
3081**
3082********************* End of the AFP lock implementation **********************
3083******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003084
drh7ed97b92010-01-20 13:07:21 +00003085/******************************************************************************
3086*************************** Begin NFS Locking ********************************/
3087
3088#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3089/*
drh308c2a52010-05-14 11:30:18 +00003090 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003091 ** must be either NO_LOCK or SHARED_LOCK.
3092 **
3093 ** If the locking level of the file descriptor is already at or below
3094 ** the requested locking level, this routine is a no-op.
3095 */
drh308c2a52010-05-14 11:30:18 +00003096static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003097 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003098}
3099
3100#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3101/*
3102** The code above is the NFS lock implementation. The code is specific
3103** to MacOSX and does not work on other unix platforms. No alternative
3104** is available.
3105**
3106********************* End of the NFS lock implementation **********************
3107******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003108
3109/******************************************************************************
3110**************** Non-locking sqlite3_file methods *****************************
3111**
3112** The next division contains implementations for all methods of the
3113** sqlite3_file object other than the locking methods. The locking
3114** methods were defined in divisions above (one locking method per
3115** division). Those methods that are common to all locking modes
3116** are gather together into this division.
3117*/
drhbfe66312006-10-03 17:40:40 +00003118
3119/*
drh734c9862008-11-28 15:37:20 +00003120** Seek to the offset passed as the second argument, then read cnt
3121** bytes into pBuf. Return the number of bytes actually read.
3122**
3123** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3124** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3125** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003126** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003127** See tickets #2741 and #2681.
3128**
3129** To avoid stomping the errno value on a failed read the lastErrno value
3130** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003131*/
drh734c9862008-11-28 15:37:20 +00003132static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3133 int got;
drh58024642011-11-07 18:16:00 +00003134 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003135#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3136 i64 newOffset;
3137#endif
drh734c9862008-11-28 15:37:20 +00003138 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003139 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003140 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003141 do{
drh734c9862008-11-28 15:37:20 +00003142#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003143 got = osPread(id->h, pBuf, cnt, offset);
3144 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003145#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003146 got = osPread64(id->h, pBuf, cnt, offset);
3147 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003148#else
drha46cadc2016-03-04 03:02:06 +00003149 newOffset = lseek(id->h, offset, SEEK_SET);
3150 SimulateIOError( newOffset = -1 );
3151 if( newOffset<0 ){
3152 storeLastErrno((unixFile*)id, errno);
3153 return -1;
3154 }
3155 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003156#endif
drh58024642011-11-07 18:16:00 +00003157 if( got==cnt ) break;
3158 if( got<0 ){
3159 if( errno==EINTR ){ got = 1; continue; }
3160 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003161 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003162 break;
3163 }else if( got>0 ){
3164 cnt -= got;
3165 offset += got;
3166 prior += got;
3167 pBuf = (void*)(got + (char*)pBuf);
3168 }
3169 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003170 TIMER_END;
drh58024642011-11-07 18:16:00 +00003171 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3172 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3173 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003174}
3175
3176/*
drh734c9862008-11-28 15:37:20 +00003177** Read data from a file into a buffer. Return SQLITE_OK if all
3178** bytes were read successfully and SQLITE_IOERR if anything goes
3179** wrong.
drh339eb0b2008-03-07 15:34:11 +00003180*/
drh734c9862008-11-28 15:37:20 +00003181static int unixRead(
3182 sqlite3_file *id,
3183 void *pBuf,
3184 int amt,
3185 sqlite3_int64 offset
3186){
dan08da86a2009-08-21 17:18:03 +00003187 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003188 int got;
3189 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003190 assert( offset>=0 );
3191 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003192
dan08da86a2009-08-21 17:18:03 +00003193 /* If this is a database file (not a journal, master-journal or temp
3194 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003195#if 0
dane946c392009-08-22 11:39:46 +00003196 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003197 || offset>=PENDING_BYTE+512
3198 || offset+amt<=PENDING_BYTE
3199 );
dan7c246102010-04-12 19:00:29 +00003200#endif
drh08c6d442009-02-09 17:34:07 +00003201
drh9b4c59f2013-04-15 17:03:42 +00003202#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003203 /* Deal with as much of this read request as possible by transfering
3204 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003205 if( offset<pFile->mmapSize ){
3206 if( offset+amt <= pFile->mmapSize ){
3207 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3208 return SQLITE_OK;
3209 }else{
3210 int nCopy = pFile->mmapSize - offset;
3211 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3212 pBuf = &((u8 *)pBuf)[nCopy];
3213 amt -= nCopy;
3214 offset += nCopy;
3215 }
3216 }
drh6e0b6d52013-04-09 16:19:20 +00003217#endif
danf23da962013-03-23 21:00:41 +00003218
dan08da86a2009-08-21 17:18:03 +00003219 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003220 if( got==amt ){
3221 return SQLITE_OK;
3222 }else if( got<0 ){
3223 /* lastErrno set by seekAndRead */
3224 return SQLITE_IOERR_READ;
3225 }else{
drh4bf66fd2015-02-19 02:43:02 +00003226 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003227 /* Unread parts of the buffer must be zero-filled */
3228 memset(&((char*)pBuf)[got], 0, amt-got);
3229 return SQLITE_IOERR_SHORT_READ;
3230 }
3231}
3232
3233/*
dan47a2b4a2013-04-26 16:09:29 +00003234** Attempt to seek the file-descriptor passed as the first argument to
3235** absolute offset iOff, then attempt to write nBuf bytes of data from
3236** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3237** return the actual number of bytes written (which may be less than
3238** nBuf).
3239*/
3240static int seekAndWriteFd(
3241 int fd, /* File descriptor to write to */
3242 i64 iOff, /* File offset to begin writing at */
3243 const void *pBuf, /* Copy data from this buffer to the file */
3244 int nBuf, /* Size of buffer pBuf in bytes */
3245 int *piErrno /* OUT: Error number if error occurs */
3246){
3247 int rc = 0; /* Value returned by system call */
3248
3249 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003250 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003251 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003252 nBuf &= 0x1ffff;
3253 TIMER_START;
3254
3255#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003256 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003257#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003258 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003259#else
3260 do{
3261 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003262 SimulateIOError( iSeek = -1 );
3263 if( iSeek<0 ){
3264 rc = -1;
3265 break;
dan47a2b4a2013-04-26 16:09:29 +00003266 }
3267 rc = osWrite(fd, pBuf, nBuf);
3268 }while( rc<0 && errno==EINTR );
3269#endif
3270
3271 TIMER_END;
3272 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3273
drhe1818ec2015-12-01 16:21:35 +00003274 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003275 return rc;
3276}
3277
3278
3279/*
drh734c9862008-11-28 15:37:20 +00003280** Seek to the offset in id->offset then read cnt bytes into pBuf.
3281** Return the number of bytes actually read. Update the offset.
3282**
3283** To avoid stomping the errno value on a failed write the lastErrno value
3284** is set before returning.
3285*/
3286static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003287 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003288}
3289
3290
3291/*
3292** Write data from a buffer into a file. Return SQLITE_OK on success
3293** or some other error code on failure.
3294*/
3295static int unixWrite(
3296 sqlite3_file *id,
3297 const void *pBuf,
3298 int amt,
3299 sqlite3_int64 offset
3300){
dan08da86a2009-08-21 17:18:03 +00003301 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003302 int wrote = 0;
3303 assert( id );
3304 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003305
dan08da86a2009-08-21 17:18:03 +00003306 /* If this is a database file (not a journal, master-journal or temp
3307 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003308#if 0
dane946c392009-08-22 11:39:46 +00003309 assert( pFile->pUnused==0
dan08da86a2009-08-21 17:18:03 +00003310 || offset>=PENDING_BYTE+512
3311 || offset+amt<=PENDING_BYTE
3312 );
dan7c246102010-04-12 19:00:29 +00003313#endif
drh08c6d442009-02-09 17:34:07 +00003314
drhd3d8c042012-05-29 17:02:40 +00003315#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003316 /* If we are doing a normal write to a database file (as opposed to
3317 ** doing a hot-journal rollback or a write to some file other than a
3318 ** normal database file) then record the fact that the database
3319 ** has changed. If the transaction counter is modified, record that
3320 ** fact too.
3321 */
dan08da86a2009-08-21 17:18:03 +00003322 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003323 pFile->dbUpdate = 1; /* The database has been modified */
3324 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003325 int rc;
drh8f941bc2009-01-14 23:03:40 +00003326 char oldCntr[4];
3327 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003328 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003329 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003330 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003331 pFile->transCntrChng = 1; /* The transaction counter has changed */
3332 }
3333 }
3334 }
3335#endif
3336
danfe33e392015-11-17 20:56:06 +00003337#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003338 /* Deal with as much of this write request as possible by transfering
3339 ** data from the memory mapping using memcpy(). */
3340 if( offset<pFile->mmapSize ){
3341 if( offset+amt <= pFile->mmapSize ){
3342 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3343 return SQLITE_OK;
3344 }else{
3345 int nCopy = pFile->mmapSize - offset;
3346 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3347 pBuf = &((u8 *)pBuf)[nCopy];
3348 amt -= nCopy;
3349 offset += nCopy;
3350 }
3351 }
drh6e0b6d52013-04-09 16:19:20 +00003352#endif
drh02bf8b42015-09-01 23:51:53 +00003353
3354 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003355 amt -= wrote;
3356 offset += wrote;
3357 pBuf = &((char*)pBuf)[wrote];
3358 }
3359 SimulateIOError(( wrote=(-1), amt=1 ));
3360 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003361
drh02bf8b42015-09-01 23:51:53 +00003362 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003363 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003364 /* lastErrno set by seekAndWrite */
3365 return SQLITE_IOERR_WRITE;
3366 }else{
drh4bf66fd2015-02-19 02:43:02 +00003367 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003368 return SQLITE_FULL;
3369 }
3370 }
dan6e09d692010-07-27 18:34:15 +00003371
drh734c9862008-11-28 15:37:20 +00003372 return SQLITE_OK;
3373}
3374
3375#ifdef SQLITE_TEST
3376/*
3377** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003378** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003379*/
3380int sqlite3_sync_count = 0;
3381int sqlite3_fullsync_count = 0;
3382#endif
3383
3384/*
drh89240432009-03-25 01:06:01 +00003385** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003386** Others do no. To be safe, we will stick with the (slightly slower)
3387** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003388** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003389*/
drhf7a4a1b2015-01-10 18:02:45 +00003390#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003391# define fdatasync fsync
3392#endif
3393
3394/*
3395** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3396** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3397** only available on Mac OS X. But that could change.
3398*/
3399#ifdef F_FULLFSYNC
3400# define HAVE_FULLFSYNC 1
3401#else
3402# define HAVE_FULLFSYNC 0
3403#endif
3404
3405
3406/*
3407** The fsync() system call does not work as advertised on many
3408** unix systems. The following procedure is an attempt to make
3409** it work better.
3410**
3411** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3412** for testing when we want to run through the test suite quickly.
3413** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3414** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3415** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003416**
3417** SQLite sets the dataOnly flag if the size of the file is unchanged.
3418** The idea behind dataOnly is that it should only write the file content
3419** to disk, not the inode. We only set dataOnly if the file size is
3420** unchanged since the file size is part of the inode. However,
3421** Ted Ts'o tells us that fdatasync() will also write the inode if the
3422** file size has changed. The only real difference between fdatasync()
3423** and fsync(), Ted tells us, is that fdatasync() will not flush the
3424** inode if the mtime or owner or other inode attributes have changed.
3425** We only care about the file size, not the other file attributes, so
3426** as far as SQLite is concerned, an fdatasync() is always adequate.
3427** So, we always use fdatasync() if it is available, regardless of
3428** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003429*/
3430static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003431 int rc;
drh734c9862008-11-28 15:37:20 +00003432
3433 /* The following "ifdef/elif/else/" block has the same structure as
3434 ** the one below. It is replicated here solely to avoid cluttering
3435 ** up the real code with the UNUSED_PARAMETER() macros.
3436 */
3437#ifdef SQLITE_NO_SYNC
3438 UNUSED_PARAMETER(fd);
3439 UNUSED_PARAMETER(fullSync);
3440 UNUSED_PARAMETER(dataOnly);
3441#elif HAVE_FULLFSYNC
3442 UNUSED_PARAMETER(dataOnly);
3443#else
3444 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003445 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003446#endif
3447
3448 /* Record the number of times that we do a normal fsync() and
3449 ** FULLSYNC. This is used during testing to verify that this procedure
3450 ** gets called with the correct arguments.
3451 */
3452#ifdef SQLITE_TEST
3453 if( fullSync ) sqlite3_fullsync_count++;
3454 sqlite3_sync_count++;
3455#endif
3456
3457 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003458 ** no-op. But go ahead and call fstat() to validate the file
3459 ** descriptor as we need a method to provoke a failure during
3460 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003461 */
3462#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003463 {
3464 struct stat buf;
3465 rc = osFstat(fd, &buf);
3466 }
drh734c9862008-11-28 15:37:20 +00003467#elif HAVE_FULLFSYNC
3468 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003469 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003470 }else{
3471 rc = 1;
3472 }
3473 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003474 ** It shouldn't be possible for fullfsync to fail on the local
3475 ** file system (on OSX), so failure indicates that FULLFSYNC
3476 ** isn't supported for this file system. So, attempt an fsync
3477 ** and (for now) ignore the overhead of a superfluous fcntl call.
3478 ** It'd be better to detect fullfsync support once and avoid
3479 ** the fcntl call every time sync is called.
3480 */
drh734c9862008-11-28 15:37:20 +00003481 if( rc ) rc = fsync(fd);
3482
drh7ed97b92010-01-20 13:07:21 +00003483#elif defined(__APPLE__)
3484 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3485 ** so currently we default to the macro that redefines fdatasync to fsync
3486 */
3487 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003488#else
drh0b647ff2009-03-21 14:41:04 +00003489 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003490#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003491 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003492 rc = fsync(fd);
3493 }
drh0b647ff2009-03-21 14:41:04 +00003494#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003495#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3496
3497 if( OS_VXWORKS && rc!= -1 ){
3498 rc = 0;
3499 }
chw97185482008-11-17 08:05:31 +00003500 return rc;
drhbfe66312006-10-03 17:40:40 +00003501}
3502
drh734c9862008-11-28 15:37:20 +00003503/*
drh0059eae2011-08-08 23:48:40 +00003504** Open a file descriptor to the directory containing file zFilename.
3505** If successful, *pFd is set to the opened file descriptor and
3506** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3507** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3508** value.
3509**
drh90315a22011-08-10 01:52:12 +00003510** The directory file descriptor is used for only one thing - to
3511** fsync() a directory to make sure file creation and deletion events
3512** are flushed to disk. Such fsyncs are not needed on newer
3513** journaling filesystems, but are required on older filesystems.
3514**
3515** This routine can be overridden using the xSetSysCall interface.
3516** The ability to override this routine was added in support of the
3517** chromium sandbox. Opening a directory is a security risk (we are
3518** told) so making it overrideable allows the chromium sandbox to
3519** replace this routine with a harmless no-op. To make this routine
3520** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3521** *pFd set to a negative number.
3522**
drh0059eae2011-08-08 23:48:40 +00003523** If SQLITE_OK is returned, the caller is responsible for closing
3524** the file descriptor *pFd using close().
3525*/
3526static int openDirectory(const char *zFilename, int *pFd){
3527 int ii;
3528 int fd = -1;
3529 char zDirname[MAX_PATHNAME+1];
3530
3531 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003532 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3533 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003534 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003535 }else{
3536 if( zDirname[0]!='/' ) zDirname[0] = '.';
3537 zDirname[1] = 0;
3538 }
3539 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3540 if( fd>=0 ){
3541 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003542 }
3543 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003544 if( fd>=0 ) return SQLITE_OK;
3545 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003546}
3547
3548/*
drh734c9862008-11-28 15:37:20 +00003549** Make sure all writes to a particular file are committed to disk.
3550**
3551** If dataOnly==0 then both the file itself and its metadata (file
3552** size, access time, etc) are synced. If dataOnly!=0 then only the
3553** file data is synced.
3554**
3555** Under Unix, also make sure that the directory entry for the file
3556** has been created by fsync-ing the directory that contains the file.
3557** If we do not do this and we encounter a power failure, the directory
3558** entry for the journal might not exist after we reboot. The next
3559** SQLite to access the file will not know that the journal exists (because
3560** the directory entry for the journal was never created) and the transaction
3561** will not roll back - possibly leading to database corruption.
3562*/
3563static int unixSync(sqlite3_file *id, int flags){
3564 int rc;
3565 unixFile *pFile = (unixFile*)id;
3566
3567 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3568 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3569
3570 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3571 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3572 || (flags&0x0F)==SQLITE_SYNC_FULL
3573 );
3574
3575 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3576 ** line is to test that doing so does not cause any problems.
3577 */
3578 SimulateDiskfullError( return SQLITE_FULL );
3579
3580 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003581 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003582 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3583 SimulateIOError( rc=1 );
3584 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003585 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003586 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003587 }
drh0059eae2011-08-08 23:48:40 +00003588
3589 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003590 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003591 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003592 */
3593 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3594 int dirfd;
3595 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003596 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003597 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003598 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003599 full_fsync(dirfd, 0, 0);
3600 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003601 }else{
3602 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003603 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003604 }
drh0059eae2011-08-08 23:48:40 +00003605 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003606 }
3607 return rc;
3608}
3609
3610/*
3611** Truncate an open file to a specified size
3612*/
3613static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003614 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003615 int rc;
dan6e09d692010-07-27 18:34:15 +00003616 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003617 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003618
3619 /* If the user has configured a chunk-size for this file, truncate the
3620 ** file so that it consists of an integer number of chunks (i.e. the
3621 ** actual file size after the operation may be larger than the requested
3622 ** size).
3623 */
drhb8af4b72012-04-05 20:04:39 +00003624 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003625 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3626 }
3627
dan2ee53412014-09-06 16:49:40 +00003628 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003629 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003630 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003631 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003632 }else{
drhd3d8c042012-05-29 17:02:40 +00003633#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003634 /* If we are doing a normal write to a database file (as opposed to
3635 ** doing a hot-journal rollback or a write to some file other than a
3636 ** normal database file) and we truncate the file to zero length,
3637 ** that effectively updates the change counter. This might happen
3638 ** when restoring a database using the backup API from a zero-length
3639 ** source.
3640 */
dan6e09d692010-07-27 18:34:15 +00003641 if( pFile->inNormalWrite && nByte==0 ){
3642 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003643 }
danf23da962013-03-23 21:00:41 +00003644#endif
danc0003312013-03-22 17:46:11 +00003645
mistachkine98844f2013-08-24 00:59:24 +00003646#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003647 /* If the file was just truncated to a size smaller than the currently
3648 ** mapped region, reduce the effective mapping size as well. SQLite will
3649 ** use read() and write() to access data beyond this point from now on.
3650 */
3651 if( nByte<pFile->mmapSize ){
3652 pFile->mmapSize = nByte;
3653 }
mistachkine98844f2013-08-24 00:59:24 +00003654#endif
drh3313b142009-11-06 04:13:18 +00003655
drh734c9862008-11-28 15:37:20 +00003656 return SQLITE_OK;
3657 }
3658}
3659
3660/*
3661** Determine the current size of a file in bytes
3662*/
3663static int unixFileSize(sqlite3_file *id, i64 *pSize){
3664 int rc;
3665 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003666 assert( id );
3667 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003668 SimulateIOError( rc=1 );
3669 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003670 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003671 return SQLITE_IOERR_FSTAT;
3672 }
3673 *pSize = buf.st_size;
3674
drh8af6c222010-05-14 12:43:01 +00003675 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003676 ** writes a single byte into that file in order to work around a bug
3677 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3678 ** layers, we need to report this file size as zero even though it is
3679 ** really 1. Ticket #3260.
3680 */
3681 if( *pSize==1 ) *pSize = 0;
3682
3683
3684 return SQLITE_OK;
3685}
3686
drhd2cb50b2009-01-09 21:41:17 +00003687#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003688/*
3689** Handler for proxy-locking file-control verbs. Defined below in the
3690** proxying locking division.
3691*/
3692static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003693#endif
drh715ff302008-12-03 22:32:44 +00003694
dan502019c2010-07-28 14:26:17 +00003695/*
3696** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003697** file-control operation. Enlarge the database to nBytes in size
3698** (rounded up to the next chunk-size). If the database is already
3699** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003700*/
3701static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003702 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003703 i64 nSize; /* Required file size */
3704 struct stat buf; /* Used to hold return values of fstat() */
3705
drh4bf66fd2015-02-19 02:43:02 +00003706 if( osFstat(pFile->h, &buf) ){
3707 return SQLITE_IOERR_FSTAT;
3708 }
dan502019c2010-07-28 14:26:17 +00003709
3710 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3711 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003712
dan502019c2010-07-28 14:26:17 +00003713#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003714 /* The code below is handling the return value of osFallocate()
3715 ** correctly. posix_fallocate() is defined to "returns zero on success,
3716 ** or an error number on failure". See the manpage for details. */
3717 int err;
drhff812312011-02-23 13:33:46 +00003718 do{
dan661d71a2011-03-30 19:08:03 +00003719 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3720 }while( err==EINTR );
3721 if( err ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003722#else
dan592bf7f2014-12-30 19:58:31 +00003723 /* If the OS does not have posix_fallocate(), fake it. Write a
3724 ** single byte to the last byte in each block that falls entirely
3725 ** within the extended region. Then, if required, a single byte
3726 ** at offset (nSize-1), to set the size of the file correctly.
3727 ** This is a similar technique to that used by glibc on systems
3728 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003729 */
3730 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003731 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003732 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003733
drh053378d2015-12-01 22:09:42 +00003734 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003735 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003736 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003737 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3738 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003739 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003740 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003741 }
dan502019c2010-07-28 14:26:17 +00003742#endif
3743 }
3744 }
3745
mistachkine98844f2013-08-24 00:59:24 +00003746#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003747 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003748 int rc;
3749 if( pFile->szChunk<=0 ){
3750 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003751 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003752 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3753 }
3754 }
3755
3756 rc = unixMapfile(pFile, nByte);
3757 return rc;
3758 }
mistachkine98844f2013-08-24 00:59:24 +00003759#endif
danf23da962013-03-23 21:00:41 +00003760
dan502019c2010-07-28 14:26:17 +00003761 return SQLITE_OK;
3762}
danielk1977ad94b582007-08-20 06:44:22 +00003763
danielk1977e3026632004-06-22 11:29:02 +00003764/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003765** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003766** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3767**
3768** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3769*/
3770static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3771 if( *pArg<0 ){
3772 *pArg = (pFile->ctrlFlags & mask)!=0;
3773 }else if( (*pArg)==0 ){
3774 pFile->ctrlFlags &= ~mask;
3775 }else{
3776 pFile->ctrlFlags |= mask;
3777 }
3778}
3779
drh696b33e2012-12-06 19:01:42 +00003780/* Forward declaration */
3781static int unixGetTempname(int nBuf, char *zBuf);
3782
drhf12b3f62011-12-21 14:42:29 +00003783/*
drh9e33c2c2007-08-31 18:34:59 +00003784** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003785*/
drhcc6bb3e2007-08-31 16:11:35 +00003786static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003787 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003788 switch( op ){
danefe16972017-07-20 19:49:14 +00003789 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3790 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
3791 return rc ? SQLITE_ERROR : SQLITE_OK;
3792 }
3793 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3794 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
3795 return rc ? SQLITE_ERROR : SQLITE_OK;
3796 }
3797 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3798 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3799 return rc ? SQLITE_ERROR : SQLITE_OK;
3800 }
3801
drh9e33c2c2007-08-31 18:34:59 +00003802 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003803 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003804 return SQLITE_OK;
3805 }
drh4bf66fd2015-02-19 02:43:02 +00003806 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003807 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003808 return SQLITE_OK;
3809 }
dan6e09d692010-07-27 18:34:15 +00003810 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003811 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003812 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003813 }
drh9ff27ec2010-05-19 19:26:05 +00003814 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003815 int rc;
3816 SimulateIOErrorBenign(1);
3817 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3818 SimulateIOErrorBenign(0);
3819 return rc;
drhf0b190d2011-07-26 16:03:07 +00003820 }
3821 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003822 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3823 return SQLITE_OK;
3824 }
drhcb15f352011-12-23 01:04:17 +00003825 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3826 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003827 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003828 }
drhde60fc22011-12-14 17:53:36 +00003829 case SQLITE_FCNTL_VFSNAME: {
3830 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3831 return SQLITE_OK;
3832 }
drh696b33e2012-12-06 19:01:42 +00003833 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003834 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003835 if( zTFile ){
3836 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3837 *(char**)pArg = zTFile;
3838 }
3839 return SQLITE_OK;
3840 }
drhb959a012013-12-07 12:29:22 +00003841 case SQLITE_FCNTL_HAS_MOVED: {
3842 *(int*)pArg = fileHasMoved(pFile);
3843 return SQLITE_OK;
3844 }
mistachkine98844f2013-08-24 00:59:24 +00003845#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003846 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003847 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003848 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003849 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3850 newLimit = sqlite3GlobalConfig.mxMmap;
3851 }
3852 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00003853 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00003854 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00003855 if( pFile->mmapSize>0 ){
3856 unixUnmapfile(pFile);
3857 rc = unixMapfile(pFile, -1);
3858 }
danbcb8a862013-04-08 15:30:41 +00003859 }
drh34e258c2013-05-23 01:40:53 +00003860 return rc;
danb2d3de32013-03-14 18:34:37 +00003861 }
mistachkine98844f2013-08-24 00:59:24 +00003862#endif
drhd3d8c042012-05-29 17:02:40 +00003863#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003864 /* The pager calls this method to signal that it has done
3865 ** a rollback and that the database is therefore unchanged and
3866 ** it hence it is OK for the transaction change counter to be
3867 ** unchanged.
3868 */
3869 case SQLITE_FCNTL_DB_UNCHANGED: {
3870 ((unixFile*)id)->dbUpdate = 0;
3871 return SQLITE_OK;
3872 }
3873#endif
drhd2cb50b2009-01-09 21:41:17 +00003874#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00003875 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
3876 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00003877 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00003878 }
drhd2cb50b2009-01-09 21:41:17 +00003879#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00003880 }
drh0b52b7d2011-01-26 19:46:22 +00003881 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00003882}
3883
3884/*
danefe16972017-07-20 19:49:14 +00003885** If pFd->sectorSize is non-zero when this function is called, it is a
3886** no-op. Otherwise, the values of pFd->sectorSize and
3887** pFd->deviceCharacteristics are set according to the file-system
3888** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00003889**
danefe16972017-07-20 19:49:14 +00003890** There are two versions of this function. One for QNX and one for all
3891** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00003892*/
danefe16972017-07-20 19:49:14 +00003893#ifndef __QNXNTO__
3894static void setDeviceCharacteristics(unixFile *pFd){
3895 if( pFd->sectorSize==0 ){
3896 int res;
3897 assert( pFd->deviceCharacteristics==0 );
drh537dddf2012-10-26 13:46:24 +00003898
danefe16972017-07-20 19:49:14 +00003899 /* Check for support for F2FS atomic batch writes. */
3900 res = osIoctl(pFd->h, F2FS_IOC_START_VOLATILE_WRITE);
3901 if( res==SQLITE_OK ){
3902 osIoctl(pFd->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
3903 pFd->deviceCharacteristics =
3904 SQLITE_IOCAP_BATCH_ATOMIC |
3905 SQLITE_IOCAP_ATOMIC |
3906 SQLITE_IOCAP_SEQUENTIAL |
3907 SQLITE_IOCAP_SAFE_APPEND;
3908 }
3909
3910 /* Set the POWERSAFE_OVERWRITE flag if requested. */
3911 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
3912 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
3913 }
3914
3915 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3916 }
3917}
3918#else
drh537dddf2012-10-26 13:46:24 +00003919#include <sys/dcmd_blk.h>
3920#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00003921static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00003922 if( pFile->sectorSize == 0 ){
3923 struct statvfs fsInfo;
3924
3925 /* Set defaults for non-supported filesystems */
3926 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3927 pFile->deviceCharacteristics = 0;
3928 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
3929 return pFile->sectorSize;
3930 }
3931
3932 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
3933 pFile->sectorSize = fsInfo.f_bsize;
3934 pFile->deviceCharacteristics =
3935 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
3936 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3937 ** the write succeeds */
3938 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3939 ** so it is ordered */
3940 0;
3941 }else if( strstr(fsInfo.f_basetype, "etfs") ){
3942 pFile->sectorSize = fsInfo.f_bsize;
3943 pFile->deviceCharacteristics =
3944 /* etfs cluster size writes are atomic */
3945 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
3946 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3947 ** the write succeeds */
3948 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3949 ** so it is ordered */
3950 0;
3951 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
3952 pFile->sectorSize = fsInfo.f_bsize;
3953 pFile->deviceCharacteristics =
3954 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
3955 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3956 ** the write succeeds */
3957 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3958 ** so it is ordered */
3959 0;
3960 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
3961 pFile->sectorSize = fsInfo.f_bsize;
3962 pFile->deviceCharacteristics =
3963 /* full bitset of atomics from max sector size and smaller */
3964 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3965 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3966 ** so it is ordered */
3967 0;
3968 }else if( strstr(fsInfo.f_basetype, "dos") ){
3969 pFile->sectorSize = fsInfo.f_bsize;
3970 pFile->deviceCharacteristics =
3971 /* full bitset of atomics from max sector size and smaller */
3972 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
3973 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
3974 ** so it is ordered */
3975 0;
3976 }else{
3977 pFile->deviceCharacteristics =
3978 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
3979 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
3980 ** the write succeeds */
3981 0;
3982 }
3983 }
3984 /* Last chance verification. If the sector size isn't a multiple of 512
3985 ** then it isn't valid.*/
3986 if( pFile->sectorSize % 512 != 0 ){
3987 pFile->deviceCharacteristics = 0;
3988 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
3989 }
drh537dddf2012-10-26 13:46:24 +00003990}
danefe16972017-07-20 19:49:14 +00003991#endif
3992
3993/*
3994** Return the sector size in bytes of the underlying block device for
3995** the specified file. This is almost always 512 bytes, but may be
3996** larger for some devices.
3997**
3998** SQLite code assumes this function cannot fail. It also assumes that
3999** if two files are created in the same file-system directory (i.e.
4000** a database and its journal file) that the sector size will be the
4001** same for both.
4002*/
4003static int unixSectorSize(sqlite3_file *id){
4004 unixFile *pFd = (unixFile*)id;
4005 setDeviceCharacteristics(pFd);
4006 return pFd->sectorSize;
4007}
danielk1977a3d4c882007-03-23 10:08:38 +00004008
danielk197790949c22007-08-17 16:50:38 +00004009/*
drhf12b3f62011-12-21 14:42:29 +00004010** Return the device characteristics for the file.
4011**
drhcb15f352011-12-23 01:04:17 +00004012** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004013** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004014** file system does not always provide powersafe overwrites. (In other
4015** words, after a power-loss event, parts of the file that were never
4016** written might end up being altered.) However, non-PSOW behavior is very,
4017** very rare. And asserting PSOW makes a large reduction in the amount
4018** of required I/O for journaling, since a lot of padding is eliminated.
4019** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4020** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004021*/
drhf12b3f62011-12-21 14:42:29 +00004022static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004023 unixFile *pFd = (unixFile*)id;
4024 setDeviceCharacteristics(pFd);
4025 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004026}
4027
dan702eec12014-06-23 10:04:58 +00004028#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004029
dan702eec12014-06-23 10:04:58 +00004030/*
4031** Return the system page size.
4032**
4033** This function should not be called directly by other code in this file.
4034** Instead, it should be called via macro osGetpagesize().
4035*/
4036static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004037#if OS_VXWORKS
4038 return 1024;
4039#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004040 return getpagesize();
4041#else
4042 return (int)sysconf(_SC_PAGESIZE);
4043#endif
4044}
4045
4046#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4047
4048#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004049
4050/*
drhd91c68f2010-05-14 14:52:25 +00004051** Object used to represent an shared memory buffer.
4052**
4053** When multiple threads all reference the same wal-index, each thread
4054** has its own unixShm object, but they all point to a single instance
4055** of this unixShmNode object. In other words, each wal-index is opened
4056** only once per process.
4057**
4058** Each unixShmNode object is connected to a single unixInodeInfo object.
4059** We could coalesce this object into unixInodeInfo, but that would mean
4060** every open file that does not use shared memory (in other words, most
4061** open files) would have to carry around this extra information. So
4062** the unixInodeInfo object contains a pointer to this unixShmNode object
4063** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004064**
4065** unixMutexHeld() must be true when creating or destroying
4066** this object or while reading or writing the following fields:
4067**
4068** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004069**
4070** The following fields are read-only after the object is created:
4071**
4072** fid
4073** zFilename
4074**
drhd91c68f2010-05-14 14:52:25 +00004075** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004076** unixMutexHeld() is true when reading or writing any other field
4077** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004078*/
drhd91c68f2010-05-14 14:52:25 +00004079struct unixShmNode {
4080 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drhd9e5c4f2010-05-12 18:01:39 +00004081 sqlite3_mutex *mutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004082 char *zFilename; /* Name of the mmapped file */
4083 int h; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004084 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004085 u16 nRegion; /* Size of array apRegion */
4086 u8 isReadonly; /* True if read-only */
dan18801912010-06-14 14:07:50 +00004087 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004088 int nRef; /* Number of unixShm objects pointing to this */
4089 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004090#ifdef SQLITE_DEBUG
4091 u8 exclMask; /* Mask of exclusive locks held */
4092 u8 sharedMask; /* Mask of shared locks held */
4093 u8 nextShmId; /* Next available unixShm.id value */
4094#endif
4095};
4096
4097/*
drhd9e5c4f2010-05-12 18:01:39 +00004098** Structure used internally by this VFS to record the state of an
4099** open shared memory connection.
4100**
drhd91c68f2010-05-14 14:52:25 +00004101** The following fields are initialized when this object is created and
4102** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004103**
drhd91c68f2010-05-14 14:52:25 +00004104** unixShm.pFile
4105** unixShm.id
4106**
4107** All other fields are read/write. The unixShm.pFile->mutex must be held
4108** while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004109*/
4110struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004111 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4112 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drhd91c68f2010-05-14 14:52:25 +00004113 u8 hasMutex; /* True if holding the unixShmNode mutex */
drhfd532312011-08-31 18:35:34 +00004114 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004115 u16 sharedMask; /* Mask of shared locks held */
4116 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004117};
4118
4119/*
drhd9e5c4f2010-05-12 18:01:39 +00004120** Constants used for locking
4121*/
drhbd9676c2010-06-23 17:58:38 +00004122#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004123#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004124
drhd9e5c4f2010-05-12 18:01:39 +00004125/*
drh73b64e42010-05-30 19:55:15 +00004126** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004127**
4128** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4129** otherwise.
4130*/
4131static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004132 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004133 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004134 int ofst, /* First byte of the locking range */
4135 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004136){
drhbbf76ee2015-03-10 20:22:35 +00004137 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4138 struct flock f; /* The posix advisory locking structure */
4139 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004140
drhd91c68f2010-05-14 14:52:25 +00004141 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004142 pShmNode = pFile->pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004143 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004144
drh73b64e42010-05-30 19:55:15 +00004145 /* Shared locks never span more than one byte */
4146 assert( n==1 || lockType!=F_RDLCK );
4147
4148 /* Locks are within range */
drhaf19f172015-12-02 17:40:13 +00004149 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004150
drh3cb93392011-03-12 18:10:44 +00004151 if( pShmNode->h>=0 ){
4152 /* Initialize the locking parameters */
4153 memset(&f, 0, sizeof(f));
4154 f.l_type = lockType;
4155 f.l_whence = SEEK_SET;
4156 f.l_start = ofst;
4157 f.l_len = n;
drhd9e5c4f2010-05-12 18:01:39 +00004158
drhdcfb9652015-12-02 00:05:26 +00004159 rc = osFcntl(pShmNode->h, F_SETLK, &f);
drh3cb93392011-03-12 18:10:44 +00004160 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4161 }
drhd9e5c4f2010-05-12 18:01:39 +00004162
4163 /* Update the global lock state and do debug tracing */
4164#ifdef SQLITE_DEBUG
drh73b64e42010-05-30 19:55:15 +00004165 { u16 mask;
drhd9e5c4f2010-05-12 18:01:39 +00004166 OSTRACE(("SHM-LOCK "));
drh693e6712014-01-24 22:58:00 +00004167 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
drhd9e5c4f2010-05-12 18:01:39 +00004168 if( rc==SQLITE_OK ){
4169 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004170 OSTRACE(("unlock %d ok", ofst));
4171 pShmNode->exclMask &= ~mask;
4172 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004173 }else if( lockType==F_RDLCK ){
drh73b64e42010-05-30 19:55:15 +00004174 OSTRACE(("read-lock %d ok", ofst));
4175 pShmNode->exclMask &= ~mask;
4176 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004177 }else{
4178 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004179 OSTRACE(("write-lock %d ok", ofst));
4180 pShmNode->exclMask |= mask;
4181 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004182 }
4183 }else{
4184 if( lockType==F_UNLCK ){
drh73b64e42010-05-30 19:55:15 +00004185 OSTRACE(("unlock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004186 }else if( lockType==F_RDLCK ){
4187 OSTRACE(("read-lock failed"));
4188 }else{
4189 assert( lockType==F_WRLCK );
drh73b64e42010-05-30 19:55:15 +00004190 OSTRACE(("write-lock %d failed", ofst));
drhd9e5c4f2010-05-12 18:01:39 +00004191 }
4192 }
drh20e1f082010-05-31 16:10:12 +00004193 OSTRACE((" - afterwards %03x,%03x\n",
4194 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004195 }
drhd9e5c4f2010-05-12 18:01:39 +00004196#endif
4197
4198 return rc;
4199}
4200
dan781e34c2014-03-20 08:59:47 +00004201/*
dan781e34c2014-03-20 08:59:47 +00004202** Return the minimum number of 32KB shm regions that should be mapped at
4203** a time, assuming that each mapping must be an integer multiple of the
4204** current system page-size.
4205**
4206** Usually, this is 1. The exception seems to be systems that are configured
4207** to use 64KB pages - in this case each mapping must cover at least two
4208** shm regions.
4209*/
4210static int unixShmRegionPerMap(void){
4211 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004212 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004213 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4214 if( pgsz<shmsz ) return 1;
4215 return pgsz/shmsz;
4216}
drhd9e5c4f2010-05-12 18:01:39 +00004217
4218/*
drhd91c68f2010-05-14 14:52:25 +00004219** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004220**
4221** This is not a VFS shared-memory method; it is a utility function called
4222** by VFS shared-memory methods.
4223*/
drhd91c68f2010-05-14 14:52:25 +00004224static void unixShmPurge(unixFile *pFd){
4225 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004226 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004227 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004228 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004229 int i;
drhd91c68f2010-05-14 14:52:25 +00004230 assert( p->pInode==pFd->pInode );
drhdf3aa162011-06-24 11:29:51 +00004231 sqlite3_mutex_free(p->mutex);
dan781e34c2014-03-20 08:59:47 +00004232 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh3cb93392011-03-12 18:10:44 +00004233 if( p->h>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004234 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004235 }else{
4236 sqlite3_free(p->apRegion[i]);
4237 }
dan13a3cb82010-06-11 19:04:21 +00004238 }
dan18801912010-06-14 14:07:50 +00004239 sqlite3_free(p->apRegion);
drh0e9365c2011-03-02 02:08:13 +00004240 if( p->h>=0 ){
4241 robust_close(pFd, p->h, __LINE__);
4242 p->h = -1;
4243 }
drhd91c68f2010-05-14 14:52:25 +00004244 p->pInode->pShmNode = 0;
4245 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004246 }
4247}
4248
4249/*
danda9fe0c2010-07-13 18:44:03 +00004250** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004251** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004252**
drh7234c6d2010-06-19 15:10:09 +00004253** The file used to implement shared-memory is in the same directory
4254** as the open database file and has the same name as the open database
4255** file with the "-shm" suffix added. For example, if the database file
4256** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004257** for shared memory will be called "/home/user1/config.db-shm".
4258**
4259** Another approach to is to use files in /dev/shm or /dev/tmp or an
4260** some other tmpfs mount. But if a file in a different directory
4261** from the database file is used, then differing access permissions
4262** or a chroot() might cause two different processes on the same
4263** database to end up using different files for shared memory -
4264** meaning that their memory would not really be shared - resulting
4265** in database corruption. Nevertheless, this tmpfs file usage
4266** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4267** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4268** option results in an incompatible build of SQLite; builds of SQLite
4269** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4270** same database file at the same time, database corruption will likely
4271** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4272** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004273**
4274** When opening a new shared-memory file, if no other instances of that
4275** file are currently open, in this process or in other processes, then
4276** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004277**
4278** If the original database file (pDbFd) is using the "unix-excl" VFS
4279** that means that an exclusive lock is held on the database file and
4280** that no other processes are able to read or write the database. In
4281** that case, we do not really need shared memory. No shared memory
4282** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004283*/
danda9fe0c2010-07-13 18:44:03 +00004284static int unixOpenSharedMemory(unixFile *pDbFd){
4285 struct unixShm *p = 0; /* The connection to be opened */
4286 struct unixShmNode *pShmNode; /* The underlying mmapped file */
4287 int rc; /* Result code */
4288 unixInodeInfo *pInode; /* The inode of fd */
4289 char *zShmFilename; /* Name of the file used for SHM */
4290 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004291
danda9fe0c2010-07-13 18:44:03 +00004292 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004293 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004294 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004295 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004296 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004297
danda9fe0c2010-07-13 18:44:03 +00004298 /* Check to see if a unixShmNode object already exists. Reuse an existing
4299 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004300 */
4301 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004302 pInode = pDbFd->pInode;
4303 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004304 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004305 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004306#ifndef SQLITE_SHM_DIRECTORY
4307 const char *zBasePath = pDbFd->zPath;
4308#endif
danddb0ac42010-07-14 14:48:58 +00004309
4310 /* Call fstat() to figure out the permissions on the database file. If
4311 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004312 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004313 */
drhf3b1ed02015-12-02 13:11:03 +00004314 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004315 rc = SQLITE_IOERR_FSTAT;
4316 goto shm_open_err;
4317 }
4318
drha4ced192010-07-15 18:32:40 +00004319#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004320 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004321#else
drh4bf66fd2015-02-19 02:43:02 +00004322 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004323#endif
drhf3cdcdc2015-04-29 16:50:28 +00004324 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004325 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004326 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004327 goto shm_open_err;
4328 }
drh9cb5a0d2012-01-05 21:19:54 +00004329 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
drh7234c6d2010-06-19 15:10:09 +00004330 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004331#ifdef SQLITE_SHM_DIRECTORY
4332 sqlite3_snprintf(nShmFilename, zShmFilename,
4333 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4334 (u32)sStat.st_ino, (u32)sStat.st_dev);
4335#else
drh4bf66fd2015-02-19 02:43:02 +00004336 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
drh81cc5162011-05-17 20:36:21 +00004337 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
drha4ced192010-07-15 18:32:40 +00004338#endif
drhd91c68f2010-05-14 14:52:25 +00004339 pShmNode->h = -1;
4340 pDbFd->pInode->pShmNode = pShmNode;
4341 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004342 if( sqlite3GlobalConfig.bCoreMutex ){
4343 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4344 if( pShmNode->mutex==0 ){
4345 rc = SQLITE_NOMEM_BKPT;
4346 goto shm_open_err;
4347 }
drhd91c68f2010-05-14 14:52:25 +00004348 }
drhd9e5c4f2010-05-12 18:01:39 +00004349
drh3cb93392011-03-12 18:10:44 +00004350 if( pInode->bProcessLock==0 ){
drh3ec4a0c2011-10-11 18:18:54 +00004351 int openFlags = O_RDWR | O_CREAT;
drh92913722011-12-23 00:07:33 +00004352 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh3ec4a0c2011-10-11 18:18:54 +00004353 openFlags = O_RDONLY;
4354 pShmNode->isReadonly = 1;
4355 }
4356 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
drh3cb93392011-03-12 18:10:44 +00004357 if( pShmNode->h<0 ){
drhc96d1e72012-02-11 18:51:34 +00004358 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
4359 goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004360 }
drhac7c3ac2012-02-11 19:23:48 +00004361
4362 /* If this process is running as root, make sure that the SHM file
4363 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004364 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004365 */
drh6226ca22015-11-24 15:06:28 +00004366 robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
drh3cb93392011-03-12 18:10:44 +00004367
4368 /* Check to see if another process is holding the dead-man switch.
drh66dfec8b2011-06-01 20:01:49 +00004369 ** If not, truncate the file to zero length.
4370 */
4371 rc = SQLITE_OK;
drhbbf76ee2015-03-10 20:22:35 +00004372 if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
drh66dfec8b2011-06-01 20:01:49 +00004373 if( robust_ftruncate(pShmNode->h, 0) ){
4374 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
drh3cb93392011-03-12 18:10:44 +00004375 }
4376 }
drh66dfec8b2011-06-01 20:01:49 +00004377 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004378 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
drh66dfec8b2011-06-01 20:01:49 +00004379 }
4380 if( rc ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004381 }
drhd9e5c4f2010-05-12 18:01:39 +00004382 }
4383
drhd91c68f2010-05-14 14:52:25 +00004384 /* Make the new connection a child of the unixShmNode */
4385 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004386#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004387 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004388#endif
drhd91c68f2010-05-14 14:52:25 +00004389 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004390 pDbFd->pShm = p;
4391 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004392
4393 /* The reference count on pShmNode has already been incremented under
4394 ** the cover of the unixEnterMutex() mutex and the pointer from the
4395 ** new (struct unixShm) object to the pShmNode has been set. All that is
4396 ** left to do is to link the new object into the linked list starting
4397 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
4398 ** mutex.
4399 */
4400 sqlite3_mutex_enter(pShmNode->mutex);
4401 p->pNext = pShmNode->pFirst;
4402 pShmNode->pFirst = p;
4403 sqlite3_mutex_leave(pShmNode->mutex);
drhd9e5c4f2010-05-12 18:01:39 +00004404 return SQLITE_OK;
4405
4406 /* Jump here on any error */
4407shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004408 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004409 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004410 unixLeaveMutex();
4411 return rc;
4412}
4413
4414/*
danda9fe0c2010-07-13 18:44:03 +00004415** This function is called to obtain a pointer to region iRegion of the
4416** shared-memory associated with the database file fd. Shared-memory regions
4417** are numbered starting from zero. Each shared-memory region is szRegion
4418** bytes in size.
4419**
4420** If an error occurs, an error code is returned and *pp is set to NULL.
4421**
4422** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4423** region has not been allocated (by any client, including one running in a
4424** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4425** bExtend is non-zero and the requested shared-memory region has not yet
4426** been allocated, it is allocated by this function.
4427**
4428** If the shared-memory region has already been allocated or is allocated by
4429** this call as described above, then it is mapped into this processes
4430** address space (if it is not already), *pp is set to point to the mapped
4431** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004432*/
danda9fe0c2010-07-13 18:44:03 +00004433static int unixShmMap(
4434 sqlite3_file *fd, /* Handle open on database file */
4435 int iRegion, /* Region to retrieve */
4436 int szRegion, /* Size of regions */
4437 int bExtend, /* True to extend file if necessary */
4438 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004439){
danda9fe0c2010-07-13 18:44:03 +00004440 unixFile *pDbFd = (unixFile*)fd;
4441 unixShm *p;
4442 unixShmNode *pShmNode;
4443 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004444 int nShmPerMap = unixShmRegionPerMap();
4445 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004446
danda9fe0c2010-07-13 18:44:03 +00004447 /* If the shared-memory file has not yet been opened, open it now. */
4448 if( pDbFd->pShm==0 ){
4449 rc = unixOpenSharedMemory(pDbFd);
4450 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004451 }
drhd9e5c4f2010-05-12 18:01:39 +00004452
danda9fe0c2010-07-13 18:44:03 +00004453 p = pDbFd->pShm;
4454 pShmNode = p->pShmNode;
4455 sqlite3_mutex_enter(pShmNode->mutex);
4456 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004457 assert( pShmNode->pInode==pDbFd->pInode );
4458 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4459 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004460
dan781e34c2014-03-20 08:59:47 +00004461 /* Minimum number of regions required to be mapped. */
4462 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4463
4464 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004465 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004466 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004467 struct stat sStat; /* Used by fstat() */
4468
4469 pShmNode->szRegion = szRegion;
4470
drh3cb93392011-03-12 18:10:44 +00004471 if( pShmNode->h>=0 ){
4472 /* The requested region is not mapped into this processes address space.
4473 ** Check to see if it has been allocated (i.e. if the wal-index file is
4474 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004475 */
drh3cb93392011-03-12 18:10:44 +00004476 if( osFstat(pShmNode->h, &sStat) ){
4477 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004478 goto shmpage_out;
4479 }
drh3cb93392011-03-12 18:10:44 +00004480
4481 if( sStat.st_size<nByte ){
4482 /* The requested memory region does not exist. If bExtend is set to
4483 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004484 */
dan47a2b4a2013-04-26 16:09:29 +00004485 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004486 goto shmpage_out;
4487 }
dan47a2b4a2013-04-26 16:09:29 +00004488
4489 /* Alternatively, if bExtend is true, extend the file. Do this by
4490 ** writing a single byte to the end of each (OS) page being
4491 ** allocated or extended. Technically, we need only write to the
4492 ** last page in order to extend the file. But writing to all new
4493 ** pages forces the OS to allocate them immediately, which reduces
4494 ** the chances of SIGBUS while accessing the mapped region later on.
4495 */
4496 else{
4497 static const int pgsz = 4096;
4498 int iPg;
4499
4500 /* Write to the last byte of each newly allocated or extended page */
4501 assert( (nByte % pgsz)==0 );
4502 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004503 int x = 0;
4504 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004505 const char *zFile = pShmNode->zFilename;
4506 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4507 goto shmpage_out;
4508 }
4509 }
drh3cb93392011-03-12 18:10:44 +00004510 }
4511 }
danda9fe0c2010-07-13 18:44:03 +00004512 }
4513
4514 /* Map the requested memory region into this processes address space. */
4515 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004516 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004517 );
4518 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004519 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004520 goto shmpage_out;
4521 }
4522 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004523 while( pShmNode->nRegion<nReqRegion ){
4524 int nMap = szRegion*nShmPerMap;
4525 int i;
drh3cb93392011-03-12 18:10:44 +00004526 void *pMem;
4527 if( pShmNode->h>=0 ){
dan781e34c2014-03-20 08:59:47 +00004528 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004529 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh5a05be12012-10-09 18:51:44 +00004530 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004531 );
4532 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004533 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004534 goto shmpage_out;
4535 }
4536 }else{
drhf3cdcdc2015-04-29 16:50:28 +00004537 pMem = sqlite3_malloc64(szRegion);
drh3cb93392011-03-12 18:10:44 +00004538 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004539 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004540 goto shmpage_out;
4541 }
4542 memset(pMem, 0, szRegion);
danda9fe0c2010-07-13 18:44:03 +00004543 }
dan781e34c2014-03-20 08:59:47 +00004544
4545 for(i=0; i<nShmPerMap; i++){
4546 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4547 }
4548 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004549 }
4550 }
4551
4552shmpage_out:
4553 if( pShmNode->nRegion>iRegion ){
4554 *pp = pShmNode->apRegion[iRegion];
4555 }else{
4556 *pp = 0;
4557 }
drh66dfec8b2011-06-01 20:01:49 +00004558 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
danda9fe0c2010-07-13 18:44:03 +00004559 sqlite3_mutex_leave(pShmNode->mutex);
4560 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004561}
4562
4563/*
drhd9e5c4f2010-05-12 18:01:39 +00004564** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004565**
4566** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4567** different here than in posix. In xShmLock(), one can go from unlocked
4568** to shared and back or from unlocked to exclusive and back. But one may
4569** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004570*/
4571static int unixShmLock(
4572 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004573 int ofst, /* First lock to acquire or release */
4574 int n, /* Number of locks to acquire or release */
4575 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004576){
drh73b64e42010-05-30 19:55:15 +00004577 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4578 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4579 unixShm *pX; /* For looping over all siblings */
4580 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4581 int rc = SQLITE_OK; /* Result code */
4582 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004583
drhd91c68f2010-05-14 14:52:25 +00004584 assert( pShmNode==pDbFd->pInode->pShmNode );
4585 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004586 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004587 assert( n>=1 );
4588 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4589 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4590 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4591 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4592 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh3cb93392011-03-12 18:10:44 +00004593 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
4594 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004595
drhc99597c2010-05-31 01:41:15 +00004596 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004597 assert( n>1 || mask==(1<<ofst) );
drhd91c68f2010-05-14 14:52:25 +00004598 sqlite3_mutex_enter(pShmNode->mutex);
drh73b64e42010-05-30 19:55:15 +00004599 if( flags & SQLITE_SHM_UNLOCK ){
4600 u16 allMask = 0; /* Mask of locks held by siblings */
4601
4602 /* See if any siblings hold this same lock */
4603 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4604 if( pX==p ) continue;
4605 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4606 allMask |= pX->sharedMask;
4607 }
4608
4609 /* Unlock the system-level locks */
4610 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004611 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004612 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004613 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004614 }
drh73b64e42010-05-30 19:55:15 +00004615
4616 /* Undo the local locks */
4617 if( rc==SQLITE_OK ){
4618 p->exclMask &= ~mask;
4619 p->sharedMask &= ~mask;
4620 }
4621 }else if( flags & SQLITE_SHM_SHARED ){
4622 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4623
4624 /* Find out which shared locks are already held by sibling connections.
4625 ** If any sibling already holds an exclusive lock, go ahead and return
4626 ** SQLITE_BUSY.
4627 */
4628 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004629 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004630 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004631 break;
4632 }
4633 allShared |= pX->sharedMask;
4634 }
4635
4636 /* Get shared locks at the system level, if necessary */
4637 if( rc==SQLITE_OK ){
4638 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004639 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004640 }else{
drh73b64e42010-05-30 19:55:15 +00004641 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004642 }
drhd9e5c4f2010-05-12 18:01:39 +00004643 }
drh73b64e42010-05-30 19:55:15 +00004644
4645 /* Get the local shared locks */
4646 if( rc==SQLITE_OK ){
4647 p->sharedMask |= mask;
4648 }
4649 }else{
4650 /* Make sure no sibling connections hold locks that will block this
4651 ** lock. If any do, return SQLITE_BUSY right away.
4652 */
4653 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004654 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4655 rc = SQLITE_BUSY;
4656 break;
4657 }
4658 }
4659
4660 /* Get the exclusive locks at the system level. Then if successful
4661 ** also mark the local connection as being locked.
4662 */
4663 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004664 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004665 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004666 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004667 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004668 }
drhd9e5c4f2010-05-12 18:01:39 +00004669 }
4670 }
drhd91c68f2010-05-14 14:52:25 +00004671 sqlite3_mutex_leave(pShmNode->mutex);
drh20e1f082010-05-31 16:10:12 +00004672 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004673 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004674 return rc;
4675}
4676
drh286a2882010-05-20 23:51:06 +00004677/*
4678** Implement a memory barrier or memory fence on shared memory.
4679**
4680** All loads and stores begun before the barrier must complete before
4681** any load or store begun after the barrier.
4682*/
4683static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004684 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004685){
drhff828942010-06-26 21:34:06 +00004686 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004687 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
4688 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004689 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004690}
4691
dan18801912010-06-14 14:07:50 +00004692/*
danda9fe0c2010-07-13 18:44:03 +00004693** Close a connection to shared-memory. Delete the underlying
4694** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004695**
4696** If there is no shared memory associated with the connection then this
4697** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004698*/
danda9fe0c2010-07-13 18:44:03 +00004699static int unixShmUnmap(
4700 sqlite3_file *fd, /* The underlying database file */
4701 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004702){
danda9fe0c2010-07-13 18:44:03 +00004703 unixShm *p; /* The connection to be closed */
4704 unixShmNode *pShmNode; /* The underlying shared-memory file */
4705 unixShm **pp; /* For looping over sibling connections */
4706 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004707
danda9fe0c2010-07-13 18:44:03 +00004708 pDbFd = (unixFile*)fd;
4709 p = pDbFd->pShm;
4710 if( p==0 ) return SQLITE_OK;
4711 pShmNode = p->pShmNode;
4712
4713 assert( pShmNode==pDbFd->pInode->pShmNode );
4714 assert( pShmNode->pInode==pDbFd->pInode );
4715
4716 /* Remove connection p from the set of connections associated
4717 ** with pShmNode */
dan18801912010-06-14 14:07:50 +00004718 sqlite3_mutex_enter(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004719 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4720 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004721
danda9fe0c2010-07-13 18:44:03 +00004722 /* Free the connection p */
4723 sqlite3_free(p);
4724 pDbFd->pShm = 0;
dan18801912010-06-14 14:07:50 +00004725 sqlite3_mutex_leave(pShmNode->mutex);
danda9fe0c2010-07-13 18:44:03 +00004726
4727 /* If pShmNode->nRef has reached 0, then close the underlying
4728 ** shared-memory file, too */
4729 unixEnterMutex();
4730 assert( pShmNode->nRef>0 );
4731 pShmNode->nRef--;
4732 if( pShmNode->nRef==0 ){
drh4bf66fd2015-02-19 02:43:02 +00004733 if( deleteFlag && pShmNode->h>=0 ){
4734 osUnlink(pShmNode->zFilename);
4735 }
danda9fe0c2010-07-13 18:44:03 +00004736 unixShmPurge(pDbFd);
4737 }
4738 unixLeaveMutex();
4739
4740 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004741}
drh286a2882010-05-20 23:51:06 +00004742
danda9fe0c2010-07-13 18:44:03 +00004743
drhd9e5c4f2010-05-12 18:01:39 +00004744#else
drh6b017cc2010-06-14 18:01:46 +00004745# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004746# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004747# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004748# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004749#endif /* #ifndef SQLITE_OMIT_WAL */
4750
mistachkine98844f2013-08-24 00:59:24 +00004751#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004752/*
danaef49d72013-03-25 16:28:54 +00004753** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004754*/
danf23da962013-03-23 21:00:41 +00004755static void unixUnmapfile(unixFile *pFd){
4756 assert( pFd->nFetchOut==0 );
4757 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004758 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004759 pFd->pMapRegion = 0;
4760 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004761 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004762 }
4763}
dan5d8a1372013-03-19 19:28:06 +00004764
danaef49d72013-03-25 16:28:54 +00004765/*
dane6ecd662013-04-01 17:56:59 +00004766** Attempt to set the size of the memory mapping maintained by file
4767** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4768**
4769** If successful, this function sets the following variables:
4770**
4771** unixFile.pMapRegion
4772** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004773** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004774**
4775** If unsuccessful, an error message is logged via sqlite3_log() and
4776** the three variables above are zeroed. In this case SQLite should
4777** continue accessing the database using the xRead() and xWrite()
4778** methods.
4779*/
4780static void unixRemapfile(
4781 unixFile *pFd, /* File descriptor object */
4782 i64 nNew /* Required mapping size */
4783){
dan4ff7bc42013-04-02 12:04:09 +00004784 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004785 int h = pFd->h; /* File descriptor open on db file */
4786 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004787 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004788 u8 *pNew = 0; /* Location of new mapping */
4789 int flags = PROT_READ; /* Flags to pass to mmap() */
4790
4791 assert( pFd->nFetchOut==0 );
4792 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00004793 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00004794 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00004795 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00004796 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00004797
danfe33e392015-11-17 20:56:06 +00004798#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00004799 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00004800#endif
dane6ecd662013-04-01 17:56:59 +00004801
4802 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00004803#if HAVE_MREMAP
4804 i64 nReuse = pFd->mmapSize;
4805#else
danbc760632014-03-20 09:42:09 +00004806 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00004807 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00004808#endif
dane6ecd662013-04-01 17:56:59 +00004809 u8 *pReq = &pOrig[nReuse];
4810
4811 /* Unmap any pages of the existing mapping that cannot be reused. */
4812 if( nReuse!=nOrig ){
4813 osMunmap(pReq, nOrig-nReuse);
4814 }
4815
4816#if HAVE_MREMAP
4817 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00004818 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00004819#else
4820 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
4821 if( pNew!=MAP_FAILED ){
4822 if( pNew!=pReq ){
4823 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00004824 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00004825 }else{
4826 pNew = pOrig;
4827 }
4828 }
4829#endif
4830
dan48ccef82013-04-02 20:55:01 +00004831 /* The attempt to extend the existing mapping failed. Free it. */
4832 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00004833 osMunmap(pOrig, nReuse);
4834 }
4835 }
4836
4837 /* If pNew is still NULL, try to create an entirely new mapping. */
4838 if( pNew==0 ){
4839 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00004840 }
4841
dan4ff7bc42013-04-02 12:04:09 +00004842 if( pNew==MAP_FAILED ){
4843 pNew = 0;
4844 nNew = 0;
4845 unixLogError(SQLITE_OK, zErr, pFd->zPath);
4846
4847 /* If the mmap() above failed, assume that all subsequent mmap() calls
4848 ** will probably fail too. Fall back to using xRead/xWrite exclusively
4849 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00004850 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00004851 }
dane6ecd662013-04-01 17:56:59 +00004852 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00004853 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00004854}
4855
4856/*
danaef49d72013-03-25 16:28:54 +00004857** Memory map or remap the file opened by file-descriptor pFd (if the file
4858** is already mapped, the existing mapping is replaced by the new). Or, if
4859** there already exists a mapping for this file, and there are still
4860** outstanding xFetch() references to it, this function is a no-op.
4861**
4862** If parameter nByte is non-negative, then it is the requested size of
4863** the mapping to create. Otherwise, if nByte is less than zero, then the
4864** requested size is the size of the file on disk. The actual size of the
4865** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00004866** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00004867**
4868** SQLITE_OK is returned if no error occurs (even if the mapping is not
4869** recreated as a result of outstanding references) or an SQLite error
4870** code otherwise.
4871*/
drhf3b1ed02015-12-02 13:11:03 +00004872static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00004873 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00004874 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004875 if( pFd->nFetchOut>0 ) return SQLITE_OK;
4876
4877 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00004878 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00004879 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00004880 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00004881 }
drh3044b512014-06-16 16:41:52 +00004882 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00004883 }
drh9b4c59f2013-04-15 17:03:42 +00004884 if( nMap>pFd->mmapSizeMax ){
4885 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00004886 }
4887
drh333e6ca2015-12-02 15:44:39 +00004888 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00004889 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00004890 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00004891 }
4892
danf23da962013-03-23 21:00:41 +00004893 return SQLITE_OK;
4894}
mistachkine98844f2013-08-24 00:59:24 +00004895#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00004896
danaef49d72013-03-25 16:28:54 +00004897/*
4898** If possible, return a pointer to a mapping of file fd starting at offset
4899** iOff. The mapping must be valid for at least nAmt bytes.
4900**
4901** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
4902** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
4903** Finally, if an error does occur, return an SQLite error code. The final
4904** value of *pp is undefined in this case.
4905**
4906** If this function does return a pointer, the caller must eventually
4907** release the reference by calling unixUnfetch().
4908*/
danf23da962013-03-23 21:00:41 +00004909static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00004910#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00004911 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00004912#endif
danf23da962013-03-23 21:00:41 +00004913 *pp = 0;
4914
drh9b4c59f2013-04-15 17:03:42 +00004915#if SQLITE_MAX_MMAP_SIZE>0
4916 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00004917 if( pFd->pMapRegion==0 ){
4918 int rc = unixMapfile(pFd, -1);
4919 if( rc!=SQLITE_OK ) return rc;
4920 }
4921 if( pFd->mmapSize >= iOff+nAmt ){
4922 *pp = &((u8 *)pFd->pMapRegion)[iOff];
4923 pFd->nFetchOut++;
4924 }
4925 }
drh6e0b6d52013-04-09 16:19:20 +00004926#endif
danf23da962013-03-23 21:00:41 +00004927 return SQLITE_OK;
4928}
4929
danaef49d72013-03-25 16:28:54 +00004930/*
dandf737fe2013-03-25 17:00:24 +00004931** If the third argument is non-NULL, then this function releases a
4932** reference obtained by an earlier call to unixFetch(). The second
4933** argument passed to this function must be the same as the corresponding
4934** argument that was passed to the unixFetch() invocation.
4935**
4936** Or, if the third argument is NULL, then this function is being called
4937** to inform the VFS layer that, according to POSIX, any existing mapping
4938** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00004939*/
dandf737fe2013-03-25 17:00:24 +00004940static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00004941#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00004942 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00004943 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00004944
danaef49d72013-03-25 16:28:54 +00004945 /* If p==0 (unmap the entire file) then there must be no outstanding
4946 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
4947 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00004948 assert( (p==0)==(pFd->nFetchOut==0) );
4949
dandf737fe2013-03-25 17:00:24 +00004950 /* If p!=0, it must match the iOff value. */
4951 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
4952
danf23da962013-03-23 21:00:41 +00004953 if( p ){
4954 pFd->nFetchOut--;
4955 }else{
4956 unixUnmapfile(pFd);
4957 }
4958
4959 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00004960#else
4961 UNUSED_PARAMETER(fd);
4962 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00004963 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00004964#endif
danf23da962013-03-23 21:00:41 +00004965 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00004966}
4967
4968/*
drh734c9862008-11-28 15:37:20 +00004969** Here ends the implementation of all sqlite3_file methods.
4970**
4971********************** End sqlite3_file Methods *******************************
4972******************************************************************************/
4973
4974/*
drh6b9d6dd2008-12-03 19:34:47 +00004975** This division contains definitions of sqlite3_io_methods objects that
4976** implement various file locking strategies. It also contains definitions
4977** of "finder" functions. A finder-function is used to locate the appropriate
4978** sqlite3_io_methods object for a particular database file. The pAppData
4979** field of the sqlite3_vfs VFS objects are initialized to be pointers to
4980** the correct finder-function for that VFS.
4981**
4982** Most finder functions return a pointer to a fixed sqlite3_io_methods
4983** object. The only interesting finder-function is autolockIoFinder, which
4984** looks at the filesystem type and tries to guess the best locking
4985** strategy from that.
4986**
peter.d.reid60ec9142014-09-06 16:39:46 +00004987** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00004988**
4989** (1) The real finder-function named "FImpt()".
4990**
dane946c392009-08-22 11:39:46 +00004991** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00004992**
4993**
4994** A pointer to the F pointer is used as the pAppData value for VFS
4995** objects. We have to do this instead of letting pAppData point
4996** directly at the finder-function since C90 rules prevent a void*
4997** from be cast into a function pointer.
4998**
drh6b9d6dd2008-12-03 19:34:47 +00004999**
drh7708e972008-11-29 00:56:52 +00005000** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005001**
drh7708e972008-11-29 00:56:52 +00005002** * A constant sqlite3_io_methods object call METHOD that has locking
5003** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5004**
5005** * An I/O method finder function called FINDER that returns a pointer
5006** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005007*/
drhe6d41732015-02-21 00:49:00 +00005008#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005009static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005010 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005011 CLOSE, /* xClose */ \
5012 unixRead, /* xRead */ \
5013 unixWrite, /* xWrite */ \
5014 unixTruncate, /* xTruncate */ \
5015 unixSync, /* xSync */ \
5016 unixFileSize, /* xFileSize */ \
5017 LOCK, /* xLock */ \
5018 UNLOCK, /* xUnlock */ \
5019 CKLOCK, /* xCheckReservedLock */ \
5020 unixFileControl, /* xFileControl */ \
5021 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005022 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005023 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005024 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005025 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005026 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005027 unixFetch, /* xFetch */ \
5028 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005029}; \
drh0c2694b2009-09-03 16:23:44 +00005030static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5031 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005032 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005033} \
drh0c2694b2009-09-03 16:23:44 +00005034static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005035 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005036
5037/*
5038** Here are all of the sqlite3_io_methods objects for each of the
5039** locking strategies. Functions that return pointers to these methods
5040** are also created.
5041*/
5042IOMETHODS(
5043 posixIoFinder, /* Finder function name */
5044 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005045 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005046 unixClose, /* xClose method */
5047 unixLock, /* xLock method */
5048 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005049 unixCheckReservedLock, /* xCheckReservedLock method */
5050 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005051)
drh7708e972008-11-29 00:56:52 +00005052IOMETHODS(
5053 nolockIoFinder, /* Finder function name */
5054 nolockIoMethods, /* sqlite3_io_methods object name */
drh142341c2014-09-19 19:00:48 +00005055 3, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005056 nolockClose, /* xClose method */
5057 nolockLock, /* xLock method */
5058 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005059 nolockCheckReservedLock, /* xCheckReservedLock method */
5060 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005061)
drh7708e972008-11-29 00:56:52 +00005062IOMETHODS(
5063 dotlockIoFinder, /* Finder function name */
5064 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005065 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005066 dotlockClose, /* xClose method */
5067 dotlockLock, /* xLock method */
5068 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005069 dotlockCheckReservedLock, /* xCheckReservedLock method */
5070 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005071)
drh7708e972008-11-29 00:56:52 +00005072
drhe89b2912015-03-03 20:42:01 +00005073#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005074IOMETHODS(
5075 flockIoFinder, /* Finder function name */
5076 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005077 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005078 flockClose, /* xClose method */
5079 flockLock, /* xLock method */
5080 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005081 flockCheckReservedLock, /* xCheckReservedLock method */
5082 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005083)
drh7708e972008-11-29 00:56:52 +00005084#endif
5085
drh6c7d5c52008-11-21 20:32:33 +00005086#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005087IOMETHODS(
5088 semIoFinder, /* Finder function name */
5089 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005090 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005091 semXClose, /* xClose method */
5092 semXLock, /* xLock method */
5093 semXUnlock, /* xUnlock method */
5094 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005095 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005096)
aswiftaebf4132008-11-21 00:10:35 +00005097#endif
drh7708e972008-11-29 00:56:52 +00005098
drhd2cb50b2009-01-09 21:41:17 +00005099#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005100IOMETHODS(
5101 afpIoFinder, /* Finder function name */
5102 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005103 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005104 afpClose, /* xClose method */
5105 afpLock, /* xLock method */
5106 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005107 afpCheckReservedLock, /* xCheckReservedLock method */
5108 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005109)
drh715ff302008-12-03 22:32:44 +00005110#endif
5111
5112/*
5113** The proxy locking method is a "super-method" in the sense that it
5114** opens secondary file descriptors for the conch and lock files and
5115** it uses proxy, dot-file, AFP, and flock() locking methods on those
5116** secondary files. For this reason, the division that implements
5117** proxy locking is located much further down in the file. But we need
5118** to go ahead and define the sqlite3_io_methods and finder function
5119** for proxy locking here. So we forward declare the I/O methods.
5120*/
drhd2cb50b2009-01-09 21:41:17 +00005121#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005122static int proxyClose(sqlite3_file*);
5123static int proxyLock(sqlite3_file*, int);
5124static int proxyUnlock(sqlite3_file*, int);
5125static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005126IOMETHODS(
5127 proxyIoFinder, /* Finder function name */
5128 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005129 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005130 proxyClose, /* xClose method */
5131 proxyLock, /* xLock method */
5132 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005133 proxyCheckReservedLock, /* xCheckReservedLock method */
5134 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005135)
aswiftaebf4132008-11-21 00:10:35 +00005136#endif
drh7708e972008-11-29 00:56:52 +00005137
drh7ed97b92010-01-20 13:07:21 +00005138/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5139#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5140IOMETHODS(
5141 nfsIoFinder, /* Finder function name */
5142 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005143 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005144 unixClose, /* xClose method */
5145 unixLock, /* xLock method */
5146 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005147 unixCheckReservedLock, /* xCheckReservedLock method */
5148 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005149)
5150#endif
drh7708e972008-11-29 00:56:52 +00005151
drhd2cb50b2009-01-09 21:41:17 +00005152#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005153/*
drh6b9d6dd2008-12-03 19:34:47 +00005154** This "finder" function attempts to determine the best locking strategy
5155** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005156** object that implements that strategy.
5157**
5158** This is for MacOSX only.
5159*/
drh1875f7a2008-12-08 18:19:17 +00005160static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005161 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005162 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005163){
5164 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005165 const char *zFilesystem; /* Filesystem type name */
5166 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005167 } aMap[] = {
5168 { "hfs", &posixIoMethods },
5169 { "ufs", &posixIoMethods },
5170 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005171 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005172 { "webdav", &nolockIoMethods },
5173 { 0, 0 }
5174 };
5175 int i;
5176 struct statfs fsInfo;
5177 struct flock lockInfo;
5178
5179 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005180 /* If filePath==NULL that means we are dealing with a transient file
5181 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005182 return &nolockIoMethods;
5183 }
5184 if( statfs(filePath, &fsInfo) != -1 ){
5185 if( fsInfo.f_flags & MNT_RDONLY ){
5186 return &nolockIoMethods;
5187 }
5188 for(i=0; aMap[i].zFilesystem; i++){
5189 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5190 return aMap[i].pMethods;
5191 }
5192 }
5193 }
5194
5195 /* Default case. Handles, amongst others, "nfs".
5196 ** Test byte-range lock using fcntl(). If the call succeeds,
5197 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005198 */
drh7708e972008-11-29 00:56:52 +00005199 lockInfo.l_len = 1;
5200 lockInfo.l_start = 0;
5201 lockInfo.l_whence = SEEK_SET;
5202 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005203 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005204 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5205 return &nfsIoMethods;
5206 } else {
5207 return &posixIoMethods;
5208 }
drh7708e972008-11-29 00:56:52 +00005209 }else{
5210 return &dotlockIoMethods;
5211 }
5212}
drh0c2694b2009-09-03 16:23:44 +00005213static const sqlite3_io_methods
5214 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005215
drhd2cb50b2009-01-09 21:41:17 +00005216#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005217
drhe89b2912015-03-03 20:42:01 +00005218#if OS_VXWORKS
5219/*
5220** This "finder" function for VxWorks checks to see if posix advisory
5221** locking works. If it does, then that is what is used. If it does not
5222** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005223*/
drhe89b2912015-03-03 20:42:01 +00005224static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005225 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005226 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005227){
5228 struct flock lockInfo;
5229
5230 if( !filePath ){
5231 /* If filePath==NULL that means we are dealing with a transient file
5232 ** that does not need to be locked. */
5233 return &nolockIoMethods;
5234 }
5235
5236 /* Test if fcntl() is supported and use POSIX style locks.
5237 ** Otherwise fall back to the named semaphore method.
5238 */
5239 lockInfo.l_len = 1;
5240 lockInfo.l_start = 0;
5241 lockInfo.l_whence = SEEK_SET;
5242 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005243 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005244 return &posixIoMethods;
5245 }else{
5246 return &semIoMethods;
5247 }
5248}
drh0c2694b2009-09-03 16:23:44 +00005249static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005250 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005251
drhe89b2912015-03-03 20:42:01 +00005252#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005253
drh7708e972008-11-29 00:56:52 +00005254/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005255** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005256*/
drh0c2694b2009-09-03 16:23:44 +00005257typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005258
aswiftaebf4132008-11-21 00:10:35 +00005259
drh734c9862008-11-28 15:37:20 +00005260/****************************************************************************
5261**************************** sqlite3_vfs methods ****************************
5262**
5263** This division contains the implementation of methods on the
5264** sqlite3_vfs object.
5265*/
5266
danielk1977a3d4c882007-03-23 10:08:38 +00005267/*
danielk1977e339d652008-06-28 11:23:00 +00005268** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005269*/
5270static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005271 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005272 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005273 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005274 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005275 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005276){
drh7708e972008-11-29 00:56:52 +00005277 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005278 unixFile *pNew = (unixFile *)pId;
5279 int rc = SQLITE_OK;
5280
drh8af6c222010-05-14 12:43:01 +00005281 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005282
dan00157392010-10-05 11:33:15 +00005283 /* Usually the path zFilename should not be a relative pathname. The
5284 ** exception is when opening the proxy "conch" file in builds that
5285 ** include the special Apple locking styles.
5286 */
dan00157392010-10-05 11:33:15 +00005287#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drhf7f55ed2010-10-05 18:22:47 +00005288 assert( zFilename==0 || zFilename[0]=='/'
5289 || pVfs->pAppData==(void*)&autolockIoFinder );
5290#else
5291 assert( zFilename==0 || zFilename[0]=='/' );
dan00157392010-10-05 11:33:15 +00005292#endif
dan00157392010-10-05 11:33:15 +00005293
drhb07028f2011-10-14 21:49:18 +00005294 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005295 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005296
drh308c2a52010-05-14 11:30:18 +00005297 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005298 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005299 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005300 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005301 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005302#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005303 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005304#endif
drhc02a43a2012-01-10 23:18:38 +00005305 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5306 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005307 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005308 }
drh503a6862013-03-01 01:07:17 +00005309 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005310 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005311 }
drh339eb0b2008-03-07 15:34:11 +00005312
drh6c7d5c52008-11-21 20:32:33 +00005313#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005314 pNew->pId = vxworksFindFileId(zFilename);
5315 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005316 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005317 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005318 }
5319#endif
5320
drhc02a43a2012-01-10 23:18:38 +00005321 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005322 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005323 }else{
drh0c2694b2009-09-03 16:23:44 +00005324 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005325#if SQLITE_ENABLE_LOCKING_STYLE
5326 /* Cache zFilename in the locking context (AFP and dotlock override) for
5327 ** proxyLock activation is possible (remote proxy is based on db name)
5328 ** zFilename remains valid until file is closed, to support */
5329 pNew->lockingContext = (void*)zFilename;
5330#endif
drhda0e7682008-07-30 15:27:54 +00005331 }
danielk1977e339d652008-06-28 11:23:00 +00005332
drh7ed97b92010-01-20 13:07:21 +00005333 if( pLockingStyle == &posixIoMethods
5334#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5335 || pLockingStyle == &nfsIoMethods
5336#endif
5337 ){
drh7708e972008-11-29 00:56:52 +00005338 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005339 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005340 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005341 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005342 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005343 ** in two scenarios:
5344 **
5345 ** (a) A call to fstat() failed.
5346 ** (b) A malloc failed.
5347 **
5348 ** Scenario (b) may only occur if the process is holding no other
5349 ** file descriptors open on the same file. If there were other file
5350 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005351 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005352 ** handle h - as it is guaranteed that no posix locks will be released
5353 ** by doing so.
5354 **
5355 ** If scenario (a) caused the error then things are not so safe. The
5356 ** implicit assumption here is that if fstat() fails, things are in
5357 ** such bad shape that dropping a lock or two doesn't matter much.
5358 */
drh0e9365c2011-03-02 02:08:13 +00005359 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005360 h = -1;
5361 }
drh7708e972008-11-29 00:56:52 +00005362 unixLeaveMutex();
5363 }
danielk1977e339d652008-06-28 11:23:00 +00005364
drhd2cb50b2009-01-09 21:41:17 +00005365#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005366 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005367 /* AFP locking uses the file path so it needs to be included in
5368 ** the afpLockingContext.
5369 */
5370 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005371 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005372 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005373 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005374 }else{
5375 /* NB: zFilename exists and remains valid until the file is closed
5376 ** according to requirement F11141. So we do not need to make a
5377 ** copy of the filename. */
5378 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005379 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005380 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005381 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005382 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005383 if( rc!=SQLITE_OK ){
5384 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005385 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005386 h = -1;
5387 }
drh7708e972008-11-29 00:56:52 +00005388 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005389 }
drh7708e972008-11-29 00:56:52 +00005390 }
5391#endif
danielk1977e339d652008-06-28 11:23:00 +00005392
drh7708e972008-11-29 00:56:52 +00005393 else if( pLockingStyle == &dotlockIoMethods ){
5394 /* Dotfile locking uses the file path so it needs to be included in
5395 ** the dotlockLockingContext
5396 */
5397 char *zLockFile;
5398 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005399 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005400 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005401 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005402 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005403 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005404 }else{
5405 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005406 }
drh7708e972008-11-29 00:56:52 +00005407 pNew->lockingContext = zLockFile;
5408 }
danielk1977e339d652008-06-28 11:23:00 +00005409
drh6c7d5c52008-11-21 20:32:33 +00005410#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005411 else if( pLockingStyle == &semIoMethods ){
5412 /* Named semaphore locking uses the file path so it needs to be
5413 ** included in the semLockingContext
5414 */
5415 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005416 rc = findInodeInfo(pNew, &pNew->pInode);
5417 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5418 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005419 int n;
drh2238dcc2009-08-27 17:56:20 +00005420 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005421 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005422 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005423 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005424 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5425 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005426 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005427 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005428 }
chw97185482008-11-17 08:05:31 +00005429 }
drh7708e972008-11-29 00:56:52 +00005430 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005431 }
drh7708e972008-11-29 00:56:52 +00005432#endif
aswift5b1a2562008-08-22 00:22:35 +00005433
drh4bf66fd2015-02-19 02:43:02 +00005434 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005435#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005436 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005437 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005438 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005439 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005440 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005441 }
chw97185482008-11-17 08:05:31 +00005442#endif
danielk1977e339d652008-06-28 11:23:00 +00005443 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005444 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005445 }else{
drh7708e972008-11-29 00:56:52 +00005446 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005447 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005448 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005449 }
danielk1977e339d652008-06-28 11:23:00 +00005450 return rc;
drh054889e2005-11-30 03:20:31 +00005451}
drh9c06c952005-11-26 00:25:00 +00005452
danielk1977ad94b582007-08-20 06:44:22 +00005453/*
drh8b3cf822010-06-01 21:02:51 +00005454** Return the name of a directory in which to put temporary files.
5455** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005456*/
drh7234c6d2010-06-19 15:10:09 +00005457static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005458 static const char *azDirs[] = {
5459 0,
aswiftaebf4132008-11-21 00:10:35 +00005460 0,
danielk197717b90b52008-06-06 11:11:25 +00005461 "/var/tmp",
5462 "/usr/tmp",
5463 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005464 "."
danielk197717b90b52008-06-06 11:11:25 +00005465 };
drh2aab11f2016-04-29 20:30:56 +00005466 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005467 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005468 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005469
drhb7e50ad2015-11-28 21:49:53 +00005470 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5471 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005472 while(1){
5473 if( zDir!=0
5474 && osStat(zDir, &buf)==0
5475 && S_ISDIR(buf.st_mode)
5476 && osAccess(zDir, 03)==0
5477 ){
5478 return zDir;
5479 }
5480 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5481 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005482 }
drh7694e062016-04-21 23:37:24 +00005483 return 0;
drh8b3cf822010-06-01 21:02:51 +00005484}
5485
5486/*
5487** Create a temporary file name in zBuf. zBuf must be allocated
5488** by the calling process and must be big enough to hold at least
5489** pVfs->mxPathname bytes.
5490*/
5491static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005492 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005493 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005494
5495 /* It's odd to simulate an io-error here, but really this is just
5496 ** using the io-error infrastructure to test that SQLite handles this
5497 ** function failing.
5498 */
drh7694e062016-04-21 23:37:24 +00005499 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005500 SimulateIOError( return SQLITE_IOERR );
5501
drh7234c6d2010-06-19 15:10:09 +00005502 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005503 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005504 do{
drh970942e2015-11-25 23:13:14 +00005505 u64 r;
5506 sqlite3_randomness(sizeof(r), &r);
5507 assert( nBuf>2 );
5508 zBuf[nBuf-2] = 0;
5509 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5510 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005511 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005512 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005513 return SQLITE_OK;
5514}
5515
drhd2cb50b2009-01-09 21:41:17 +00005516#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005517/*
5518** Routine to transform a unixFile into a proxy-locking unixFile.
5519** Implementation in the proxy-lock division, but used by unixOpen()
5520** if SQLITE_PREFER_PROXY_LOCKING is defined.
5521*/
5522static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005523#endif
drhc66d5b62008-12-03 22:48:32 +00005524
dan08da86a2009-08-21 17:18:03 +00005525/*
5526** Search for an unused file descriptor that was opened on the database
5527** file (not a journal or master-journal file) identified by pathname
5528** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5529** argument to this function.
5530**
5531** Such a file descriptor may exist if a database connection was closed
5532** but the associated file descriptor could not be closed because some
5533** other file descriptor open on the same file is holding a file-lock.
5534** Refer to comments in the unixClose() function and the lengthy comment
5535** describing "Posix Advisory Locking" at the start of this file for
5536** further details. Also, ticket #4018.
5537**
5538** If a suitable file descriptor is found, then it is returned. If no
5539** such file descriptor is located, -1 is returned.
5540*/
dane946c392009-08-22 11:39:46 +00005541static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5542 UnixUnusedFd *pUnused = 0;
5543
5544 /* Do not search for an unused file descriptor on vxworks. Not because
5545 ** vxworks would not benefit from the change (it might, we're not sure),
5546 ** but because no way to test it is currently available. It is better
5547 ** not to risk breaking vxworks support for the sake of such an obscure
5548 ** feature. */
5549#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005550 struct stat sStat; /* Results of stat() call */
5551
5552 /* A stat() call may fail for various reasons. If this happens, it is
5553 ** almost certain that an open() call on the same path will also fail.
5554 ** For this reason, if an error occurs in the stat() call here, it is
5555 ** ignored and -1 is returned. The caller will try to open a new file
5556 ** descriptor on the same path, fail, and return an error to SQLite.
5557 **
5558 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005559 ** not searching for a reusable file descriptor are not dire. */
drh58384f12011-07-28 00:14:45 +00005560 if( 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005561 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005562
5563 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005564 pInode = inodeList;
5565 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005566 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005567 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005568 }
drh8af6c222010-05-14 12:43:01 +00005569 if( pInode ){
dane946c392009-08-22 11:39:46 +00005570 UnixUnusedFd **pp;
drh8af6c222010-05-14 12:43:01 +00005571 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005572 pUnused = *pp;
5573 if( pUnused ){
5574 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005575 }
5576 }
5577 unixLeaveMutex();
5578 }
dane946c392009-08-22 11:39:46 +00005579#endif /* if !OS_VXWORKS */
5580 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005581}
danielk197717b90b52008-06-06 11:11:25 +00005582
5583/*
dan1bf4ca72016-08-11 18:05:47 +00005584** Find the mode, uid and gid of file zFile.
5585*/
5586static int getFileMode(
5587 const char *zFile, /* File name */
5588 mode_t *pMode, /* OUT: Permissions of zFile */
5589 uid_t *pUid, /* OUT: uid of zFile. */
5590 gid_t *pGid /* OUT: gid of zFile. */
5591){
5592 struct stat sStat; /* Output of stat() on database file */
5593 int rc = SQLITE_OK;
5594 if( 0==osStat(zFile, &sStat) ){
5595 *pMode = sStat.st_mode & 0777;
5596 *pUid = sStat.st_uid;
5597 *pGid = sStat.st_gid;
5598 }else{
5599 rc = SQLITE_IOERR_FSTAT;
5600 }
5601 return rc;
5602}
5603
5604/*
danddb0ac42010-07-14 14:48:58 +00005605** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005606** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005607** and a value suitable for passing as the third argument to open(2) is
5608** written to *pMode. If an IO error occurs, an SQLite error code is
5609** returned and the value of *pMode is not modified.
5610**
peter.d.reid60ec9142014-09-06 16:39:46 +00005611** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005612** an indication to robust_open() to create the file using
5613** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5614** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005615** this function queries the file-system for the permissions on the
5616** corresponding database file and sets *pMode to this value. Whenever
5617** possible, WAL and journal files are created using the same permissions
5618** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005619**
5620** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5621** original filename is unavailable. But 8_3_NAMES is only used for
5622** FAT filesystems and permissions do not matter there, so just use
5623** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005624*/
5625static int findCreateFileMode(
5626 const char *zPath, /* Path of file (possibly) being created */
5627 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005628 mode_t *pMode, /* OUT: Permissions to open file with */
5629 uid_t *pUid, /* OUT: uid to set on the file */
5630 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005631){
5632 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005633 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005634 *pUid = 0;
5635 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005636 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005637 char zDb[MAX_PATHNAME+1]; /* Database file path */
5638 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005639
dana0c989d2010-11-05 18:07:37 +00005640 /* zPath is a path to a WAL or journal file. The following block derives
5641 ** the path to the associated database file from zPath. This block handles
5642 ** the following naming conventions:
5643 **
5644 ** "<path to db>-journal"
5645 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005646 ** "<path to db>-journalNN"
5647 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005648 **
drhd337c5b2011-10-20 18:23:35 +00005649 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005650 ** used by the test_multiplex.c module.
5651 */
5652 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005653 while( zPath[nDb]!='-' ){
drh90e5dda2015-12-03 20:42:28 +00005654#ifndef SQLITE_ENABLE_8_3_NAMES
5655 /* In the normal case (8+3 filenames disabled) the journal filename
5656 ** is guaranteed to contain a '-' character. */
drhc47167a2011-10-05 15:26:13 +00005657 assert( nDb>0 );
drh90e5dda2015-12-03 20:42:28 +00005658 assert( sqlite3Isalnum(zPath[nDb]) );
5659#else
5660 /* If 8+3 names are possible, then the journal file might not contain
5661 ** a '-' character. So check for that case and return early. */
5662 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
5663#endif
drhc47167a2011-10-05 15:26:13 +00005664 nDb--;
5665 }
danddb0ac42010-07-14 14:48:58 +00005666 memcpy(zDb, zPath, nDb);
5667 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005668
dan1bf4ca72016-08-11 18:05:47 +00005669 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005670 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5671 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005672 }else if( flags & SQLITE_OPEN_URI ){
5673 /* If this is a main database file and the file was opened using a URI
5674 ** filename, check for the "modeof" parameter. If present, interpret
5675 ** its value as a filename and try to copy the mode, uid and gid from
5676 ** that file. */
5677 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5678 if( z ){
5679 rc = getFileMode(z, pMode, pUid, pGid);
5680 }
danddb0ac42010-07-14 14:48:58 +00005681 }
5682 return rc;
5683}
5684
5685/*
danielk1977ad94b582007-08-20 06:44:22 +00005686** Open the file zPath.
5687**
danielk1977b4b47412007-08-17 15:53:36 +00005688** Previously, the SQLite OS layer used three functions in place of this
5689** one:
5690**
5691** sqlite3OsOpenReadWrite();
5692** sqlite3OsOpenReadOnly();
5693** sqlite3OsOpenExclusive();
5694**
5695** These calls correspond to the following combinations of flags:
5696**
5697** ReadWrite() -> (READWRITE | CREATE)
5698** ReadOnly() -> (READONLY)
5699** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5700**
5701** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5702** true, the file was configured to be automatically deleted when the
5703** file handle closed. To achieve the same effect using this new
5704** interface, add the DELETEONCLOSE flag to those specified above for
5705** OpenExclusive().
5706*/
5707static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005708 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5709 const char *zPath, /* Pathname of file to be opened */
5710 sqlite3_file *pFile, /* The file descriptor to be filled in */
5711 int flags, /* Input flags to control the opening */
5712 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005713){
dan08da86a2009-08-21 17:18:03 +00005714 unixFile *p = (unixFile *)pFile;
5715 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005716 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005717 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005718 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005719 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005720 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005721
5722 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5723 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5724 int isCreate = (flags & SQLITE_OPEN_CREATE);
5725 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5726 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005727#if SQLITE_ENABLE_LOCKING_STYLE
5728 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5729#endif
drh3d4435b2011-08-26 20:55:50 +00005730#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5731 struct statfs fsInfo;
5732#endif
danielk1977b4b47412007-08-17 15:53:36 +00005733
danielk1977fee2d252007-08-18 10:59:19 +00005734 /* If creating a master or main-file journal, this function will open
5735 ** a file-descriptor on the directory too. The first time unixSync()
5736 ** is called the directory file descriptor will be fsync()ed and close()d.
5737 */
drh0059eae2011-08-08 23:48:40 +00005738 int syncDir = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005739 eType==SQLITE_OPEN_MASTER_JOURNAL
5740 || eType==SQLITE_OPEN_MAIN_JOURNAL
5741 || eType==SQLITE_OPEN_WAL
5742 ));
danielk1977fee2d252007-08-18 10:59:19 +00005743
danielk197717b90b52008-06-06 11:11:25 +00005744 /* If argument zPath is a NULL pointer, this function is required to open
5745 ** a temporary file. Use this buffer to store the file name in.
5746 */
drhc02a43a2012-01-10 23:18:38 +00005747 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005748 const char *zName = zPath;
5749
danielk1977fee2d252007-08-18 10:59:19 +00005750 /* Check the following statements are true:
5751 **
5752 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5753 ** (b) if CREATE is set, then READWRITE must also be set, and
5754 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005755 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005756 */
danielk1977b4b47412007-08-17 15:53:36 +00005757 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005758 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005759 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005760 assert(isDelete==0 || isCreate);
5761
danddb0ac42010-07-14 14:48:58 +00005762 /* The main DB, main journal, WAL file and master journal are never
5763 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005764 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5765 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5766 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005767 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005768
danielk1977fee2d252007-08-18 10:59:19 +00005769 /* Assert that the upper layer has set one of the "file-type" flags. */
5770 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5771 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5772 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005773 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005774 );
5775
drhb00d8622014-01-01 15:18:36 +00005776 /* Detect a pid change and reset the PRNG. There is a race condition
5777 ** here such that two or more threads all trying to open databases at
5778 ** the same instant might all reset the PRNG. But multiple resets
5779 ** are harmless.
5780 */
drh5ac93652015-03-21 20:59:43 +00005781 if( randomnessPid!=osGetpid(0) ){
5782 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005783 sqlite3_randomness(0,0);
5784 }
5785
dan08da86a2009-08-21 17:18:03 +00005786 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005787
dan08da86a2009-08-21 17:18:03 +00005788 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005789 UnixUnusedFd *pUnused;
5790 pUnused = findReusableFd(zName, flags);
5791 if( pUnused ){
5792 fd = pUnused->fd;
5793 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005794 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005795 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005796 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005797 }
5798 }
5799 p->pUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005800
5801 /* Database filenames are double-zero terminated if they are not
5802 ** URIs with parameters. Hence, they can always be passed into
5803 ** sqlite3_uri_parameter(). */
5804 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
5805
dan08da86a2009-08-21 17:18:03 +00005806 }else if( !zName ){
5807 /* If zName is NULL, the upper layer is requesting a temp file. */
drh0059eae2011-08-08 23:48:40 +00005808 assert(isDelete && !syncDir);
drhb7e50ad2015-11-28 21:49:53 +00005809 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00005810 if( rc!=SQLITE_OK ){
5811 return rc;
5812 }
5813 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00005814
5815 /* Generated temporary filenames are always double-zero terminated
5816 ** for use by sqlite3_uri_parameter(). */
5817 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00005818 }
5819
dan08da86a2009-08-21 17:18:03 +00005820 /* Determine the value of the flags parameter passed to POSIX function
5821 ** open(). These must be calculated even if open() is not called, as
5822 ** they may be stored as part of the file handle and used by the
5823 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00005824 if( isReadonly ) openFlags |= O_RDONLY;
5825 if( isReadWrite ) openFlags |= O_RDWR;
5826 if( isCreate ) openFlags |= O_CREAT;
5827 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
5828 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00005829
danielk1977b4b47412007-08-17 15:53:36 +00005830 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00005831 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00005832 uid_t uid; /* Userid for the file */
5833 gid_t gid; /* Groupid for the file */
5834 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00005835 if( rc!=SQLITE_OK ){
5836 assert( !p->pUnused );
drh8ab58662010-07-15 18:38:39 +00005837 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005838 return rc;
5839 }
drhad4f1e52011-03-04 15:43:57 +00005840 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00005841 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00005842 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
5843 if( fd<0 && errno!=EISDIR && isReadWrite ){
dan08da86a2009-08-21 17:18:03 +00005844 /* Failed to open the file for read/write access. Try read-only. */
5845 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
dane946c392009-08-22 11:39:46 +00005846 openFlags &= ~(O_RDWR|O_CREAT);
dan08da86a2009-08-21 17:18:03 +00005847 flags |= SQLITE_OPEN_READONLY;
dane946c392009-08-22 11:39:46 +00005848 openFlags |= O_RDONLY;
drh77197112011-03-15 19:08:48 +00005849 isReadonly = 1;
drhad4f1e52011-03-04 15:43:57 +00005850 fd = robust_open(zName, openFlags, openMode);
dan08da86a2009-08-21 17:18:03 +00005851 }
5852 if( fd<0 ){
dane18d4952011-02-21 11:46:24 +00005853 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
dane946c392009-08-22 11:39:46 +00005854 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00005855 }
drhac7c3ac2012-02-11 19:23:48 +00005856
5857 /* If this process is running as root and if creating a new rollback
5858 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00005859 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00005860 */
5861 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00005862 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00005863 }
danielk1977b4b47412007-08-17 15:53:36 +00005864 }
dan08da86a2009-08-21 17:18:03 +00005865 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00005866 if( pOutFlags ){
5867 *pOutFlags = flags;
5868 }
5869
dane946c392009-08-22 11:39:46 +00005870 if( p->pUnused ){
5871 p->pUnused->fd = fd;
5872 p->pUnused->flags = flags;
5873 }
5874
danielk1977b4b47412007-08-17 15:53:36 +00005875 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00005876#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005877 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00005878#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
5879 zPath = sqlite3_mprintf("%s", zName);
5880 if( zPath==0 ){
5881 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00005882 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00005883 }
chw97185482008-11-17 08:05:31 +00005884#else
drh036ac7f2011-08-08 23:18:05 +00005885 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00005886#endif
danielk1977b4b47412007-08-17 15:53:36 +00005887 }
drh41022642008-11-21 00:24:42 +00005888#if SQLITE_ENABLE_LOCKING_STYLE
5889 else{
dan08da86a2009-08-21 17:18:03 +00005890 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00005891 }
5892#endif
drh7ed97b92010-01-20 13:07:21 +00005893
5894#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00005895 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00005896 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00005897 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005898 return SQLITE_IOERR_ACCESS;
5899 }
5900 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
5901 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5902 }
drh4bf66fd2015-02-19 02:43:02 +00005903 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
5904 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
5905 }
drh7ed97b92010-01-20 13:07:21 +00005906#endif
drhc02a43a2012-01-10 23:18:38 +00005907
5908 /* Set up appropriate ctrlFlags */
5909 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
5910 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00005911 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00005912 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
5913 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
5914 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
5915
drh7ed97b92010-01-20 13:07:21 +00005916#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00005917#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00005918 isAutoProxy = 1;
5919#endif
5920 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00005921 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
5922 int useProxy = 0;
5923
dan08da86a2009-08-21 17:18:03 +00005924 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
5925 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00005926 if( envforce!=NULL ){
5927 useProxy = atoi(envforce)>0;
5928 }else{
aswiftaebf4132008-11-21 00:10:35 +00005929 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
5930 }
5931 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00005932 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00005933 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00005934 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00005935 if( rc!=SQLITE_OK ){
5936 /* Use unixClose to clean up the resources added in fillInUnixFile
5937 ** and clear all the structure's references. Specifically,
5938 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
5939 */
5940 unixClose(pFile);
5941 return rc;
5942 }
aswiftaebf4132008-11-21 00:10:35 +00005943 }
dane946c392009-08-22 11:39:46 +00005944 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00005945 }
5946 }
5947#endif
5948
drhc02a43a2012-01-10 23:18:38 +00005949 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
5950
dane946c392009-08-22 11:39:46 +00005951open_finished:
5952 if( rc!=SQLITE_OK ){
5953 sqlite3_free(p->pUnused);
5954 }
5955 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005956}
5957
dane946c392009-08-22 11:39:46 +00005958
danielk1977b4b47412007-08-17 15:53:36 +00005959/*
danielk1977fee2d252007-08-18 10:59:19 +00005960** Delete the file at zPath. If the dirSync argument is true, fsync()
5961** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00005962*/
drh6b9d6dd2008-12-03 19:34:47 +00005963static int unixDelete(
5964 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
5965 const char *zPath, /* Name of file to be deleted */
5966 int dirSync /* If true, fsync() directory after deleting file */
5967){
danielk1977fee2d252007-08-18 10:59:19 +00005968 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00005969 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00005970 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00005971 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00005972 if( errno==ENOENT
5973#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00005974 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00005975#endif
5976 ){
dan9fc5b4a2012-11-09 20:17:26 +00005977 rc = SQLITE_IOERR_DELETE_NOENT;
5978 }else{
drhb4308162012-11-09 21:40:02 +00005979 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00005980 }
drhb4308162012-11-09 21:40:02 +00005981 return rc;
drh5d4feff2010-07-14 01:45:22 +00005982 }
danielk1977d39fa702008-10-16 13:27:40 +00005983#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00005984 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00005985 int fd;
drh90315a22011-08-10 01:52:12 +00005986 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00005987 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00005988 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00005989 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00005990 }
drh0e9365c2011-03-02 02:08:13 +00005991 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00005992 }else{
5993 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00005994 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00005995 }
5996 }
danielk1977d138dd82008-10-15 16:02:48 +00005997#endif
danielk1977fee2d252007-08-18 10:59:19 +00005998 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00005999}
6000
danielk197790949c22007-08-17 16:50:38 +00006001/*
mistachkin48864df2013-03-21 21:20:32 +00006002** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006003** test performed depends on the value of flags:
6004**
6005** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6006** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6007** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6008**
6009** Otherwise return 0.
6010*/
danielk1977861f7452008-06-05 11:39:11 +00006011static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006012 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6013 const char *zPath, /* Path of the file to examine */
6014 int flags, /* What do we want to learn about the zPath file? */
6015 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006016){
danielk1977397d65f2008-11-19 11:35:39 +00006017 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006018 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006019 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006020
drhd260b5b2015-11-25 18:03:33 +00006021 /* The spec says there are three possible values for flags. But only
6022 ** two of them are actually used */
6023 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6024
6025 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006026 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006027 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6028 }else{
6029 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006030 }
danielk1977861f7452008-06-05 11:39:11 +00006031 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006032}
6033
danielk1977b4b47412007-08-17 15:53:36 +00006034/*
danielk1977b4b47412007-08-17 15:53:36 +00006035**
danielk1977b4b47412007-08-17 15:53:36 +00006036*/
dane88ec182016-01-25 17:04:48 +00006037static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006038 const char *zPath, /* Input path */
6039 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006040 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006041){
dancaf6b152016-01-25 18:05:49 +00006042 int nPath = sqlite3Strlen30(zPath);
6043 int iOff = 0;
6044 if( zPath[0]!='/' ){
6045 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006046 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006047 }
dancaf6b152016-01-25 18:05:49 +00006048 iOff = sqlite3Strlen30(zOut);
6049 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006050 }
dan23496702016-01-26 13:56:42 +00006051 if( (iOff+nPath+1)>nOut ){
6052 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6053 ** even if it returns an error. */
6054 zOut[iOff] = '\0';
6055 return SQLITE_CANTOPEN_BKPT;
6056 }
dancaf6b152016-01-25 18:05:49 +00006057 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006058 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006059}
6060
dane88ec182016-01-25 17:04:48 +00006061/*
6062** Turn a relative pathname into a full pathname. The relative path
6063** is stored as a nul-terminated string in the buffer pointed to by
6064** zPath.
6065**
6066** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6067** (in this case, MAX_PATHNAME bytes). The full-path is written to
6068** this buffer before returning.
6069*/
6070static int unixFullPathname(
6071 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6072 const char *zPath, /* Possibly relative input path */
6073 int nOut, /* Size of output buffer in bytes */
6074 char *zOut /* Output buffer */
6075){
danaf1b36b2016-01-25 18:43:05 +00006076#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006077 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006078#else
6079 int rc = SQLITE_OK;
6080 int nByte;
dancaf6b152016-01-25 18:05:49 +00006081 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006082 const char *zIn = zPath; /* Input path for each iteration of loop */
6083 char *zDel = 0;
6084
6085 assert( pVfs->mxPathname==MAX_PATHNAME );
6086 UNUSED_PARAMETER(pVfs);
6087
6088 /* It's odd to simulate an io-error here, but really this is just
6089 ** using the io-error infrastructure to test that SQLite handles this
6090 ** function failing. This function could fail if, for example, the
6091 ** current working directory has been unlinked.
6092 */
6093 SimulateIOError( return SQLITE_ERROR );
6094
6095 do {
6096
dancaf6b152016-01-25 18:05:49 +00006097 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6098 ** link, or false otherwise. */
6099 int bLink = 0;
6100 struct stat buf;
6101 if( osLstat(zIn, &buf)!=0 ){
6102 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006103 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006104 }
dane88ec182016-01-25 17:04:48 +00006105 }else{
dancaf6b152016-01-25 18:05:49 +00006106 bLink = S_ISLNK(buf.st_mode);
6107 }
6108
6109 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006110 if( zDel==0 ){
6111 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006112 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006113 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6114 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006115 }
dancaf6b152016-01-25 18:05:49 +00006116
6117 if( rc==SQLITE_OK ){
6118 nByte = osReadlink(zIn, zDel, nOut-1);
6119 if( nByte<0 ){
6120 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006121 }else{
6122 if( zDel[0]!='/' ){
6123 int n;
6124 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6125 if( nByte+n+1>nOut ){
6126 rc = SQLITE_CANTOPEN_BKPT;
6127 }else{
6128 memmove(&zDel[n], zDel, nByte+1);
6129 memcpy(zDel, zIn, n);
6130 nByte += n;
6131 }
dancaf6b152016-01-25 18:05:49 +00006132 }
6133 zDel[nByte] = '\0';
6134 }
6135 }
6136
6137 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006138 }
6139
dan23496702016-01-26 13:56:42 +00006140 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6141 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006142 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006143 }
dancaf6b152016-01-25 18:05:49 +00006144 if( bLink==0 ) break;
6145 zIn = zOut;
6146 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006147
6148 sqlite3_free(zDel);
6149 return rc;
danaf1b36b2016-01-25 18:43:05 +00006150#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006151}
6152
drh0ccebe72005-06-07 22:22:50 +00006153
drh761df872006-12-21 01:29:22 +00006154#ifndef SQLITE_OMIT_LOAD_EXTENSION
6155/*
6156** Interfaces for opening a shared library, finding entry points
6157** within the shared library, and closing the shared library.
6158*/
6159#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006160static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6161 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006162 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6163}
danielk197795c8a542007-09-01 06:51:27 +00006164
6165/*
6166** SQLite calls this function immediately after a call to unixDlSym() or
6167** unixDlOpen() fails (returns a null pointer). If a more detailed error
6168** message is available, it is written to zBufOut. If no error message
6169** is available, zBufOut is left unmodified and SQLite uses a default
6170** error message.
6171*/
danielk1977397d65f2008-11-19 11:35:39 +00006172static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006173 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006174 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006175 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006176 zErr = dlerror();
6177 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006178 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006179 }
drh6c7d5c52008-11-21 20:32:33 +00006180 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006181}
drh1875f7a2008-12-08 18:19:17 +00006182static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6183 /*
6184 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6185 ** cast into a pointer to a function. And yet the library dlsym() routine
6186 ** returns a void* which is really a pointer to a function. So how do we
6187 ** use dlsym() with -pedantic-errors?
6188 **
6189 ** Variable x below is defined to be a pointer to a function taking
6190 ** parameters void* and const char* and returning a pointer to a function.
6191 ** We initialize x by assigning it a pointer to the dlsym() function.
6192 ** (That assignment requires a cast.) Then we call the function that
6193 ** x points to.
6194 **
6195 ** This work-around is unlikely to work correctly on any system where
6196 ** you really cannot cast a function pointer into void*. But then, on the
6197 ** other hand, dlsym() will not work on such a system either, so we have
6198 ** not really lost anything.
6199 */
6200 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006201 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006202 x = (void(*(*)(void*,const char*))(void))dlsym;
6203 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006204}
danielk1977397d65f2008-11-19 11:35:39 +00006205static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6206 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006207 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006208}
danielk1977b4b47412007-08-17 15:53:36 +00006209#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6210 #define unixDlOpen 0
6211 #define unixDlError 0
6212 #define unixDlSym 0
6213 #define unixDlClose 0
6214#endif
6215
6216/*
danielk197790949c22007-08-17 16:50:38 +00006217** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006218*/
danielk1977397d65f2008-11-19 11:35:39 +00006219static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6220 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006221 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006222
drhbbd42a62004-05-22 17:41:58 +00006223 /* We have to initialize zBuf to prevent valgrind from reporting
6224 ** errors. The reports issued by valgrind are incorrect - we would
6225 ** prefer that the randomness be increased by making use of the
6226 ** uninitialized space in zBuf - but valgrind errors tend to worry
6227 ** some users. Rather than argue, it seems easier just to initialize
6228 ** the whole array and silence valgrind, even if that means less randomness
6229 ** in the random seed.
6230 **
6231 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006232 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006233 ** tests repeatable.
6234 */
danielk1977b4b47412007-08-17 15:53:36 +00006235 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006236 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006237#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006238 {
drhb00d8622014-01-01 15:18:36 +00006239 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006240 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006241 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006242 time_t t;
6243 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006244 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006245 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6246 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6247 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006248 }else{
drhc18b4042012-02-10 03:10:27 +00006249 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006250 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006251 }
drhbbd42a62004-05-22 17:41:58 +00006252 }
6253#endif
drh72cbd072008-10-14 17:58:38 +00006254 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006255}
6256
danielk1977b4b47412007-08-17 15:53:36 +00006257
drhbbd42a62004-05-22 17:41:58 +00006258/*
6259** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006260** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006261** The return value is the number of microseconds of sleep actually
6262** requested from the underlying operating system, a number which
6263** might be greater than or equal to the argument, but not less
6264** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006265*/
danielk1977397d65f2008-11-19 11:35:39 +00006266static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006267#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006268 struct timespec sp;
6269
6270 sp.tv_sec = microseconds / 1000000;
6271 sp.tv_nsec = (microseconds % 1000000) * 1000;
6272 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006273 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006274 return microseconds;
6275#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006276 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006277 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006278 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006279#else
danielk1977b4b47412007-08-17 15:53:36 +00006280 int seconds = (microseconds+999999)/1000000;
6281 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006282 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006283 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006284#endif
drh88f474a2006-01-02 20:00:12 +00006285}
6286
6287/*
drh6b9d6dd2008-12-03 19:34:47 +00006288** The following variable, if set to a non-zero value, is interpreted as
6289** the number of seconds since 1970 and is used to set the result of
6290** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006291*/
6292#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006293int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006294#endif
6295
6296/*
drhb7e8ea22010-05-03 14:32:30 +00006297** Find the current time (in Universal Coordinated Time). Write into *piNow
6298** the current time and date as a Julian Day number times 86_400_000. In
6299** other words, write into *piNow the number of milliseconds since the Julian
6300** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6301** proleptic Gregorian calendar.
6302**
drh31702252011-10-12 23:13:43 +00006303** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6304** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006305*/
6306static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6307 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006308 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006309#if defined(NO_GETTOD)
6310 time_t t;
6311 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006312 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006313#elif OS_VXWORKS
6314 struct timespec sNow;
6315 clock_gettime(CLOCK_REALTIME, &sNow);
6316 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6317#else
6318 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006319 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6320 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006321#endif
6322
6323#ifdef SQLITE_TEST
6324 if( sqlite3_current_time ){
6325 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6326 }
6327#endif
6328 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006329 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006330}
6331
drhc3dfa5e2016-01-22 19:44:03 +00006332#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006333/*
drhbbd42a62004-05-22 17:41:58 +00006334** Find the current time (in Universal Coordinated Time). Write the
6335** current time and date as a Julian Day number into *prNow and
6336** return 0. Return 1 if the time and date cannot be found.
6337*/
danielk1977397d65f2008-11-19 11:35:39 +00006338static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006339 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006340 int rc;
drhff828942010-06-26 21:34:06 +00006341 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006342 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006343 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006344 return rc;
drhbbd42a62004-05-22 17:41:58 +00006345}
drh5337dac2015-11-25 15:15:03 +00006346#else
6347# define unixCurrentTime 0
6348#endif
danielk1977b4b47412007-08-17 15:53:36 +00006349
drh6b9d6dd2008-12-03 19:34:47 +00006350/*
drh1b9f2142016-03-17 16:01:23 +00006351** The xGetLastError() method is designed to return a better
6352** low-level error message when operating-system problems come up
6353** during SQLite operation. Only the integer return code is currently
6354** used.
drh6b9d6dd2008-12-03 19:34:47 +00006355*/
danielk1977397d65f2008-11-19 11:35:39 +00006356static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6357 UNUSED_PARAMETER(NotUsed);
6358 UNUSED_PARAMETER(NotUsed2);
6359 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006360 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006361}
6362
drhf2424c52010-04-26 00:04:55 +00006363
6364/*
drh734c9862008-11-28 15:37:20 +00006365************************ End of sqlite3_vfs methods ***************************
6366******************************************************************************/
6367
drh715ff302008-12-03 22:32:44 +00006368/******************************************************************************
6369************************** Begin Proxy Locking ********************************
6370**
6371** Proxy locking is a "uber-locking-method" in this sense: It uses the
6372** other locking methods on secondary lock files. Proxy locking is a
6373** meta-layer over top of the primitive locking implemented above. For
6374** this reason, the division that implements of proxy locking is deferred
6375** until late in the file (here) after all of the other I/O methods have
6376** been defined - so that the primitive locking methods are available
6377** as services to help with the implementation of proxy locking.
6378**
6379****
6380**
6381** The default locking schemes in SQLite use byte-range locks on the
6382** database file to coordinate safe, concurrent access by multiple readers
6383** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6384** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6385** as POSIX read & write locks over fixed set of locations (via fsctl),
6386** on AFP and SMB only exclusive byte-range locks are available via fsctl
6387** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6388** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6389** address in the shared range is taken for a SHARED lock, the entire
6390** shared range is taken for an EXCLUSIVE lock):
6391**
drhf2f105d2012-08-20 15:53:54 +00006392** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006393** RESERVED_BYTE 0x40000001
6394** SHARED_RANGE 0x40000002 -> 0x40000200
6395**
6396** This works well on the local file system, but shows a nearly 100x
6397** slowdown in read performance on AFP because the AFP client disables
6398** the read cache when byte-range locks are present. Enabling the read
6399** cache exposes a cache coherency problem that is present on all OS X
6400** supported network file systems. NFS and AFP both observe the
6401** close-to-open semantics for ensuring cache coherency
6402** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6403** address the requirements for concurrent database access by multiple
6404** readers and writers
6405** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6406**
6407** To address the performance and cache coherency issues, proxy file locking
6408** changes the way database access is controlled by limiting access to a
6409** single host at a time and moving file locks off of the database file
6410** and onto a proxy file on the local file system.
6411**
6412**
6413** Using proxy locks
6414** -----------------
6415**
6416** C APIs
6417**
drh4bf66fd2015-02-19 02:43:02 +00006418** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006419** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006420** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6421** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006422**
6423**
6424** SQL pragmas
6425**
6426** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6427** PRAGMA [database.]lock_proxy_file
6428**
6429** Specifying ":auto:" means that if there is a conch file with a matching
6430** host ID in it, the proxy path in the conch file will be used, otherwise
6431** a proxy path based on the user's temp dir
6432** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6433** actual proxy file name is generated from the name and path of the
6434** database file. For example:
6435**
6436** For database path "/Users/me/foo.db"
6437** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6438**
6439** Once a lock proxy is configured for a database connection, it can not
6440** be removed, however it may be switched to a different proxy path via
6441** the above APIs (assuming the conch file is not being held by another
6442** connection or process).
6443**
6444**
6445** How proxy locking works
6446** -----------------------
6447**
6448** Proxy file locking relies primarily on two new supporting files:
6449**
6450** * conch file to limit access to the database file to a single host
6451** at a time
6452**
6453** * proxy file to act as a proxy for the advisory locks normally
6454** taken on the database
6455**
6456** The conch file - to use a proxy file, sqlite must first "hold the conch"
6457** by taking an sqlite-style shared lock on the conch file, reading the
6458** contents and comparing the host's unique host ID (see below) and lock
6459** proxy path against the values stored in the conch. The conch file is
6460** stored in the same directory as the database file and the file name
6461** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006462** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006463** host ID and/or proxy path, then the lock is escalated to an exclusive
6464** lock and the conch file contents is updated with the host ID and proxy
6465** path and the lock is downgraded to a shared lock again. If the conch
6466** is held by another process (with a shared lock), the exclusive lock
6467** will fail and SQLITE_BUSY is returned.
6468**
6469** The proxy file - a single-byte file used for all advisory file locks
6470** normally taken on the database file. This allows for safe sharing
6471** of the database file for multiple readers and writers on the same
6472** host (the conch ensures that they all use the same local lock file).
6473**
drh715ff302008-12-03 22:32:44 +00006474** Requesting the lock proxy does not immediately take the conch, it is
6475** only taken when the first request to lock database file is made.
6476** This matches the semantics of the traditional locking behavior, where
6477** opening a connection to a database file does not take a lock on it.
6478** The shared lock and an open file descriptor are maintained until
6479** the connection to the database is closed.
6480**
6481** The proxy file and the lock file are never deleted so they only need
6482** to be created the first time they are used.
6483**
6484** Configuration options
6485** ---------------------
6486**
6487** SQLITE_PREFER_PROXY_LOCKING
6488**
6489** Database files accessed on non-local file systems are
6490** automatically configured for proxy locking, lock files are
6491** named automatically using the same logic as
6492** PRAGMA lock_proxy_file=":auto:"
6493**
6494** SQLITE_PROXY_DEBUG
6495**
6496** Enables the logging of error messages during host id file
6497** retrieval and creation
6498**
drh715ff302008-12-03 22:32:44 +00006499** LOCKPROXYDIR
6500**
6501** Overrides the default directory used for lock proxy files that
6502** are named automatically via the ":auto:" setting
6503**
6504** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6505**
6506** Permissions to use when creating a directory for storing the
6507** lock proxy files, only used when LOCKPROXYDIR is not set.
6508**
6509**
6510** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6511** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6512** force proxy locking to be used for every database file opened, and 0
6513** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006514** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006515** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6516*/
6517
6518/*
6519** Proxy locking is only available on MacOSX
6520*/
drhd2cb50b2009-01-09 21:41:17 +00006521#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006522
drh715ff302008-12-03 22:32:44 +00006523/*
6524** The proxyLockingContext has the path and file structures for the remote
6525** and local proxy files in it
6526*/
6527typedef struct proxyLockingContext proxyLockingContext;
6528struct proxyLockingContext {
6529 unixFile *conchFile; /* Open conch file */
6530 char *conchFilePath; /* Name of the conch file */
6531 unixFile *lockProxy; /* Open proxy lock file */
6532 char *lockProxyPath; /* Name of the proxy lock file */
6533 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006534 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006535 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006536 void *oldLockingContext; /* Original lockingcontext to restore on close */
6537 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6538};
6539
drh7ed97b92010-01-20 13:07:21 +00006540/*
6541** The proxy lock file path for the database at dbPath is written into lPath,
6542** which must point to valid, writable memory large enough for a maxLen length
6543** file path.
drh715ff302008-12-03 22:32:44 +00006544*/
drh715ff302008-12-03 22:32:44 +00006545static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6546 int len;
6547 int dbLen;
6548 int i;
6549
6550#ifdef LOCKPROXYDIR
6551 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6552#else
6553# ifdef _CS_DARWIN_USER_TEMP_DIR
6554 {
drh7ed97b92010-01-20 13:07:21 +00006555 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006556 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006557 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006558 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006559 }
drh7ed97b92010-01-20 13:07:21 +00006560 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006561 }
6562# else
6563 len = strlcpy(lPath, "/tmp/", maxLen);
6564# endif
6565#endif
6566
6567 if( lPath[len-1]!='/' ){
6568 len = strlcat(lPath, "/", maxLen);
6569 }
6570
6571 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006572 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006573 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006574 char c = dbPath[i];
6575 lPath[i+len] = (c=='/')?'_':c;
6576 }
6577 lPath[i+len]='\0';
6578 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006579 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006580 return SQLITE_OK;
6581}
6582
drh7ed97b92010-01-20 13:07:21 +00006583/*
6584 ** Creates the lock file and any missing directories in lockPath
6585 */
6586static int proxyCreateLockPath(const char *lockPath){
6587 int i, len;
6588 char buf[MAXPATHLEN];
6589 int start = 0;
6590
6591 assert(lockPath!=NULL);
6592 /* try to create all the intermediate directories */
6593 len = (int)strlen(lockPath);
6594 buf[0] = lockPath[0];
6595 for( i=1; i<len; i++ ){
6596 if( lockPath[i] == '/' && (i - start > 0) ){
6597 /* only mkdir if leaf dir != "." or "/" or ".." */
6598 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6599 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6600 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006601 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006602 int err=errno;
6603 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006604 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006605 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006606 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006607 return err;
6608 }
6609 }
6610 }
6611 start=i+1;
6612 }
6613 buf[i] = lockPath[i];
6614 }
drh62aaa6c2015-11-21 17:27:42 +00006615 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006616 return 0;
6617}
6618
drh715ff302008-12-03 22:32:44 +00006619/*
6620** Create a new VFS file descriptor (stored in memory obtained from
6621** sqlite3_malloc) and open the file named "path" in the file descriptor.
6622**
6623** The caller is responsible not only for closing the file descriptor
6624** but also for freeing the memory associated with the file descriptor.
6625*/
drh7ed97b92010-01-20 13:07:21 +00006626static int proxyCreateUnixFile(
6627 const char *path, /* path for the new unixFile */
6628 unixFile **ppFile, /* unixFile created and returned by ref */
6629 int islockfile /* if non zero missing dirs will be created */
6630) {
6631 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006632 unixFile *pNew;
6633 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006634 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006635 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006636 int terrno = 0;
6637 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006638
drh7ed97b92010-01-20 13:07:21 +00006639 /* 1. first try to open/create the file
6640 ** 2. if that fails, and this is a lock file (not-conch), try creating
6641 ** the parent directories and then try again.
6642 ** 3. if that fails, try to open the file read-only
6643 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6644 */
6645 pUnused = findReusableFd(path, openFlags);
6646 if( pUnused ){
6647 fd = pUnused->fd;
6648 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006649 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006650 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006651 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006652 }
6653 }
6654 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006655 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006656 terrno = errno;
6657 if( fd<0 && errno==ENOENT && islockfile ){
6658 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006659 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006660 }
6661 }
6662 }
6663 if( fd<0 ){
6664 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006665 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006666 terrno = errno;
6667 }
6668 if( fd<0 ){
6669 if( islockfile ){
6670 return SQLITE_BUSY;
6671 }
6672 switch (terrno) {
6673 case EACCES:
6674 return SQLITE_PERM;
6675 case EIO:
6676 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6677 default:
drh9978c972010-02-23 17:36:32 +00006678 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006679 }
6680 }
6681
drhf3cdcdc2015-04-29 16:50:28 +00006682 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006683 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006684 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006685 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006686 }
6687 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006688 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006689 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006690 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006691 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006692 pUnused->fd = fd;
6693 pUnused->flags = openFlags;
6694 pNew->pUnused = pUnused;
6695
drhc02a43a2012-01-10 23:18:38 +00006696 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006697 if( rc==SQLITE_OK ){
6698 *ppFile = pNew;
6699 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006700 }
drh7ed97b92010-01-20 13:07:21 +00006701end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006702 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006703 sqlite3_free(pNew);
6704 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006705 return rc;
6706}
6707
drh7ed97b92010-01-20 13:07:21 +00006708#ifdef SQLITE_TEST
6709/* simulate multiple hosts by creating unique hostid file paths */
6710int sqlite3_hostid_num = 0;
6711#endif
6712
6713#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6714
drh6bca6512015-04-13 23:05:28 +00006715#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006716/* Not always defined in the headers as it ought to be */
6717extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006718#endif
drh0ab216a2010-07-02 17:10:40 +00006719
drh7ed97b92010-01-20 13:07:21 +00006720/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6721** bytes of writable memory.
6722*/
6723static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006724 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6725 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006726#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006727 {
drh4bf66fd2015-02-19 02:43:02 +00006728 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006729 if( gethostuuid(pHostID, &timeout) ){
6730 int err = errno;
6731 if( pError ){
6732 *pError = err;
6733 }
6734 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006735 }
drh7ed97b92010-01-20 13:07:21 +00006736 }
drh3d4435b2011-08-26 20:55:50 +00006737#else
6738 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006739#endif
drh7ed97b92010-01-20 13:07:21 +00006740#ifdef SQLITE_TEST
6741 /* simulate multiple hosts by creating unique hostid file paths */
6742 if( sqlite3_hostid_num != 0){
6743 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6744 }
6745#endif
6746
6747 return SQLITE_OK;
6748}
6749
6750/* The conch file contains the header, host id and lock file path
6751 */
6752#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6753#define PROXY_HEADERLEN 1 /* conch file header length */
6754#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6755#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6756
6757/*
6758** Takes an open conch file, copies the contents to a new path and then moves
6759** it back. The newly created file's file descriptor is assigned to the
6760** conch file structure and finally the original conch file descriptor is
6761** closed. Returns zero if successful.
6762*/
6763static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6764 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6765 unixFile *conchFile = pCtx->conchFile;
6766 char tPath[MAXPATHLEN];
6767 char buf[PROXY_MAXCONCHLEN];
6768 char *cPath = pCtx->conchFilePath;
6769 size_t readLen = 0;
6770 size_t pathLen = 0;
6771 char errmsg[64] = "";
6772 int fd = -1;
6773 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006774 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006775
6776 /* create a new path by replace the trailing '-conch' with '-break' */
6777 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6778 if( pathLen>MAXPATHLEN || pathLen<6 ||
6779 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006780 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006781 goto end_breaklock;
6782 }
6783 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006784 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006785 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006786 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006787 goto end_breaklock;
6788 }
6789 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006790 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006791 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006792 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006793 goto end_breaklock;
6794 }
drhe562be52011-03-02 18:01:10 +00006795 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00006796 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006797 goto end_breaklock;
6798 }
6799 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00006800 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006801 goto end_breaklock;
6802 }
6803 rc = 0;
6804 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00006805 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006806 conchFile->h = fd;
6807 conchFile->openFlags = O_RDWR | O_CREAT;
6808
6809end_breaklock:
6810 if( rc ){
6811 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00006812 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00006813 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006814 }
6815 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
6816 }
6817 return rc;
6818}
6819
6820/* Take the requested lock on the conch file and break a stale lock if the
6821** host id matches.
6822*/
6823static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
6824 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6825 unixFile *conchFile = pCtx->conchFile;
6826 int rc = SQLITE_OK;
6827 int nTries = 0;
6828 struct timespec conchModTime;
6829
drh3d4435b2011-08-26 20:55:50 +00006830 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00006831 do {
6832 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6833 nTries ++;
6834 if( rc==SQLITE_BUSY ){
6835 /* If the lock failed (busy):
6836 * 1st try: get the mod time of the conch, wait 0.5s and try again.
6837 * 2nd try: fail if the mod time changed or host id is different, wait
6838 * 10 sec and try again
6839 * 3rd try: break the lock unless the mod time has changed.
6840 */
6841 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00006842 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00006843 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006844 return SQLITE_IOERR_LOCK;
6845 }
6846
6847 if( nTries==1 ){
6848 conchModTime = buf.st_mtimespec;
6849 usleep(500000); /* wait 0.5 sec and try the lock again*/
6850 continue;
6851 }
6852
6853 assert( nTries>1 );
6854 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
6855 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
6856 return SQLITE_BUSY;
6857 }
6858
6859 if( nTries==2 ){
6860 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00006861 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006862 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00006863 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00006864 return SQLITE_IOERR_LOCK;
6865 }
6866 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
6867 /* don't break the lock if the host id doesn't match */
6868 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
6869 return SQLITE_BUSY;
6870 }
6871 }else{
6872 /* don't break the lock on short read or a version mismatch */
6873 return SQLITE_BUSY;
6874 }
6875 usleep(10000000); /* wait 10 sec and try the lock again */
6876 continue;
6877 }
6878
6879 assert( nTries==3 );
6880 if( 0==proxyBreakConchLock(pFile, myHostID) ){
6881 rc = SQLITE_OK;
6882 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00006883 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00006884 }
6885 if( !rc ){
6886 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
6887 }
6888 }
6889 }
6890 } while( rc==SQLITE_BUSY && nTries<3 );
6891
6892 return rc;
6893}
6894
6895/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00006896** lockPath is non-NULL, the host ID and lock file path must match. A NULL
6897** lockPath means that the lockPath in the conch file will be used if the
6898** host IDs match, or a new lock path will be generated automatically
6899** and written to the conch file.
6900*/
6901static int proxyTakeConch(unixFile *pFile){
6902 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6903
drh7ed97b92010-01-20 13:07:21 +00006904 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00006905 return SQLITE_OK;
6906 }else{
6907 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00006908 uuid_t myHostID;
6909 int pError = 0;
6910 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00006911 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00006912 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00006913 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006914 int createConch = 0;
6915 int hostIdMatch = 0;
6916 int readLen = 0;
6917 int tryOldLockPath = 0;
6918 int forceNewLockPath = 0;
6919
drh308c2a52010-05-14 11:30:18 +00006920 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00006921 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00006922 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006923
drh7ed97b92010-01-20 13:07:21 +00006924 rc = proxyGetHostID(myHostID, &pError);
6925 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00006926 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00006927 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006928 }
drh7ed97b92010-01-20 13:07:21 +00006929 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00006930 if( rc!=SQLITE_OK ){
6931 goto end_takeconch;
6932 }
drh7ed97b92010-01-20 13:07:21 +00006933 /* read the existing conch file */
6934 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
6935 if( readLen<0 ){
6936 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00006937 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00006938 rc = SQLITE_IOERR_READ;
6939 goto end_takeconch;
6940 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
6941 readBuf[0]!=(char)PROXY_CONCHVERSION ){
6942 /* a short read or version format mismatch means we need to create a new
6943 ** conch file.
6944 */
6945 createConch = 1;
6946 }
6947 /* if the host id matches and the lock path already exists in the conch
6948 ** we'll try to use the path there, if we can't open that path, we'll
6949 ** retry with a new auto-generated path
6950 */
6951 do { /* in case we need to try again for an :auto: named lock file */
6952
6953 if( !createConch && !forceNewLockPath ){
6954 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
6955 PROXY_HOSTIDLEN);
6956 /* if the conch has data compare the contents */
6957 if( !pCtx->lockProxyPath ){
6958 /* for auto-named local lock file, just check the host ID and we'll
6959 ** use the local lock file path that's already in there
6960 */
6961 if( hostIdMatch ){
6962 size_t pathLen = (readLen - PROXY_PATHINDEX);
6963
6964 if( pathLen>=MAXPATHLEN ){
6965 pathLen=MAXPATHLEN-1;
6966 }
6967 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
6968 lockPath[pathLen] = 0;
6969 tempLockPath = lockPath;
6970 tryOldLockPath = 1;
6971 /* create a copy of the lock path if the conch is taken */
6972 goto end_takeconch;
6973 }
6974 }else if( hostIdMatch
6975 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
6976 readLen-PROXY_PATHINDEX)
6977 ){
6978 /* conch host and lock path match */
6979 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00006980 }
drh7ed97b92010-01-20 13:07:21 +00006981 }
6982
6983 /* if the conch isn't writable and doesn't match, we can't take it */
6984 if( (conchFile->openFlags&O_RDWR) == 0 ){
6985 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00006986 goto end_takeconch;
6987 }
drh7ed97b92010-01-20 13:07:21 +00006988
6989 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00006990 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00006991 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
6992 tempLockPath = lockPath;
6993 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00006994 }
drh7ed97b92010-01-20 13:07:21 +00006995
6996 /* update conch with host and path (this will fail if other process
6997 ** has a shared lock already), if the host id matches, use the big
6998 ** stick.
drh715ff302008-12-03 22:32:44 +00006999 */
drh7ed97b92010-01-20 13:07:21 +00007000 futimes(conchFile->h, NULL);
7001 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007002 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007003 /* We are trying for an exclusive lock but another thread in this
7004 ** same process is still holding a shared lock. */
7005 rc = SQLITE_BUSY;
7006 } else {
7007 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007008 }
drh715ff302008-12-03 22:32:44 +00007009 }else{
drh4bf66fd2015-02-19 02:43:02 +00007010 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007011 }
drh7ed97b92010-01-20 13:07:21 +00007012 if( rc==SQLITE_OK ){
7013 char writeBuffer[PROXY_MAXCONCHLEN];
7014 int writeSize = 0;
7015
7016 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7017 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7018 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007019 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7020 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007021 }else{
7022 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7023 }
7024 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007025 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007026 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007027 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007028 /* If we created a new conch file (not just updated the contents of a
7029 ** valid conch file), try to match the permissions of the database
7030 */
7031 if( rc==SQLITE_OK && createConch ){
7032 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007033 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007034 if( err==0 ){
7035 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7036 S_IROTH|S_IWOTH);
7037 /* try to match the database file R/W permissions, ignore failure */
7038#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007039 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007040#else
drhff812312011-02-23 13:33:46 +00007041 do{
drhe562be52011-03-02 18:01:10 +00007042 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007043 }while( rc==(-1) && errno==EINTR );
7044 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007045 int code = errno;
7046 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7047 cmode, code, strerror(code));
7048 } else {
7049 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7050 }
7051 }else{
7052 int code = errno;
7053 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7054 err, code, strerror(code));
7055#endif
7056 }
drh715ff302008-12-03 22:32:44 +00007057 }
7058 }
drh7ed97b92010-01-20 13:07:21 +00007059 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7060
7061 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007062 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007063 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007064 int fd;
drh7ed97b92010-01-20 13:07:21 +00007065 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007066 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007067 }
7068 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007069 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007070 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007071 if( fd>=0 ){
7072 pFile->h = fd;
7073 }else{
drh9978c972010-02-23 17:36:32 +00007074 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007075 during locking */
7076 }
7077 }
7078 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7079 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7080 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7081 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7082 /* we couldn't create the proxy lock file with the old lock file path
7083 ** so try again via auto-naming
7084 */
7085 forceNewLockPath = 1;
7086 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007087 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007088 }
7089 }
7090 if( rc==SQLITE_OK ){
7091 /* Need to make a copy of path if we extracted the value
7092 ** from the conch file or the path was allocated on the stack
7093 */
7094 if( tempLockPath ){
7095 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7096 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007097 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007098 }
7099 }
7100 }
7101 if( rc==SQLITE_OK ){
7102 pCtx->conchHeld = 1;
7103
7104 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7105 afpLockingContext *afpCtx;
7106 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7107 afpCtx->dbPath = pCtx->lockProxyPath;
7108 }
7109 } else {
7110 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7111 }
drh308c2a52010-05-14 11:30:18 +00007112 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7113 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007114 return rc;
drh308c2a52010-05-14 11:30:18 +00007115 } while (1); /* in case we need to retry the :auto: lock file -
7116 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007117 }
7118}
7119
7120/*
7121** If pFile holds a lock on a conch file, then release that lock.
7122*/
7123static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007124 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007125 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7126 unixFile *conchFile; /* Name of the conch file */
7127
7128 pCtx = (proxyLockingContext *)pFile->lockingContext;
7129 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007130 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007131 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007132 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007133 if( pCtx->conchHeld>0 ){
7134 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7135 }
drh715ff302008-12-03 22:32:44 +00007136 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007137 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7138 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007139 return rc;
7140}
7141
7142/*
7143** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007144** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007145** Make *pConchPath point to the new name. Return SQLITE_OK on success
7146** or SQLITE_NOMEM if unable to obtain memory.
7147**
7148** The caller is responsible for ensuring that the allocated memory
7149** space is eventually freed.
7150**
7151** *pConchPath is set to NULL if a memory allocation error occurs.
7152*/
7153static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7154 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007155 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007156 char *conchPath; /* buffer in which to construct conch name */
7157
7158 /* Allocate space for the conch filename and initialize the name to
7159 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007160 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007161 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007162 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007163 }
7164 memcpy(conchPath, dbPath, len+1);
7165
7166 /* now insert a "." before the last / character */
7167 for( i=(len-1); i>=0; i-- ){
7168 if( conchPath[i]=='/' ){
7169 i++;
7170 break;
7171 }
7172 }
7173 conchPath[i]='.';
7174 while ( i<len ){
7175 conchPath[i+1]=dbPath[i];
7176 i++;
7177 }
7178
7179 /* append the "-conch" suffix to the file */
7180 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007181 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007182
7183 return SQLITE_OK;
7184}
7185
7186
7187/* Takes a fully configured proxy locking-style unix file and switches
7188** the local lock file path
7189*/
7190static int switchLockProxyPath(unixFile *pFile, const char *path) {
7191 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7192 char *oldPath = pCtx->lockProxyPath;
7193 int rc = SQLITE_OK;
7194
drh308c2a52010-05-14 11:30:18 +00007195 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007196 return SQLITE_BUSY;
7197 }
7198
7199 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7200 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7201 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7202 return SQLITE_OK;
7203 }else{
7204 unixFile *lockProxy = pCtx->lockProxy;
7205 pCtx->lockProxy=NULL;
7206 pCtx->conchHeld = 0;
7207 if( lockProxy!=NULL ){
7208 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7209 if( rc ) return rc;
7210 sqlite3_free(lockProxy);
7211 }
7212 sqlite3_free(oldPath);
7213 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7214 }
7215
7216 return rc;
7217}
7218
7219/*
7220** pFile is a file that has been opened by a prior xOpen call. dbPath
7221** is a string buffer at least MAXPATHLEN+1 characters in size.
7222**
7223** This routine find the filename associated with pFile and writes it
7224** int dbPath.
7225*/
7226static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007227#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007228 if( pFile->pMethod == &afpIoMethods ){
7229 /* afp style keeps a reference to the db path in the filePath field
7230 ** of the struct */
drhea678832008-12-10 19:26:22 +00007231 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007232 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7233 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007234 } else
drh715ff302008-12-03 22:32:44 +00007235#endif
7236 if( pFile->pMethod == &dotlockIoMethods ){
7237 /* dot lock style uses the locking context to store the dot lock
7238 ** file path */
7239 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7240 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7241 }else{
7242 /* all other styles use the locking context to store the db file path */
7243 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007244 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007245 }
7246 return SQLITE_OK;
7247}
7248
7249/*
7250** Takes an already filled in unix file and alters it so all file locking
7251** will be performed on the local proxy lock file. The following fields
7252** are preserved in the locking context so that they can be restored and
7253** the unix structure properly cleaned up at close time:
7254** ->lockingContext
7255** ->pMethod
7256*/
7257static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7258 proxyLockingContext *pCtx;
7259 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7260 char *lockPath=NULL;
7261 int rc = SQLITE_OK;
7262
drh308c2a52010-05-14 11:30:18 +00007263 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007264 return SQLITE_BUSY;
7265 }
7266 proxyGetDbPathForUnixFile(pFile, dbPath);
7267 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7268 lockPath=NULL;
7269 }else{
7270 lockPath=(char *)path;
7271 }
7272
drh308c2a52010-05-14 11:30:18 +00007273 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007274 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007275
drhf3cdcdc2015-04-29 16:50:28 +00007276 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007277 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007278 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007279 }
7280 memset(pCtx, 0, sizeof(*pCtx));
7281
7282 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7283 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007284 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7285 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7286 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7287 ** (c) the file system is read-only, then enable no-locking access.
7288 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7289 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7290 */
7291 struct statfs fsInfo;
7292 struct stat conchInfo;
7293 int goLockless = 0;
7294
drh99ab3b12011-03-02 15:09:07 +00007295 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007296 int err = errno;
7297 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7298 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7299 }
7300 }
7301 if( goLockless ){
7302 pCtx->conchHeld = -1; /* read only FS/ lockless */
7303 rc = SQLITE_OK;
7304 }
7305 }
drh715ff302008-12-03 22:32:44 +00007306 }
7307 if( rc==SQLITE_OK && lockPath ){
7308 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7309 }
7310
7311 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007312 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7313 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007314 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007315 }
7316 }
7317 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007318 /* all memory is allocated, proxys are created and assigned,
7319 ** switch the locking context and pMethod then return.
7320 */
drh715ff302008-12-03 22:32:44 +00007321 pCtx->oldLockingContext = pFile->lockingContext;
7322 pFile->lockingContext = pCtx;
7323 pCtx->pOldMethod = pFile->pMethod;
7324 pFile->pMethod = &proxyIoMethods;
7325 }else{
7326 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007327 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007328 sqlite3_free(pCtx->conchFile);
7329 }
drhd56b1212010-08-11 06:14:15 +00007330 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007331 sqlite3_free(pCtx->conchFilePath);
7332 sqlite3_free(pCtx);
7333 }
drh308c2a52010-05-14 11:30:18 +00007334 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7335 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007336 return rc;
7337}
7338
7339
7340/*
7341** This routine handles sqlite3_file_control() calls that are specific
7342** to proxy locking.
7343*/
7344static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7345 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007346 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007347 unixFile *pFile = (unixFile*)id;
7348 if( pFile->pMethod == &proxyIoMethods ){
7349 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7350 proxyTakeConch(pFile);
7351 if( pCtx->lockProxyPath ){
7352 *(const char **)pArg = pCtx->lockProxyPath;
7353 }else{
7354 *(const char **)pArg = ":auto: (not held)";
7355 }
7356 } else {
7357 *(const char **)pArg = NULL;
7358 }
7359 return SQLITE_OK;
7360 }
drh4bf66fd2015-02-19 02:43:02 +00007361 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007362 unixFile *pFile = (unixFile*)id;
7363 int rc = SQLITE_OK;
7364 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7365 if( pArg==NULL || (const char *)pArg==0 ){
7366 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007367 /* turn off proxy locking - not supported. If support is added for
7368 ** switching proxy locking mode off then it will need to fail if
7369 ** the journal mode is WAL mode.
7370 */
drh715ff302008-12-03 22:32:44 +00007371 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7372 }else{
7373 /* turn off proxy locking - already off - NOOP */
7374 rc = SQLITE_OK;
7375 }
7376 }else{
7377 const char *proxyPath = (const char *)pArg;
7378 if( isProxyStyle ){
7379 proxyLockingContext *pCtx =
7380 (proxyLockingContext*)pFile->lockingContext;
7381 if( !strcmp(pArg, ":auto:")
7382 || (pCtx->lockProxyPath &&
7383 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7384 ){
7385 rc = SQLITE_OK;
7386 }else{
7387 rc = switchLockProxyPath(pFile, proxyPath);
7388 }
7389 }else{
7390 /* turn on proxy file locking */
7391 rc = proxyTransformUnixFile(pFile, proxyPath);
7392 }
7393 }
7394 return rc;
7395 }
7396 default: {
7397 assert( 0 ); /* The call assures that only valid opcodes are sent */
7398 }
7399 }
7400 /*NOTREACHED*/
7401 return SQLITE_ERROR;
7402}
7403
7404/*
7405** Within this division (the proxying locking implementation) the procedures
7406** above this point are all utilities. The lock-related methods of the
7407** proxy-locking sqlite3_io_method object follow.
7408*/
7409
7410
7411/*
7412** This routine checks if there is a RESERVED lock held on the specified
7413** file by this or any other process. If such a lock is held, set *pResOut
7414** to a non-zero value otherwise *pResOut is set to zero. The return value
7415** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7416*/
7417static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7418 unixFile *pFile = (unixFile*)id;
7419 int rc = proxyTakeConch(pFile);
7420 if( rc==SQLITE_OK ){
7421 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007422 if( pCtx->conchHeld>0 ){
7423 unixFile *proxy = pCtx->lockProxy;
7424 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7425 }else{ /* conchHeld < 0 is lockless */
7426 pResOut=0;
7427 }
drh715ff302008-12-03 22:32:44 +00007428 }
7429 return rc;
7430}
7431
7432/*
drh308c2a52010-05-14 11:30:18 +00007433** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007434** of the following:
7435**
7436** (1) SHARED_LOCK
7437** (2) RESERVED_LOCK
7438** (3) PENDING_LOCK
7439** (4) EXCLUSIVE_LOCK
7440**
7441** Sometimes when requesting one lock state, additional lock states
7442** are inserted in between. The locking might fail on one of the later
7443** transitions leaving the lock state different from what it started but
7444** still short of its goal. The following chart shows the allowed
7445** transitions and the inserted intermediate states:
7446**
7447** UNLOCKED -> SHARED
7448** SHARED -> RESERVED
7449** SHARED -> (PENDING) -> EXCLUSIVE
7450** RESERVED -> (PENDING) -> EXCLUSIVE
7451** PENDING -> EXCLUSIVE
7452**
7453** This routine will only increase a lock. Use the sqlite3OsUnlock()
7454** routine to lower a locking level.
7455*/
drh308c2a52010-05-14 11:30:18 +00007456static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007457 unixFile *pFile = (unixFile*)id;
7458 int rc = proxyTakeConch(pFile);
7459 if( rc==SQLITE_OK ){
7460 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007461 if( pCtx->conchHeld>0 ){
7462 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007463 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7464 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007465 }else{
7466 /* conchHeld < 0 is lockless */
7467 }
drh715ff302008-12-03 22:32:44 +00007468 }
7469 return rc;
7470}
7471
7472
7473/*
drh308c2a52010-05-14 11:30:18 +00007474** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007475** must be either NO_LOCK or SHARED_LOCK.
7476**
7477** If the locking level of the file descriptor is already at or below
7478** the requested locking level, this routine is a no-op.
7479*/
drh308c2a52010-05-14 11:30:18 +00007480static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007481 unixFile *pFile = (unixFile*)id;
7482 int rc = proxyTakeConch(pFile);
7483 if( rc==SQLITE_OK ){
7484 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007485 if( pCtx->conchHeld>0 ){
7486 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007487 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7488 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007489 }else{
7490 /* conchHeld < 0 is lockless */
7491 }
drh715ff302008-12-03 22:32:44 +00007492 }
7493 return rc;
7494}
7495
7496/*
7497** Close a file that uses proxy locks.
7498*/
7499static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007500 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007501 unixFile *pFile = (unixFile*)id;
7502 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7503 unixFile *lockProxy = pCtx->lockProxy;
7504 unixFile *conchFile = pCtx->conchFile;
7505 int rc = SQLITE_OK;
7506
7507 if( lockProxy ){
7508 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7509 if( rc ) return rc;
7510 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7511 if( rc ) return rc;
7512 sqlite3_free(lockProxy);
7513 pCtx->lockProxy = 0;
7514 }
7515 if( conchFile ){
7516 if( pCtx->conchHeld ){
7517 rc = proxyReleaseConch(pFile);
7518 if( rc ) return rc;
7519 }
7520 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7521 if( rc ) return rc;
7522 sqlite3_free(conchFile);
7523 }
drhd56b1212010-08-11 06:14:15 +00007524 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007525 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007526 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007527 /* restore the original locking context and pMethod then close it */
7528 pFile->lockingContext = pCtx->oldLockingContext;
7529 pFile->pMethod = pCtx->pOldMethod;
7530 sqlite3_free(pCtx);
7531 return pFile->pMethod->xClose(id);
7532 }
7533 return SQLITE_OK;
7534}
7535
7536
7537
drhd2cb50b2009-01-09 21:41:17 +00007538#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007539/*
7540** The proxy locking style is intended for use with AFP filesystems.
7541** And since AFP is only supported on MacOSX, the proxy locking is also
7542** restricted to MacOSX.
7543**
7544**
7545******************* End of the proxy lock implementation **********************
7546******************************************************************************/
7547
drh734c9862008-11-28 15:37:20 +00007548/*
danielk1977e339d652008-06-28 11:23:00 +00007549** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007550**
7551** This routine registers all VFS implementations for unix-like operating
7552** systems. This routine, and the sqlite3_os_end() routine that follows,
7553** should be the only routines in this file that are visible from other
7554** files.
drh6b9d6dd2008-12-03 19:34:47 +00007555**
7556** This routine is called once during SQLite initialization and by a
7557** single thread. The memory allocation and mutex subsystems have not
7558** necessarily been initialized when this routine is called, and so they
7559** should not be used.
drh153c62c2007-08-24 03:51:33 +00007560*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007561int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007562 /*
7563 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007564 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7565 ** to the "finder" function. (pAppData is a pointer to a pointer because
7566 ** silly C90 rules prohibit a void* from being cast to a function pointer
7567 ** and so we have to go through the intermediate pointer to avoid problems
7568 ** when compiling with -pedantic-errors on GCC.)
7569 **
7570 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007571 ** finder-function. The finder-function returns a pointer to the
7572 ** sqlite_io_methods object that implements the desired locking
7573 ** behaviors. See the division above that contains the IOMETHODS
7574 ** macro for addition information on finder-functions.
7575 **
7576 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7577 ** object. But the "autolockIoFinder" available on MacOSX does a little
7578 ** more than that; it looks at the filesystem type that hosts the
7579 ** database file and tries to choose an locking method appropriate for
7580 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007581 */
drh7708e972008-11-29 00:56:52 +00007582 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007583 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007584 sizeof(unixFile), /* szOsFile */ \
7585 MAX_PATHNAME, /* mxPathname */ \
7586 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007587 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007588 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007589 unixOpen, /* xOpen */ \
7590 unixDelete, /* xDelete */ \
7591 unixAccess, /* xAccess */ \
7592 unixFullPathname, /* xFullPathname */ \
7593 unixDlOpen, /* xDlOpen */ \
7594 unixDlError, /* xDlError */ \
7595 unixDlSym, /* xDlSym */ \
7596 unixDlClose, /* xDlClose */ \
7597 unixRandomness, /* xRandomness */ \
7598 unixSleep, /* xSleep */ \
7599 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007600 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007601 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007602 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007603 unixGetSystemCall, /* xGetSystemCall */ \
7604 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007605 }
7606
drh6b9d6dd2008-12-03 19:34:47 +00007607 /*
7608 ** All default VFSes for unix are contained in the following array.
7609 **
7610 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7611 ** by the SQLite core when the VFS is registered. So the following
7612 ** array cannot be const.
7613 */
danielk1977e339d652008-06-28 11:23:00 +00007614 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007615#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007616 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007617#elif OS_VXWORKS
7618 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007619#else
7620 UNIXVFS("unix", posixIoFinder ),
7621#endif
7622 UNIXVFS("unix-none", nolockIoFinder ),
7623 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007624 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007625#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007626 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007627#endif
drhe89b2912015-03-03 20:42:01 +00007628#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007629 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007630#endif
drhe89b2912015-03-03 20:42:01 +00007631#if SQLITE_ENABLE_LOCKING_STYLE
7632 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007633#endif
drhd2cb50b2009-01-09 21:41:17 +00007634#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007635 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007636 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007637 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007638#endif
drh153c62c2007-08-24 03:51:33 +00007639 };
drh6b9d6dd2008-12-03 19:34:47 +00007640 unsigned int i; /* Loop counter */
7641
drh2aa5a002011-04-13 13:42:25 +00007642 /* Double-check that the aSyscall[] array has been constructed
7643 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007644 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007645
drh6b9d6dd2008-12-03 19:34:47 +00007646 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007647 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007648 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007649 }
danielk1977c0fa4c52008-06-25 17:19:00 +00007650 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007651}
danielk1977e339d652008-06-28 11:23:00 +00007652
7653/*
drh6b9d6dd2008-12-03 19:34:47 +00007654** Shutdown the operating system interface.
7655**
7656** Some operating systems might need to do some cleanup in this routine,
7657** to release dynamically allocated objects. But not on unix.
7658** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007659*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007660int sqlite3_os_end(void){
7661 return SQLITE_OK;
7662}
drhdce8bdb2007-08-16 13:01:44 +00007663
danielk197729bafea2008-06-26 10:41:19 +00007664#endif /* SQLITE_OS_UNIX */