blob: 103df1d199f5645ba38b12eb9cdd785ac585efff [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/*
drh24efa542018-10-02 19:36:40 +0000139** If we are to be thread-safe, include the pthreads header.
drh9cbe6352005-11-29 03:13:21 +0000140*/
drhd677b3d2007-08-20 22:48:41 +0000141#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000142# include <pthread.h>
drh9cbe6352005-11-29 03:13:21 +0000143#endif
144
145/*
146** Default permissions when creating a new file
147*/
148#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
149# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
150#endif
151
danielk1977b4b47412007-08-17 15:53:36 +0000152/*
drh5adc60b2012-04-14 13:25:11 +0000153** Default permissions when creating auto proxy dir
154*/
aswiftaebf4132008-11-21 00:10:35 +0000155#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
156# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
157#endif
158
159/*
danielk1977b4b47412007-08-17 15:53:36 +0000160** Maximum supported path-length.
161*/
162#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000163
dane88ec182016-01-25 17:04:48 +0000164/*
165** Maximum supported symbolic links
166*/
167#define SQLITE_MAX_SYMLINKS 100
168
drh91eb93c2015-03-03 19:56:20 +0000169/* Always cast the getpid() return type for compatibility with
170** kernel modules in VxWorks. */
171#define osGetpid(X) (pid_t)getpid()
172
drh734c9862008-11-28 15:37:20 +0000173/*
drh734c9862008-11-28 15:37:20 +0000174** Only set the lastErrno if the error code is a real error and not
175** a normal expected return code of SQLITE_BUSY or SQLITE_OK
176*/
177#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
178
drhd91c68f2010-05-14 14:52:25 +0000179/* Forward references */
180typedef struct unixShm unixShm; /* Connection shared memory */
181typedef struct unixShmNode unixShmNode; /* Shared memory instance */
182typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
183typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000184
185/*
dane946c392009-08-22 11:39:46 +0000186** Sometimes, after a file handle is closed by SQLite, the file descriptor
187** cannot be closed immediately. In these cases, instances of the following
188** structure are used to store the file descriptor while waiting for an
189** opportunity to either close or reuse it.
190*/
dane946c392009-08-22 11:39:46 +0000191struct UnixUnusedFd {
192 int fd; /* File descriptor to close */
193 int flags; /* Flags this file descriptor was opened with */
194 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
195};
196
197/*
drh9b35ea62008-11-29 02:20:26 +0000198** The unixFile structure is subclass of sqlite3_file specific to the unix
199** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000200*/
drh054889e2005-11-30 03:20:31 +0000201typedef struct unixFile unixFile;
202struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000203 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000204 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000205 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000206 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000207 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000208 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000209 int lastErrno; /* The unix errno from last I/O error */
210 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000211 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000212 const char *zPath; /* Name of the file */
213 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000214 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000215#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000216 int nFetchOut; /* Number of outstanding xFetch refs */
217 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000218 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
219 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000220 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000221#endif
drh537dddf2012-10-26 13:46:24 +0000222 int sectorSize; /* Device sector size */
223 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000224#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000225 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000226#endif
drh7ed97b92010-01-20 13:07:21 +0000227#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000228 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000229#endif
drhf0119b22018-03-26 17:40:53 +0000230#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
231 unsigned iBusyTimeout; /* Wait this many millisec on locks */
232#endif
drh6c7d5c52008-11-21 20:32:33 +0000233#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000234 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000235#endif
drhd3d8c042012-05-29 17:02:40 +0000236#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000237 /* The next group of variables are used to track whether or not the
238 ** transaction counter in bytes 24-27 of database files are updated
239 ** whenever any part of the database changes. An assertion fault will
240 ** occur if a file is updated without also updating the transaction
241 ** counter. This test is made to avoid new problems similar to the
242 ** one described by ticket #3584.
243 */
244 unsigned char transCntrChng; /* True if the transaction counter changed */
245 unsigned char dbUpdate; /* True if any part of database file changed */
246 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000247
drh8f941bc2009-01-14 23:03:40 +0000248#endif
danf23da962013-03-23 21:00:41 +0000249
danielk1977967a4a12007-08-20 14:23:44 +0000250#ifdef SQLITE_TEST
251 /* In test mode, increase the size of this structure a bit so that
252 ** it is larger than the struct CrashFile defined in test6.c.
253 */
254 char aPadding[32];
255#endif
drh9cbe6352005-11-29 03:13:21 +0000256};
257
drhb00d8622014-01-01 15:18:36 +0000258/* This variable holds the process id (pid) from when the xRandomness()
259** method was called. If xOpen() is called from a different process id,
260** indicating that a fork() has occurred, the PRNG will be reset.
261*/
drh8cd5b252015-03-02 22:06:43 +0000262static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000263
drh0ccebe72005-06-07 22:22:50 +0000264/*
drha7e61d82011-03-12 17:02:57 +0000265** Allowed values for the unixFile.ctrlFlags bitmask:
266*/
drhf0b190d2011-07-26 16:03:07 +0000267#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
268#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
269#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000270#ifndef SQLITE_DISABLE_DIRSYNC
271# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
272#else
273# define UNIXFILE_DIRSYNC 0x00
274#endif
drhcb15f352011-12-23 01:04:17 +0000275#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000276#define UNIXFILE_DELETE 0x20 /* Delete on close */
277#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
278#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000279
280/*
drh198bf392006-01-06 21:52:49 +0000281** Include code that is common to all os_*.c files
282*/
283#include "os_common.h"
284
285/*
drh0ccebe72005-06-07 22:22:50 +0000286** Define various macros that are missing from some systems.
287*/
drhbbd42a62004-05-22 17:41:58 +0000288#ifndef O_LARGEFILE
289# define O_LARGEFILE 0
290#endif
291#ifdef SQLITE_DISABLE_LFS
292# undef O_LARGEFILE
293# define O_LARGEFILE 0
294#endif
295#ifndef O_NOFOLLOW
296# define O_NOFOLLOW 0
297#endif
298#ifndef O_BINARY
299# define O_BINARY 0
300#endif
301
302/*
drh2b4b5962005-06-15 17:47:55 +0000303** The threadid macro resolves to the thread-id or to 0. Used for
304** testing and debugging only.
305*/
drhd677b3d2007-08-20 22:48:41 +0000306#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000307#define threadid pthread_self()
308#else
309#define threadid 0
310#endif
311
drh99ab3b12011-03-02 15:09:07 +0000312/*
dane6ecd662013-04-01 17:56:59 +0000313** HAVE_MREMAP defaults to true on Linux and false everywhere else.
314*/
315#if !defined(HAVE_MREMAP)
316# if defined(__linux__) && defined(_GNU_SOURCE)
317# define HAVE_MREMAP 1
318# else
319# define HAVE_MREMAP 0
320# endif
321#endif
322
323/*
dan2ee53412014-09-06 16:49:40 +0000324** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
325** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
326*/
327#ifdef __ANDROID__
328# define lseek lseek64
329#endif
330
drhd76dba72017-07-22 16:00:34 +0000331#ifdef __linux__
332/*
333** Linux-specific IOCTL magic numbers used for controlling F2FS
334*/
danefe16972017-07-20 19:49:14 +0000335#define F2FS_IOCTL_MAGIC 0xf5
336#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
337#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
338#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
339#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000340#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000341#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000342#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000343
344
dan2ee53412014-09-06 16:49:40 +0000345/*
drh9a3baf12011-04-25 18:01:27 +0000346** Different Unix systems declare open() in different ways. Same use
347** open(const char*,int,mode_t). Others use open(const char*,int,...).
348** The difference is important when using a pointer to the function.
349**
350** The safest way to deal with the problem is to always use this wrapper
351** which always has the same well-defined interface.
352*/
353static int posixOpen(const char *zFile, int flags, int mode){
354 return open(zFile, flags, mode);
355}
356
drh90315a22011-08-10 01:52:12 +0000357/* Forward reference */
358static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000359static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000360
drh9a3baf12011-04-25 18:01:27 +0000361/*
drh99ab3b12011-03-02 15:09:07 +0000362** Many system calls are accessed through pointer-to-functions so that
363** they may be overridden at runtime to facilitate fault injection during
364** testing and sandboxing. The following array holds the names and pointers
365** to all overrideable system calls.
366*/
367static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000368 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000369 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
370 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000371} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000372 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
373#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000374
drh58ad5802011-03-23 22:02:23 +0000375 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000376#define osClose ((int(*)(int))aSyscall[1].pCurrent)
377
drh58ad5802011-03-23 22:02:23 +0000378 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000379#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
380
drh58ad5802011-03-23 22:02:23 +0000381 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000382#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
383
drh58ad5802011-03-23 22:02:23 +0000384 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000385#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
386
387/*
388** The DJGPP compiler environment looks mostly like Unix, but it
389** lacks the fcntl() system call. So redefine fcntl() to be something
390** that always succeeds. This means that locking does not occur under
391** DJGPP. But it is DOS - what did you expect?
392*/
393#ifdef __DJGPP__
394 { "fstat", 0, 0 },
395#define osFstat(a,b,c) 0
396#else
drh58ad5802011-03-23 22:02:23 +0000397 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000398#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
399#endif
400
drh58ad5802011-03-23 22:02:23 +0000401 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000402#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
403
drh58ad5802011-03-23 22:02:23 +0000404 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000405#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000406
drh58ad5802011-03-23 22:02:23 +0000407 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000408#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
409
drhe89b2912015-03-03 20:42:01 +0000410#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000411 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000412#else
drh58ad5802011-03-23 22:02:23 +0000413 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000414#endif
415#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
416
417#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000418 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000419#else
drh58ad5802011-03-23 22:02:23 +0000420 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000421#endif
drhf9986d92016-04-18 13:09:55 +0000422#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000423
drh58ad5802011-03-23 22:02:23 +0000424 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000425#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
426
drhe89b2912015-03-03 20:42:01 +0000427#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000428 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000429#else
drh58ad5802011-03-23 22:02:23 +0000430 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000431#endif
432#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
433 aSyscall[12].pCurrent)
434
435#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000436 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000437#else
drh58ad5802011-03-23 22:02:23 +0000438 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000439#endif
drhf9986d92016-04-18 13:09:55 +0000440#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000441 aSyscall[13].pCurrent)
442
drh6226ca22015-11-24 15:06:28 +0000443 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000444#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000445
446#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000447 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000448#else
drh58ad5802011-03-23 22:02:23 +0000449 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000450#endif
dan0fd7d862011-03-29 10:04:23 +0000451#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000452
drh036ac7f2011-08-08 23:18:05 +0000453 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
454#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
455
drh90315a22011-08-10 01:52:12 +0000456 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
457#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
458
drh9ef6bc42011-11-04 02:24:02 +0000459 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
460#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
461
462 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
463#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
464
drhe2258a22016-01-12 00:37:55 +0000465#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000466 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000467#else
468 { "fchown", (sqlite3_syscall_ptr)0, 0 },
469#endif
dand3eaebd2012-02-13 08:50:23 +0000470#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000471
drh26f625f2018-02-19 16:34:31 +0000472#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000473 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000474#else
475 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
476#endif
drh6226ca22015-11-24 15:06:28 +0000477#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
478
dan4dd51442013-08-26 14:30:25 +0000479#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000480 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
481#else
482 { "mmap", (sqlite3_syscall_ptr)0, 0 },
483#endif
drh6226ca22015-11-24 15:06:28 +0000484#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000485
drhe4a08f92016-01-08 19:17:30 +0000486#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000487 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000488#else
drha8299922016-01-08 22:31:00 +0000489 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000490#endif
drh62be1fa2017-12-09 01:02:33 +0000491#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000492
drhe4a08f92016-01-08 19:17:30 +0000493#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000494 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
495#else
496 { "mremap", (sqlite3_syscall_ptr)0, 0 },
497#endif
drh6226ca22015-11-24 15:06:28 +0000498#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
499
drh24dbeae2016-01-08 22:18:00 +0000500#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000501 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000502#else
503 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
504#endif
drh6226ca22015-11-24 15:06:28 +0000505#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000506
drhe2258a22016-01-12 00:37:55 +0000507#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000508 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000509#else
510 { "readlink", (sqlite3_syscall_ptr)0, 0 },
511#endif
drh6226ca22015-11-24 15:06:28 +0000512#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000513
danaf1b36b2016-01-25 18:43:05 +0000514#if defined(HAVE_LSTAT)
515 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
516#else
517 { "lstat", (sqlite3_syscall_ptr)0, 0 },
518#endif
dancaf6b152016-01-25 18:05:49 +0000519#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000520
drhb5d013e2017-10-25 16:14:12 +0000521#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
dan16f39b62018-09-18 19:40:18 +0000522# ifdef __ANDROID__
523 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
524# else
danefe16972017-07-20 19:49:14 +0000525 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
dan16f39b62018-09-18 19:40:18 +0000526# endif
drhb5d013e2017-10-25 16:14:12 +0000527#else
528 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
529#endif
dan9d709542017-07-21 21:06:24 +0000530#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
danefe16972017-07-20 19:49:14 +0000531
drhe562be52011-03-02 18:01:10 +0000532}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000533
drh6226ca22015-11-24 15:06:28 +0000534
535/*
536** On some systems, calls to fchown() will trigger a message in a security
537** log if they come from non-root processes. So avoid calling fchown() if
538** we are not running as root.
539*/
540static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000541#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000542 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000543#else
544 return 0;
drh6226ca22015-11-24 15:06:28 +0000545#endif
546}
547
drh99ab3b12011-03-02 15:09:07 +0000548/*
549** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000550** "unix" VFSes. Return SQLITE_OK opon successfully updating the
551** system call pointer, or SQLITE_NOTFOUND if there is no configurable
552** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000553*/
554static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000555 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
556 const char *zName, /* Name of system call to override */
557 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000558){
drh58ad5802011-03-23 22:02:23 +0000559 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000560 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000561
562 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000563 if( zName==0 ){
564 /* If no zName is given, restore all system calls to their default
565 ** settings and return NULL
566 */
dan51438a72011-04-02 17:00:47 +0000567 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000568 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
569 if( aSyscall[i].pDefault ){
570 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000571 }
572 }
573 }else{
574 /* If zName is specified, operate on only the one system call
575 ** specified.
576 */
577 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
578 if( strcmp(zName, aSyscall[i].zName)==0 ){
579 if( aSyscall[i].pDefault==0 ){
580 aSyscall[i].pDefault = aSyscall[i].pCurrent;
581 }
drh1df30962011-03-02 19:06:42 +0000582 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000583 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
584 aSyscall[i].pCurrent = pNewFunc;
585 break;
586 }
587 }
588 }
589 return rc;
590}
591
drh1df30962011-03-02 19:06:42 +0000592/*
593** Return the value of a system call. Return NULL if zName is not a
594** recognized system call name. NULL is also returned if the system call
595** is currently undefined.
596*/
drh58ad5802011-03-23 22:02:23 +0000597static sqlite3_syscall_ptr unixGetSystemCall(
598 sqlite3_vfs *pNotUsed,
599 const char *zName
600){
601 unsigned int i;
602
603 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000604 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
605 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
606 }
607 return 0;
608}
609
610/*
611** Return the name of the first system call after zName. If zName==NULL
612** then return the name of the first system call. Return NULL if zName
613** is the last system call or if zName is not the name of a valid
614** system call.
615*/
616static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000617 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000618
619 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000620 if( zName ){
621 for(i=0; i<ArraySize(aSyscall)-1; i++){
622 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000623 }
624 }
dan0fd7d862011-03-29 10:04:23 +0000625 for(i++; i<ArraySize(aSyscall); i++){
626 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000627 }
628 return 0;
629}
630
drhad4f1e52011-03-04 15:43:57 +0000631/*
drh77a3fdc2013-08-30 14:24:12 +0000632** Do not accept any file descriptor less than this value, in order to avoid
633** opening database file using file descriptors that are commonly used for
634** standard input, output, and error.
635*/
636#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
637# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
638#endif
639
640/*
drh8c815d12012-02-13 20:16:37 +0000641** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000642** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000643**
644** If the file creation mode "m" is 0 then set it to the default for
645** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
646** 0644) as modified by the system umask. If m is not 0, then
647** make the file creation mode be exactly m ignoring the umask.
648**
649** The m parameter will be non-zero only when creating -wal, -journal,
650** and -shm files. We want those files to have *exactly* the same
651** permissions as their original database, unadulterated by the umask.
652** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
653** transaction crashes and leaves behind hot journals, then any
654** process that is able to write to the database will also be able to
655** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000656*/
drh8c815d12012-02-13 20:16:37 +0000657static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000658 int fd;
drhe1186ab2013-01-04 20:45:13 +0000659 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000660 while(1){
drh5adc60b2012-04-14 13:25:11 +0000661#if defined(O_CLOEXEC)
662 fd = osOpen(z,f|O_CLOEXEC,m2);
663#else
664 fd = osOpen(z,f,m2);
665#endif
drh5128d002013-08-30 06:20:23 +0000666 if( fd<0 ){
667 if( errno==EINTR ) continue;
668 break;
669 }
drh77a3fdc2013-08-30 14:24:12 +0000670 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000671 osClose(fd);
672 sqlite3_log(SQLITE_WARNING,
673 "attempt to open \"%s\" as file descriptor %d", z, fd);
674 fd = -1;
675 if( osOpen("/dev/null", f, m)<0 ) break;
676 }
drhe1186ab2013-01-04 20:45:13 +0000677 if( fd>=0 ){
678 if( m!=0 ){
679 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000680 if( osFstat(fd, &statbuf)==0
681 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000682 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000683 ){
drhe1186ab2013-01-04 20:45:13 +0000684 osFchmod(fd, m);
685 }
686 }
drh5adc60b2012-04-14 13:25:11 +0000687#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000688 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000689#endif
drhe1186ab2013-01-04 20:45:13 +0000690 }
drh5adc60b2012-04-14 13:25:11 +0000691 return fd;
drhad4f1e52011-03-04 15:43:57 +0000692}
danielk197713adf8a2004-06-03 16:08:41 +0000693
drh107886a2008-11-21 22:21:50 +0000694/*
dan9359c7b2009-08-21 08:29:10 +0000695** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000696** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000697** vxworksFileId objects used by this file, all of which may be
698** shared by multiple threads.
699**
700** Function unixMutexHeld() is used to assert() that the global mutex
701** is held when required. This function is only used as part of assert()
702** statements. e.g.
703**
704** unixEnterMutex()
705** assert( unixMutexHeld() );
706** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000707**
708** To prevent deadlock, the global unixBigLock must must be acquired
709** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
710** OK to get the pLockMutex without holding unixBigLock first, but if
711** that happens, the unixBigLock mutex must not be acquired until after
712** pLockMutex is released.
713**
714** OK: enter(unixBigLock), enter(pLockInfo)
715** OK: enter(unixBigLock)
716** OK: enter(pLockInfo)
717** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000718*/
drh56115892018-02-05 16:39:12 +0000719static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000720static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000721 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000722 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000723}
724static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000725 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000726 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000727}
dan9359c7b2009-08-21 08:29:10 +0000728#ifdef SQLITE_DEBUG
729static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000730 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000731}
732#endif
drh107886a2008-11-21 22:21:50 +0000733
drh734c9862008-11-28 15:37:20 +0000734
mistachkinfb383e92015-04-16 03:24:38 +0000735#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000736/*
737** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000738** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000739** integer lock-type.
740*/
drh308c2a52010-05-14 11:30:18 +0000741static const char *azFileLock(int eFileLock){
742 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000743 case NO_LOCK: return "NONE";
744 case SHARED_LOCK: return "SHARED";
745 case RESERVED_LOCK: return "RESERVED";
746 case PENDING_LOCK: return "PENDING";
747 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000748 }
749 return "ERROR";
750}
751#endif
752
753#ifdef SQLITE_LOCK_TRACE
754/*
755** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000756**
drh734c9862008-11-28 15:37:20 +0000757** This routine is used for troubleshooting locks on multithreaded
758** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
759** command-line option on the compiler. This code is normally
760** turned off.
761*/
762static int lockTrace(int fd, int op, struct flock *p){
763 char *zOpName, *zType;
764 int s;
765 int savedErrno;
766 if( op==F_GETLK ){
767 zOpName = "GETLK";
768 }else if( op==F_SETLK ){
769 zOpName = "SETLK";
770 }else{
drh99ab3b12011-03-02 15:09:07 +0000771 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000772 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
773 return s;
774 }
775 if( p->l_type==F_RDLCK ){
776 zType = "RDLCK";
777 }else if( p->l_type==F_WRLCK ){
778 zType = "WRLCK";
779 }else if( p->l_type==F_UNLCK ){
780 zType = "UNLCK";
781 }else{
782 assert( 0 );
783 }
784 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000785 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000786 savedErrno = errno;
787 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
788 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
789 (int)p->l_pid, s);
790 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
791 struct flock l2;
792 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000793 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000794 if( l2.l_type==F_RDLCK ){
795 zType = "RDLCK";
796 }else if( l2.l_type==F_WRLCK ){
797 zType = "WRLCK";
798 }else if( l2.l_type==F_UNLCK ){
799 zType = "UNLCK";
800 }else{
801 assert( 0 );
802 }
803 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
804 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
805 }
806 errno = savedErrno;
807 return s;
808}
drh99ab3b12011-03-02 15:09:07 +0000809#undef osFcntl
810#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000811#endif /* SQLITE_LOCK_TRACE */
812
drhff812312011-02-23 13:33:46 +0000813/*
814** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000815**
drhe6d41732015-02-21 00:49:00 +0000816** All calls to ftruncate() within this file should be made through
817** this wrapper. On the Android platform, bypassing the logic below
818** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000819*/
drhff812312011-02-23 13:33:46 +0000820static int robust_ftruncate(int h, sqlite3_int64 sz){
821 int rc;
dan2ee53412014-09-06 16:49:40 +0000822#ifdef __ANDROID__
823 /* On Android, ftruncate() always uses 32-bit offsets, even if
824 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000825 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000826 ** such attempts. */
827 if( sz>(sqlite3_int64)0x7FFFFFFF ){
828 rc = SQLITE_OK;
829 }else
830#endif
drh99ab3b12011-03-02 15:09:07 +0000831 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000832 return rc;
833}
drh734c9862008-11-28 15:37:20 +0000834
835/*
836** This routine translates a standard POSIX errno code into something
837** useful to the clients of the sqlite3 functions. Specifically, it is
838** intended to translate a variety of "try again" errors into SQLITE_BUSY
839** and a variety of "please close the file descriptor NOW" errors into
840** SQLITE_IOERR
841**
842** Errors during initialization of locks, or file system support for locks,
843** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
844*/
845static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000846 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
847 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
848 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
849 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000850 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000851 case EACCES:
drh734c9862008-11-28 15:37:20 +0000852 case EAGAIN:
853 case ETIMEDOUT:
854 case EBUSY:
855 case EINTR:
856 case ENOLCK:
857 /* random NFS retry error, unless during file system support
858 * introspection, in which it actually means what it says */
859 return SQLITE_BUSY;
860
drh734c9862008-11-28 15:37:20 +0000861 case EPERM:
862 return SQLITE_PERM;
863
drh734c9862008-11-28 15:37:20 +0000864 default:
865 return sqliteIOErr;
866 }
867}
868
869
drh734c9862008-11-28 15:37:20 +0000870/******************************************************************************
871****************** Begin Unique File ID Utility Used By VxWorks ***************
872**
873** On most versions of unix, we can get a unique ID for a file by concatenating
874** the device number and the inode number. But this does not work on VxWorks.
875** On VxWorks, a unique file id must be based on the canonical filename.
876**
877** A pointer to an instance of the following structure can be used as a
878** unique file ID in VxWorks. Each instance of this structure contains
879** a copy of the canonical filename. There is also a reference count.
880** The structure is reclaimed when the number of pointers to it drops to
881** zero.
882**
883** There are never very many files open at one time and lookups are not
884** a performance-critical path, so it is sufficient to put these
885** structures on a linked list.
886*/
887struct vxworksFileId {
888 struct vxworksFileId *pNext; /* Next in a list of them all */
889 int nRef; /* Number of references to this one */
890 int nName; /* Length of the zCanonicalName[] string */
891 char *zCanonicalName; /* Canonical filename */
892};
893
894#if OS_VXWORKS
895/*
drh9b35ea62008-11-29 02:20:26 +0000896** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000897** variable:
898*/
899static struct vxworksFileId *vxworksFileList = 0;
900
901/*
902** Simplify a filename into its canonical form
903** by making the following changes:
904**
905** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000906** * convert /./ into just /
907** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000908**
909** Changes are made in-place. Return the new name length.
910**
911** The original filename is in z[0..n-1]. Return the number of
912** characters in the simplified name.
913*/
914static int vxworksSimplifyName(char *z, int n){
915 int i, j;
916 while( n>1 && z[n-1]=='/' ){ n--; }
917 for(i=j=0; i<n; i++){
918 if( z[i]=='/' ){
919 if( z[i+1]=='/' ) continue;
920 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
921 i += 1;
922 continue;
923 }
924 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
925 while( j>0 && z[j-1]!='/' ){ j--; }
926 if( j>0 ){ j--; }
927 i += 2;
928 continue;
929 }
930 }
931 z[j++] = z[i];
932 }
933 z[j] = 0;
934 return j;
935}
936
937/*
938** Find a unique file ID for the given absolute pathname. Return
939** a pointer to the vxworksFileId object. This pointer is the unique
940** file ID.
941**
942** The nRef field of the vxworksFileId object is incremented before
943** the object is returned. A new vxworksFileId object is created
944** and added to the global list if necessary.
945**
946** If a memory allocation error occurs, return NULL.
947*/
948static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
949 struct vxworksFileId *pNew; /* search key and new file ID */
950 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
951 int n; /* Length of zAbsoluteName string */
952
953 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000954 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000955 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000956 if( pNew==0 ) return 0;
957 pNew->zCanonicalName = (char*)&pNew[1];
958 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
959 n = vxworksSimplifyName(pNew->zCanonicalName, n);
960
961 /* Search for an existing entry that matching the canonical name.
962 ** If found, increment the reference count and return a pointer to
963 ** the existing file ID.
964 */
965 unixEnterMutex();
966 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
967 if( pCandidate->nName==n
968 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
969 ){
970 sqlite3_free(pNew);
971 pCandidate->nRef++;
972 unixLeaveMutex();
973 return pCandidate;
974 }
975 }
976
977 /* No match was found. We will make a new file ID */
978 pNew->nRef = 1;
979 pNew->nName = n;
980 pNew->pNext = vxworksFileList;
981 vxworksFileList = pNew;
982 unixLeaveMutex();
983 return pNew;
984}
985
986/*
987** Decrement the reference count on a vxworksFileId object. Free
988** the object when the reference count reaches zero.
989*/
990static void vxworksReleaseFileId(struct vxworksFileId *pId){
991 unixEnterMutex();
992 assert( pId->nRef>0 );
993 pId->nRef--;
994 if( pId->nRef==0 ){
995 struct vxworksFileId **pp;
996 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
997 assert( *pp==pId );
998 *pp = pId->pNext;
999 sqlite3_free(pId);
1000 }
1001 unixLeaveMutex();
1002}
1003#endif /* OS_VXWORKS */
1004/*************** End of Unique File ID Utility Used By VxWorks ****************
1005******************************************************************************/
1006
1007
1008/******************************************************************************
1009*************************** Posix Advisory Locking ****************************
1010**
drh9b35ea62008-11-29 02:20:26 +00001011** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001012** section 6.5.2.2 lines 483 through 490 specify that when a process
1013** sets or clears a lock, that operation overrides any prior locks set
1014** by the same process. It does not explicitly say so, but this implies
1015** that it overrides locks set by the same process using a different
1016** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001017**
1018** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001019** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1020**
1021** Suppose ./file1 and ./file2 are really the same file (because
1022** one is a hard or symbolic link to the other) then if you set
1023** an exclusive lock on fd1, then try to get an exclusive lock
1024** on fd2, it works. I would have expected the second lock to
1025** fail since there was already a lock on the file due to fd1.
1026** But not so. Since both locks came from the same process, the
1027** second overrides the first, even though they were on different
1028** file descriptors opened on different file names.
1029**
drh734c9862008-11-28 15:37:20 +00001030** This means that we cannot use POSIX locks to synchronize file access
1031** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001032** to synchronize access for threads in separate processes, but not
1033** threads within the same process.
1034**
1035** To work around the problem, SQLite has to manage file locks internally
1036** on its own. Whenever a new database is opened, we have to find the
1037** specific inode of the database file (the inode is determined by the
1038** st_dev and st_ino fields of the stat structure that fstat() fills in)
1039** and check for locks already existing on that inode. When locks are
1040** created or removed, we have to look at our own internal record of the
1041** locks to see if another thread has previously set a lock on that same
1042** inode.
1043**
drh9b35ea62008-11-29 02:20:26 +00001044** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1045** For VxWorks, we have to use the alternative unique ID system based on
1046** canonical filename and implemented in the previous division.)
1047**
danielk1977ad94b582007-08-20 06:44:22 +00001048** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001049** descriptor. It is now a structure that holds the integer file
1050** descriptor and a pointer to a structure that describes the internal
1051** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001052** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001053** point to the same locking structure. The locking structure keeps
1054** a reference count (so we will know when to delete it) and a "cnt"
1055** field that tells us its internal lock status. cnt==0 means the
1056** file is unlocked. cnt==-1 means the file has an exclusive lock.
1057** cnt>0 means there are cnt shared locks on the file.
1058**
1059** Any attempt to lock or unlock a file first checks the locking
1060** structure. The fcntl() system call is only invoked to set a
1061** POSIX lock if the internal lock structure transitions between
1062** a locked and an unlocked state.
1063**
drh734c9862008-11-28 15:37:20 +00001064** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001065**
1066** If you close a file descriptor that points to a file that has locks,
1067** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001068** released. To work around this problem, each unixInodeInfo object
1069** maintains a count of the number of pending locks on tha inode.
1070** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001071** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001072** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001073** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001074** be closed and that list is walked (and cleared) when the last lock
1075** clears.
1076**
drh9b35ea62008-11-29 02:20:26 +00001077** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001078**
drh9b35ea62008-11-29 02:20:26 +00001079** Many older versions of linux use the LinuxThreads library which is
1080** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001081** A cannot be modified or overridden by a different thread B.
1082** Only thread A can modify the lock. Locking behavior is correct
1083** if the appliation uses the newer Native Posix Thread Library (NPTL)
1084** on linux - with NPTL a lock created by thread A can override locks
1085** in thread B. But there is no way to know at compile-time which
1086** threading library is being used. So there is no way to know at
1087** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001088** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001089** current process.
drh5fdae772004-06-29 03:29:00 +00001090**
drh8af6c222010-05-14 12:43:01 +00001091** SQLite used to support LinuxThreads. But support for LinuxThreads
1092** was dropped beginning with version 3.7.0. SQLite will still work with
1093** LinuxThreads provided that (1) there is no more than one connection
1094** per database file in the same process and (2) database connections
1095** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001096*/
1097
1098/*
1099** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001100** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001101*/
1102struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001103 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001104#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001105 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001106#else
drh25ef7f52016-12-05 20:06:45 +00001107 /* We are told that some versions of Android contain a bug that
1108 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1109 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1110 ** To work around this, always allocate 64-bits for the inode number.
1111 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1112 ** but that should not be a big deal. */
1113 /* WAS: ino_t ino; */
1114 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001115#endif
1116};
1117
1118/*
drhbbd42a62004-05-22 17:41:58 +00001119** An instance of the following structure is allocated for each open
drh24efa542018-10-02 19:36:40 +00001120** inode.
drhbbd42a62004-05-22 17:41:58 +00001121**
danielk1977ad94b582007-08-20 06:44:22 +00001122** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001123** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001124** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001125**
1126** Mutex rules:
1127**
drh095908e2018-08-13 20:46:18 +00001128** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001129** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001130** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001131**
1132** (2) When nRef>0, then the following fields are unchanging and can
1133** be read (but not written) without holding any mutex:
1134** fileId, pLockMutex
1135**
drhef52b362018-08-13 22:50:34 +00001136** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001137** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001138**
1139** Deadlock prevention: The global unixBigLock mutex may not
1140** be acquired while holding the pLockMutex mutex. If both unixBigLock
1141** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001142*/
drh8af6c222010-05-14 12:43:01 +00001143struct unixInodeInfo {
1144 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001145 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1146 int nShared; /* Number of SHARED locks held */
1147 int nLock; /* Number of outstanding file locks */
1148 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1149 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001150 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001151 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001152 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001153 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1154 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001155#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001156 unsigned long long sharedByte; /* for AFP simulated shared lock */
1157#endif
drh6c7d5c52008-11-21 20:32:33 +00001158#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001159 sem_t *pSem; /* Named POSIX semaphore */
1160 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001161#endif
drhbbd42a62004-05-22 17:41:58 +00001162};
1163
drhda0e7682008-07-30 15:27:54 +00001164/*
drh8af6c222010-05-14 12:43:01 +00001165** A lists of all unixInodeInfo objects.
drh24efa542018-10-02 19:36:40 +00001166**
1167** Must hold unixBigLock in order to read or write this variable.
drhbbd42a62004-05-22 17:41:58 +00001168*/
drhc68886b2017-08-18 16:09:52 +00001169static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001170
1171#ifdef SQLITE_DEBUG
1172/*
drh24efa542018-10-02 19:36:40 +00001173** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1174** This routine is used only within assert() to help verify correct mutex
1175** usage.
drh095908e2018-08-13 20:46:18 +00001176*/
1177int unixFileMutexHeld(unixFile *pFile){
1178 assert( pFile->pInode );
1179 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1180}
1181int unixFileMutexNotheld(unixFile *pFile){
1182 assert( pFile->pInode );
1183 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1184}
1185#endif
drh5fdae772004-06-29 03:29:00 +00001186
drh5fdae772004-06-29 03:29:00 +00001187/*
dane18d4952011-02-21 11:46:24 +00001188**
drhaaeaa182015-11-24 15:12:47 +00001189** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001190** unixLogError().
1191**
1192** It is invoked after an error occurs in an OS function and errno has been
1193** set. It logs a message using sqlite3_log() containing the current value of
1194** errno and, if possible, the human-readable equivalent from strerror() or
1195** strerror_r().
1196**
1197** The first argument passed to the macro should be the error code that
1198** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1199** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001200** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001201** if any.
1202*/
drh0e9365c2011-03-02 02:08:13 +00001203#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1204static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001205 int errcode, /* SQLite error code */
1206 const char *zFunc, /* Name of OS function that failed */
1207 const char *zPath, /* File path associated with error */
1208 int iLine /* Source line number where error occurred */
1209){
1210 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001211 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001212
1213 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1214 ** the strerror() function to obtain the human-readable error message
1215 ** equivalent to errno. Otherwise, use strerror_r().
1216 */
1217#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1218 char aErr[80];
1219 memset(aErr, 0, sizeof(aErr));
1220 zErr = aErr;
1221
1222 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001223 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001224 ** returns a pointer to a buffer containing the error message. That pointer
1225 ** may point to aErr[], or it may point to some static storage somewhere.
1226 ** Otherwise, assume that the system provides the POSIX version of
1227 ** strerror_r(), which always writes an error message into aErr[].
1228 **
1229 ** If the code incorrectly assumes that it is the POSIX version that is
1230 ** available, the error message will often be an empty string. Not a
1231 ** huge problem. Incorrectly concluding that the GNU version is available
1232 ** could lead to a segfault though.
1233 */
1234#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1235 zErr =
1236# endif
drh0e9365c2011-03-02 02:08:13 +00001237 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001238
1239#elif SQLITE_THREADSAFE
1240 /* This is a threadsafe build, but strerror_r() is not available. */
1241 zErr = "";
1242#else
1243 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001244 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001245#endif
1246
drh0e9365c2011-03-02 02:08:13 +00001247 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001248 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001249 "os_unix.c:%d: (%d) %s(%s) - %s",
1250 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001251 );
1252
1253 return errcode;
1254}
1255
drh0e9365c2011-03-02 02:08:13 +00001256/*
1257** Close a file descriptor.
1258**
1259** We assume that close() almost always works, since it is only in a
1260** very sick application or on a very sick platform that it might fail.
1261** If it does fail, simply leak the file descriptor, but do log the
1262** error.
1263**
1264** Note that it is not safe to retry close() after EINTR since the
1265** file descriptor might have already been reused by another thread.
1266** So we don't even try to recover from an EINTR. Just log the error
1267** and move on.
1268*/
1269static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001270 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001271 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1272 pFile ? pFile->zPath : 0, lineno);
1273 }
1274}
dane18d4952011-02-21 11:46:24 +00001275
1276/*
drhe6d41732015-02-21 00:49:00 +00001277** Set the pFile->lastErrno. Do this in a subroutine as that provides
1278** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001279*/
1280static void storeLastErrno(unixFile *pFile, int error){
1281 pFile->lastErrno = error;
1282}
1283
1284/*
danb0ac3e32010-06-16 10:55:42 +00001285** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001286*/
drh0e9365c2011-03-02 02:08:13 +00001287static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001288 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001289 UnixUnusedFd *p;
1290 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001291 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001292 for(p=pInode->pUnused; p; p=pNext){
1293 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001294 robust_close(pFile, p->fd, __LINE__);
1295 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001296 }
drh0e9365c2011-03-02 02:08:13 +00001297 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001298}
1299
1300/*
drh8af6c222010-05-14 12:43:01 +00001301** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001302**
drh24efa542018-10-02 19:36:40 +00001303** The global mutex must be held when this routine is called, but the mutex
1304** on the inode being deleted must NOT be held.
drh6c7d5c52008-11-21 20:32:33 +00001305*/
danb0ac3e32010-06-16 10:55:42 +00001306static void releaseInodeInfo(unixFile *pFile){
1307 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001308 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001309 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001310 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001311 pInode->nRef--;
1312 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001313 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001314 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001315 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001316 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001317 if( pInode->pPrev ){
1318 assert( pInode->pPrev->pNext==pInode );
1319 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001320 }else{
drh8af6c222010-05-14 12:43:01 +00001321 assert( inodeList==pInode );
1322 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001323 }
drh8af6c222010-05-14 12:43:01 +00001324 if( pInode->pNext ){
1325 assert( pInode->pNext->pPrev==pInode );
1326 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001327 }
drhda6dc242018-07-23 21:10:37 +00001328 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001329 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001330 }
drhbbd42a62004-05-22 17:41:58 +00001331 }
1332}
1333
1334/*
drh8af6c222010-05-14 12:43:01 +00001335** Given a file descriptor, locate the unixInodeInfo object that
1336** describes that file descriptor. Create a new one if necessary. The
1337** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001338**
drh24efa542018-10-02 19:36:40 +00001339** The global mutex must held when calling this routine.
dan9359c7b2009-08-21 08:29:10 +00001340**
drh6c7d5c52008-11-21 20:32:33 +00001341** Return an appropriate error code.
1342*/
drh8af6c222010-05-14 12:43:01 +00001343static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001344 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001345 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001346){
1347 int rc; /* System call return code */
1348 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001349 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1350 struct stat statbuf; /* Low-level file information */
1351 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001352
dan9359c7b2009-08-21 08:29:10 +00001353 assert( unixMutexHeld() );
1354
drh6c7d5c52008-11-21 20:32:33 +00001355 /* Get low-level information about the file that we can used to
1356 ** create a unique name for the file.
1357 */
1358 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001359 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001360 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001361 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001362#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001363 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1364#endif
1365 return SQLITE_IOERR;
1366 }
1367
drheb0d74f2009-02-03 15:27:02 +00001368#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001369 /* On OS X on an msdos filesystem, the inode number is reported
1370 ** incorrectly for zero-size files. See ticket #3260. To work
1371 ** around this problem (we consider it a bug in OS X, not SQLite)
1372 ** we always increase the file size to 1 by writing a single byte
1373 ** prior to accessing the inode number. The one byte written is
1374 ** an ASCII 'S' character which also happens to be the first byte
1375 ** in the header of every SQLite database. In this way, if there
1376 ** is a race condition such that another thread has already populated
1377 ** the first page of the database, no damage is done.
1378 */
drh7ed97b92010-01-20 13:07:21 +00001379 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001380 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001381 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001382 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001383 return SQLITE_IOERR;
1384 }
drh99ab3b12011-03-02 15:09:07 +00001385 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001386 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001387 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001388 return SQLITE_IOERR;
1389 }
1390 }
drheb0d74f2009-02-03 15:27:02 +00001391#endif
drh6c7d5c52008-11-21 20:32:33 +00001392
drh8af6c222010-05-14 12:43:01 +00001393 memset(&fileId, 0, sizeof(fileId));
1394 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001395#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001396 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001397#else
drh25ef7f52016-12-05 20:06:45 +00001398 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001399#endif
drh24efa542018-10-02 19:36:40 +00001400 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001401 pInode = inodeList;
1402 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1403 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001404 }
drh8af6c222010-05-14 12:43:01 +00001405 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001406 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001407 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001408 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001409 }
drh8af6c222010-05-14 12:43:01 +00001410 memset(pInode, 0, sizeof(*pInode));
1411 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001412 if( sqlite3GlobalConfig.bCoreMutex ){
1413 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1414 if( pInode->pLockMutex==0 ){
1415 sqlite3_free(pInode);
1416 return SQLITE_NOMEM_BKPT;
1417 }
1418 }
drh8af6c222010-05-14 12:43:01 +00001419 pInode->nRef = 1;
drh24efa542018-10-02 19:36:40 +00001420 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001421 pInode->pNext = inodeList;
1422 pInode->pPrev = 0;
1423 if( inodeList ) inodeList->pPrev = pInode;
1424 inodeList = pInode;
1425 }else{
1426 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001427 }
drh8af6c222010-05-14 12:43:01 +00001428 *ppInode = pInode;
1429 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001430}
drh6c7d5c52008-11-21 20:32:33 +00001431
drhb959a012013-12-07 12:29:22 +00001432/*
1433** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1434*/
1435static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001436#if OS_VXWORKS
1437 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1438#else
drhb959a012013-12-07 12:29:22 +00001439 struct stat buf;
1440 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001441 (osStat(pFile->zPath, &buf)!=0
1442 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001443#endif
drhb959a012013-12-07 12:29:22 +00001444}
1445
aswift5b1a2562008-08-22 00:22:35 +00001446
1447/*
drhfbc7e882013-04-11 01:16:15 +00001448** Check a unixFile that is a database. Verify the following:
1449**
1450** (1) There is exactly one hard link on the file
1451** (2) The file is not a symbolic link
1452** (3) The file has not been renamed or unlinked
1453**
1454** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1455*/
1456static void verifyDbFile(unixFile *pFile){
1457 struct stat buf;
1458 int rc;
drh86151e82015-12-08 14:37:16 +00001459
1460 /* These verifications occurs for the main database only */
1461 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1462
drhfbc7e882013-04-11 01:16:15 +00001463 rc = osFstat(pFile->h, &buf);
1464 if( rc!=0 ){
1465 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001466 return;
1467 }
drh6369bc32016-03-21 16:06:42 +00001468 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001469 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001470 return;
1471 }
1472 if( buf.st_nlink>1 ){
1473 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001474 return;
1475 }
drhb959a012013-12-07 12:29:22 +00001476 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001477 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001478 return;
1479 }
1480}
1481
1482
1483/*
danielk197713adf8a2004-06-03 16:08:41 +00001484** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001485** file by this or any other process. If such a lock is held, set *pResOut
1486** to a non-zero value otherwise *pResOut is set to zero. The return value
1487** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001488*/
danielk1977861f7452008-06-05 11:39:11 +00001489static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001490 int rc = SQLITE_OK;
1491 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001492 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001493
danielk1977861f7452008-06-05 11:39:11 +00001494 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1495
drh054889e2005-11-30 03:20:31 +00001496 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001497 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001498 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001499
1500 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001501 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001502 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001503 }
1504
drh2ac3ee92004-06-07 16:27:46 +00001505 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001506 */
danielk197709480a92009-02-09 05:32:32 +00001507#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001508 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001509 struct flock lock;
1510 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001511 lock.l_start = RESERVED_BYTE;
1512 lock.l_len = 1;
1513 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001514 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1515 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001516 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001517 } else if( lock.l_type!=F_UNLCK ){
1518 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001519 }
1520 }
danielk197709480a92009-02-09 05:32:32 +00001521#endif
danielk197713adf8a2004-06-03 16:08:41 +00001522
drhda6dc242018-07-23 21:10:37 +00001523 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001524 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001525
aswift5b1a2562008-08-22 00:22:35 +00001526 *pResOut = reserved;
1527 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001528}
1529
1530/*
drhf0119b22018-03-26 17:40:53 +00001531** Set a posix-advisory-lock.
1532**
1533** There are two versions of this routine. If compiled with
1534** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1535** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1536** value is set, then it is the number of milliseconds to wait before
1537** failing the lock. The iBusyTimeout value is always reset back to
1538** zero on each call.
1539**
1540** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1541** attempt to set the lock.
1542*/
1543#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1544# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1545#else
1546static int osSetPosixAdvisoryLock(
1547 int h, /* The file descriptor on which to take the lock */
1548 struct flock *pLock, /* The description of the lock */
1549 unixFile *pFile /* Structure holding timeout value */
1550){
1551 int rc = osFcntl(h,F_SETLK,pLock);
drhfd725632018-03-26 20:43:05 +00001552 while( rc<0 && pFile->iBusyTimeout>0 ){
drhf0119b22018-03-26 17:40:53 +00001553 /* On systems that support some kind of blocking file lock with a timeout,
1554 ** make appropriate changes here to invoke that blocking file lock. On
1555 ** generic posix, however, there is no such API. So we simply try the
1556 ** lock once every millisecond until either the timeout expires, or until
1557 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001558 usleep(1000);
1559 rc = osFcntl(h,F_SETLK,pLock);
1560 pFile->iBusyTimeout--;
drhf0119b22018-03-26 17:40:53 +00001561 }
1562 return rc;
1563}
1564#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1565
1566
1567/*
drha7e61d82011-03-12 17:02:57 +00001568** Attempt to set a system-lock on the file pFile. The lock is
1569** described by pLock.
1570**
drh77197112011-03-15 19:08:48 +00001571** If the pFile was opened read/write from unix-excl, then the only lock
1572** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001573** the first time any lock is attempted. All subsequent system locking
1574** operations become no-ops. Locking operations still happen internally,
1575** in order to coordinate access between separate database connections
1576** within this process, but all of that is handled in memory and the
1577** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001578**
1579** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1580** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1581** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001582**
1583** Zero is returned if the call completes successfully, or -1 if a call
1584** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001585*/
1586static int unixFileLock(unixFile *pFile, struct flock *pLock){
1587 int rc;
drh3cb93392011-03-12 18:10:44 +00001588 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001589 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001590 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001591 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001592 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001593 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001594 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001595 lock.l_whence = SEEK_SET;
1596 lock.l_start = SHARED_FIRST;
1597 lock.l_len = SHARED_SIZE;
1598 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001599 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001600 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001601 pInode->bProcessLock = 1;
1602 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001603 }else{
1604 rc = 0;
1605 }
1606 }else{
drhf0119b22018-03-26 17:40:53 +00001607 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001608 }
1609 return rc;
1610}
1611
1612/*
drh308c2a52010-05-14 11:30:18 +00001613** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001614** of the following:
1615**
drh2ac3ee92004-06-07 16:27:46 +00001616** (1) SHARED_LOCK
1617** (2) RESERVED_LOCK
1618** (3) PENDING_LOCK
1619** (4) EXCLUSIVE_LOCK
1620**
drhb3e04342004-06-08 00:47:47 +00001621** Sometimes when requesting one lock state, additional lock states
1622** are inserted in between. The locking might fail on one of the later
1623** transitions leaving the lock state different from what it started but
1624** still short of its goal. The following chart shows the allowed
1625** transitions and the inserted intermediate states:
1626**
1627** UNLOCKED -> SHARED
1628** SHARED -> RESERVED
1629** SHARED -> (PENDING) -> EXCLUSIVE
1630** RESERVED -> (PENDING) -> EXCLUSIVE
1631** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001632**
drha6abd042004-06-09 17:37:22 +00001633** This routine will only increase a lock. Use the sqlite3OsUnlock()
1634** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001635*/
drh308c2a52010-05-14 11:30:18 +00001636static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001637 /* The following describes the implementation of the various locks and
1638 ** lock transitions in terms of the POSIX advisory shared and exclusive
1639 ** lock primitives (called read-locks and write-locks below, to avoid
1640 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001641 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001642 ** accessing the same database file, in case that is ever required.
1643 **
1644 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1645 ** byte', each single bytes at well known offsets, and the 'shared byte
1646 ** range', a range of 510 bytes at a well known offset.
1647 **
1648 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001649 ** byte'. If this is successful, 'shared byte range' is read-locked
1650 ** and the lock on the 'pending byte' released. (Legacy note: When
1651 ** SQLite was first developed, Windows95 systems were still very common,
1652 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1653 ** single randomly selected by from the 'shared byte range' is locked.
1654 ** Windows95 is now pretty much extinct, but this work-around for the
1655 ** lack of shared-locks on Windows95 lives on, for backwards
1656 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001657 **
danielk197790ba3bd2004-06-25 08:32:25 +00001658 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1659 ** A RESERVED lock is implemented by grabbing a write-lock on the
1660 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001661 **
1662 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001663 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1664 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1665 ** obtained, but existing SHARED locks are allowed to persist. A process
1666 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1667 ** This property is used by the algorithm for rolling back a journal file
1668 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001669 **
danielk197790ba3bd2004-06-25 08:32:25 +00001670 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1671 ** implemented by obtaining a write-lock on the entire 'shared byte
1672 ** range'. Since all other locks require a read-lock on one of the bytes
1673 ** within this range, this ensures that no other locks are held on the
1674 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001675 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001676 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001677 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001678 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001679 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001680 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001681
drh054889e2005-11-30 03:20:31 +00001682 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001683 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1684 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001685 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001686 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001687
1688 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001689 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001690 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001691 */
drh308c2a52010-05-14 11:30:18 +00001692 if( pFile->eFileLock>=eFileLock ){
1693 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1694 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001695 return SQLITE_OK;
1696 }
1697
drh0c2694b2009-09-03 16:23:44 +00001698 /* Make sure the locking sequence is correct.
1699 ** (1) We never move from unlocked to anything higher than shared lock.
1700 ** (2) SQLite never explicitly requests a pendig lock.
1701 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001702 */
drh308c2a52010-05-14 11:30:18 +00001703 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1704 assert( eFileLock!=PENDING_LOCK );
1705 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001706
drh8af6c222010-05-14 12:43:01 +00001707 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001708 */
drh8af6c222010-05-14 12:43:01 +00001709 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001710 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001711
danielk1977ad94b582007-08-20 06:44:22 +00001712 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001713 ** handle that precludes the requested lock, return BUSY.
1714 */
drh8af6c222010-05-14 12:43:01 +00001715 if( (pFile->eFileLock!=pInode->eFileLock &&
1716 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001717 ){
1718 rc = SQLITE_BUSY;
1719 goto end_lock;
1720 }
1721
1722 /* If a SHARED lock is requested, and some thread using this PID already
1723 ** has a SHARED or RESERVED lock, then increment reference counts and
1724 ** return SQLITE_OK.
1725 */
drh308c2a52010-05-14 11:30:18 +00001726 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001727 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001728 assert( eFileLock==SHARED_LOCK );
1729 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001730 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001731 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001732 pInode->nShared++;
1733 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001734 goto end_lock;
1735 }
1736
danielk19779a1d0ab2004-06-01 14:09:28 +00001737
drh3cde3bb2004-06-12 02:17:14 +00001738 /* A PENDING lock is needed before acquiring a SHARED lock and before
1739 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1740 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001741 */
drh0c2694b2009-09-03 16:23:44 +00001742 lock.l_len = 1L;
1743 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001744 if( eFileLock==SHARED_LOCK
1745 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001746 ){
drh308c2a52010-05-14 11:30:18 +00001747 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001748 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001749 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001750 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001751 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001752 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001753 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001754 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001755 goto end_lock;
1756 }
drh3cde3bb2004-06-12 02:17:14 +00001757 }
1758
1759
1760 /* If control gets to this point, then actually go ahead and make
1761 ** operating system calls for the specified lock.
1762 */
drh308c2a52010-05-14 11:30:18 +00001763 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001764 assert( pInode->nShared==0 );
1765 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001766 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001767
drh2ac3ee92004-06-07 16:27:46 +00001768 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001769 lock.l_start = SHARED_FIRST;
1770 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001771 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001772 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001773 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001774 }
dan661d71a2011-03-30 19:08:03 +00001775
drh2ac3ee92004-06-07 16:27:46 +00001776 /* Drop the temporary PENDING lock */
1777 lock.l_start = PENDING_BYTE;
1778 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001779 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001780 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1781 /* This could happen with a network mount */
1782 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001783 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001784 }
dan661d71a2011-03-30 19:08:03 +00001785
1786 if( rc ){
1787 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001788 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001789 }
dan661d71a2011-03-30 19:08:03 +00001790 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001791 }else{
drh308c2a52010-05-14 11:30:18 +00001792 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001793 pInode->nLock++;
1794 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001795 }
drh8af6c222010-05-14 12:43:01 +00001796 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001797 /* We are trying for an exclusive lock but another thread in this
1798 ** same process is still holding a shared lock. */
1799 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001800 }else{
drh3cde3bb2004-06-12 02:17:14 +00001801 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001802 ** assumed that there is a SHARED or greater lock on the file
1803 ** already.
1804 */
drh308c2a52010-05-14 11:30:18 +00001805 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001806 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001807
1808 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1809 if( eFileLock==RESERVED_LOCK ){
1810 lock.l_start = RESERVED_BYTE;
1811 lock.l_len = 1L;
1812 }else{
1813 lock.l_start = SHARED_FIRST;
1814 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001815 }
dan661d71a2011-03-30 19:08:03 +00001816
1817 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001818 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001819 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001820 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001821 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001822 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001823 }
drhbbd42a62004-05-22 17:41:58 +00001824 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001825
drh8f941bc2009-01-14 23:03:40 +00001826
drhd3d8c042012-05-29 17:02:40 +00001827#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001828 /* Set up the transaction-counter change checking flags when
1829 ** transitioning from a SHARED to a RESERVED lock. The change
1830 ** from SHARED to RESERVED marks the beginning of a normal
1831 ** write operation (not a hot journal rollback).
1832 */
1833 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001834 && pFile->eFileLock<=SHARED_LOCK
1835 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001836 ){
1837 pFile->transCntrChng = 0;
1838 pFile->dbUpdate = 0;
1839 pFile->inNormalWrite = 1;
1840 }
1841#endif
1842
1843
danielk1977ecb2a962004-06-02 06:30:16 +00001844 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001845 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001846 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001847 }else if( eFileLock==EXCLUSIVE_LOCK ){
1848 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001849 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001850 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001851
1852end_lock:
drhda6dc242018-07-23 21:10:37 +00001853 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001854 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1855 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001856 return rc;
1857}
1858
1859/*
dan08da86a2009-08-21 17:18:03 +00001860** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001861** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001862*/
1863static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001864 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001865 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001866 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001867 p->pNext = pInode->pUnused;
1868 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001869 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001870 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001871}
1872
1873/*
drh308c2a52010-05-14 11:30:18 +00001874** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001875** must be either NO_LOCK or SHARED_LOCK.
1876**
1877** If the locking level of the file descriptor is already at or below
1878** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001879**
1880** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1881** the byte range is divided into 2 parts and the first part is unlocked then
1882** set to a read lock, then the other part is simply unlocked. This works
1883** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1884** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001885*/
drha7e61d82011-03-12 17:02:57 +00001886static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001887 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001888 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001889 struct flock lock;
1890 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001891
drh054889e2005-11-30 03:20:31 +00001892 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001893 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001894 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001895 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001896
drh308c2a52010-05-14 11:30:18 +00001897 assert( eFileLock<=SHARED_LOCK );
1898 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001899 return SQLITE_OK;
1900 }
drh8af6c222010-05-14 12:43:01 +00001901 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001902 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001903 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001904 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001905 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001906
drhd3d8c042012-05-29 17:02:40 +00001907#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001908 /* When reducing a lock such that other processes can start
1909 ** reading the database file again, make sure that the
1910 ** transaction counter was updated if any part of the database
1911 ** file changed. If the transaction counter is not updated,
1912 ** other connections to the same file might not realize that
1913 ** the file has changed and hence might not know to flush their
1914 ** cache. The use of a stale cache can lead to database corruption.
1915 */
drh8f941bc2009-01-14 23:03:40 +00001916 pFile->inNormalWrite = 0;
1917#endif
1918
drh7ed97b92010-01-20 13:07:21 +00001919 /* downgrading to a shared lock on NFS involves clearing the write lock
1920 ** before establishing the readlock - to avoid a race condition we downgrade
1921 ** the lock in 2 blocks, so that part of the range will be covered by a
1922 ** write lock until the rest is covered by a read lock:
1923 ** 1: [WWWWW]
1924 ** 2: [....W]
1925 ** 3: [RRRRW]
1926 ** 4: [RRRR.]
1927 */
drh308c2a52010-05-14 11:30:18 +00001928 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001929#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001930 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001931 assert( handleNFSUnlock==0 );
1932#endif
1933#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001934 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001935 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001936 off_t divSize = SHARED_SIZE - 1;
1937
1938 lock.l_type = F_UNLCK;
1939 lock.l_whence = SEEK_SET;
1940 lock.l_start = SHARED_FIRST;
1941 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001942 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001943 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001944 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001945 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001946 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001947 }
drh7ed97b92010-01-20 13:07:21 +00001948 lock.l_type = F_RDLCK;
1949 lock.l_whence = SEEK_SET;
1950 lock.l_start = SHARED_FIRST;
1951 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001952 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001953 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001954 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1955 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001956 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001957 }
1958 goto end_unlock;
1959 }
1960 lock.l_type = F_UNLCK;
1961 lock.l_whence = SEEK_SET;
1962 lock.l_start = SHARED_FIRST+divSize;
1963 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001964 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001965 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001966 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001967 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001968 goto end_unlock;
1969 }
drh30f776f2011-02-25 03:25:07 +00001970 }else
1971#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1972 {
drh7ed97b92010-01-20 13:07:21 +00001973 lock.l_type = F_RDLCK;
1974 lock.l_whence = SEEK_SET;
1975 lock.l_start = SHARED_FIRST;
1976 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001977 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001978 /* In theory, the call to unixFileLock() cannot fail because another
1979 ** process is holding an incompatible lock. If it does, this
1980 ** indicates that the other process is not following the locking
1981 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1982 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
1983 ** an assert to fail). */
1984 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001985 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00001986 goto end_unlock;
1987 }
drh9c105bb2004-10-02 20:38:28 +00001988 }
1989 }
drhbbd42a62004-05-22 17:41:58 +00001990 lock.l_type = F_UNLCK;
1991 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00001992 lock.l_start = PENDING_BYTE;
1993 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00001994 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00001995 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00001996 }else{
danea83bc62011-04-01 11:56:32 +00001997 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001998 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00001999 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00002000 }
drhbbd42a62004-05-22 17:41:58 +00002001 }
drh308c2a52010-05-14 11:30:18 +00002002 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002003 /* Decrement the shared lock counter. Release the lock using an
2004 ** OS call only when all threads in this same process have released
2005 ** the lock.
2006 */
drh8af6c222010-05-14 12:43:01 +00002007 pInode->nShared--;
2008 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002009 lock.l_type = F_UNLCK;
2010 lock.l_whence = SEEK_SET;
2011 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002012 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002013 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002014 }else{
danea83bc62011-04-01 11:56:32 +00002015 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002016 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002017 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002018 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002019 }
drha6abd042004-06-09 17:37:22 +00002020 }
2021
drhbbd42a62004-05-22 17:41:58 +00002022 /* Decrement the count of locks against this same file. When the
2023 ** count reaches zero, close any other file descriptors whose close
2024 ** was deferred because of outstanding locks.
2025 */
drh8af6c222010-05-14 12:43:01 +00002026 pInode->nLock--;
2027 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002028 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002029 }
drhf2f105d2012-08-20 15:53:54 +00002030
aswift5b1a2562008-08-22 00:22:35 +00002031end_unlock:
drhda6dc242018-07-23 21:10:37 +00002032 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002033 if( rc==SQLITE_OK ){
2034 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002035 }
drh9c105bb2004-10-02 20:38:28 +00002036 return rc;
drhbbd42a62004-05-22 17:41:58 +00002037}
2038
2039/*
drh308c2a52010-05-14 11:30:18 +00002040** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002041** must be either NO_LOCK or SHARED_LOCK.
2042**
2043** If the locking level of the file descriptor is already at or below
2044** the requested locking level, this routine is a no-op.
2045*/
drh308c2a52010-05-14 11:30:18 +00002046static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002047#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002048 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002049#endif
drha7e61d82011-03-12 17:02:57 +00002050 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002051}
2052
mistachkine98844f2013-08-24 00:59:24 +00002053#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002054static int unixMapfile(unixFile *pFd, i64 nByte);
2055static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002056#endif
danf23da962013-03-23 21:00:41 +00002057
drh7ed97b92010-01-20 13:07:21 +00002058/*
danielk1977e339d652008-06-28 11:23:00 +00002059** This function performs the parts of the "close file" operation
2060** common to all locking schemes. It closes the directory and file
2061** handles, if they are valid, and sets all fields of the unixFile
2062** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002063**
2064** It is *not* necessary to hold the mutex when this routine is called,
2065** even on VxWorks. A mutex will be acquired on VxWorks by the
2066** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002067*/
2068static int closeUnixFile(sqlite3_file *id){
2069 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002070#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002071 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002072#endif
dan661d71a2011-03-30 19:08:03 +00002073 if( pFile->h>=0 ){
2074 robust_close(pFile, pFile->h, __LINE__);
2075 pFile->h = -1;
2076 }
2077#if OS_VXWORKS
2078 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002079 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002080 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002081 }
2082 vxworksReleaseFileId(pFile->pId);
2083 pFile->pId = 0;
2084 }
2085#endif
drh0bdbc902014-06-16 18:35:06 +00002086#ifdef SQLITE_UNLINK_AFTER_CLOSE
2087 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2088 osUnlink(pFile->zPath);
2089 sqlite3_free(*(char**)&pFile->zPath);
2090 pFile->zPath = 0;
2091 }
2092#endif
dan661d71a2011-03-30 19:08:03 +00002093 OSTRACE(("CLOSE %-3d\n", pFile->h));
2094 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002095 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002096 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002097 return SQLITE_OK;
2098}
2099
2100/*
danielk1977e3026632004-06-22 11:29:02 +00002101** Close a file.
2102*/
danielk197762079062007-08-15 17:08:46 +00002103static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002104 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002105 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002106 unixInodeInfo *pInode = pFile->pInode;
2107
2108 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002109 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002110 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002111 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002112 unixEnterMutex();
2113
2114 /* unixFile.pInode is always valid here. Otherwise, a different close
2115 ** routine (e.g. nolockClose()) would be called instead.
2116 */
2117 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002118 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002119 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002120 /* If there are outstanding locks, do not actually close the file just
2121 ** yet because that would clear those locks. Instead, add the file
2122 ** descriptor to pInode->pUnused list. It will be automatically closed
2123 ** when the last lock is cleared.
2124 */
2125 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002126 }
drhef52b362018-08-13 22:50:34 +00002127 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002128 releaseInodeInfo(pFile);
2129 rc = closeUnixFile(id);
2130 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002131 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002132}
2133
drh734c9862008-11-28 15:37:20 +00002134/************** End of the posix advisory lock implementation *****************
2135******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002136
drh734c9862008-11-28 15:37:20 +00002137/******************************************************************************
2138****************************** No-op Locking **********************************
2139**
2140** Of the various locking implementations available, this is by far the
2141** simplest: locking is ignored. No attempt is made to lock the database
2142** file for reading or writing.
2143**
2144** This locking mode is appropriate for use on read-only databases
2145** (ex: databases that are burned into CD-ROM, for example.) It can
2146** also be used if the application employs some external mechanism to
2147** prevent simultaneous access of the same database by two or more
2148** database connections. But there is a serious risk of database
2149** corruption if this locking mode is used in situations where multiple
2150** database connections are accessing the same database file at the same
2151** time and one or more of those connections are writing.
2152*/
drhbfe66312006-10-03 17:40:40 +00002153
drh734c9862008-11-28 15:37:20 +00002154static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2155 UNUSED_PARAMETER(NotUsed);
2156 *pResOut = 0;
2157 return SQLITE_OK;
2158}
drh734c9862008-11-28 15:37:20 +00002159static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2160 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2161 return SQLITE_OK;
2162}
drh734c9862008-11-28 15:37:20 +00002163static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2164 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2165 return SQLITE_OK;
2166}
2167
2168/*
drh9b35ea62008-11-29 02:20:26 +00002169** Close the file.
drh734c9862008-11-28 15:37:20 +00002170*/
2171static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002172 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002173}
2174
2175/******************* End of the no-op lock implementation *********************
2176******************************************************************************/
2177
2178/******************************************************************************
2179************************* Begin dot-file Locking ******************************
2180**
mistachkin48864df2013-03-21 21:20:32 +00002181** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002182** files (really a directory) to control access to the database. This works
2183** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002184**
2185** (1) There is zero concurrency. A single reader blocks all other
2186** connections from reading or writing the database.
2187**
2188** (2) An application crash or power loss can leave stale lock files
2189** sitting around that need to be cleared manually.
2190**
2191** Nevertheless, a dotlock is an appropriate locking mode for use if no
2192** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002193**
drh9ef6bc42011-11-04 02:24:02 +00002194** Dotfile locking works by creating a subdirectory in the same directory as
2195** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002196** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002197** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002198*/
2199
2200/*
2201** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002202** lock directory.
drh734c9862008-11-28 15:37:20 +00002203*/
2204#define DOTLOCK_SUFFIX ".lock"
2205
drh7708e972008-11-29 00:56:52 +00002206/*
2207** This routine checks if there is a RESERVED lock held on the specified
2208** file by this or any other process. If such a lock is held, set *pResOut
2209** to a non-zero value otherwise *pResOut is set to zero. The return value
2210** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2211**
2212** In dotfile locking, either a lock exists or it does not. So in this
2213** variation of CheckReservedLock(), *pResOut is set to true if any lock
2214** is held on the file and false if the file is unlocked.
2215*/
drh734c9862008-11-28 15:37:20 +00002216static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2217 int rc = SQLITE_OK;
2218 int reserved = 0;
2219 unixFile *pFile = (unixFile*)id;
2220
2221 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2222
2223 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002224 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002225 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002226 *pResOut = reserved;
2227 return rc;
2228}
2229
drh7708e972008-11-29 00:56:52 +00002230/*
drh308c2a52010-05-14 11:30:18 +00002231** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002232** of the following:
2233**
2234** (1) SHARED_LOCK
2235** (2) RESERVED_LOCK
2236** (3) PENDING_LOCK
2237** (4) EXCLUSIVE_LOCK
2238**
2239** Sometimes when requesting one lock state, additional lock states
2240** are inserted in between. The locking might fail on one of the later
2241** transitions leaving the lock state different from what it started but
2242** still short of its goal. The following chart shows the allowed
2243** transitions and the inserted intermediate states:
2244**
2245** UNLOCKED -> SHARED
2246** SHARED -> RESERVED
2247** SHARED -> (PENDING) -> EXCLUSIVE
2248** RESERVED -> (PENDING) -> EXCLUSIVE
2249** PENDING -> EXCLUSIVE
2250**
2251** This routine will only increase a lock. Use the sqlite3OsUnlock()
2252** routine to lower a locking level.
2253**
2254** With dotfile locking, we really only support state (4): EXCLUSIVE.
2255** But we track the other locking levels internally.
2256*/
drh308c2a52010-05-14 11:30:18 +00002257static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002258 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002259 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002260 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002261
drh7708e972008-11-29 00:56:52 +00002262
2263 /* If we have any lock, then the lock file already exists. All we have
2264 ** to do is adjust our internal record of the lock level.
2265 */
drh308c2a52010-05-14 11:30:18 +00002266 if( pFile->eFileLock > NO_LOCK ){
2267 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002268 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002269#ifdef HAVE_UTIME
2270 utime(zLockFile, NULL);
2271#else
drh734c9862008-11-28 15:37:20 +00002272 utimes(zLockFile, NULL);
2273#endif
drh7708e972008-11-29 00:56:52 +00002274 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002275 }
2276
2277 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002278 rc = osMkdir(zLockFile, 0777);
2279 if( rc<0 ){
2280 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002281 int tErrno = errno;
2282 if( EEXIST == tErrno ){
2283 rc = SQLITE_BUSY;
2284 } else {
2285 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002286 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002287 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002288 }
2289 }
drh7708e972008-11-29 00:56:52 +00002290 return rc;
drh734c9862008-11-28 15:37:20 +00002291 }
drh734c9862008-11-28 15:37:20 +00002292
2293 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002294 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002295 return rc;
2296}
2297
drh7708e972008-11-29 00:56:52 +00002298/*
drh308c2a52010-05-14 11:30:18 +00002299** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002300** must be either NO_LOCK or SHARED_LOCK.
2301**
2302** If the locking level of the file descriptor is already at or below
2303** the requested locking level, this routine is a no-op.
2304**
2305** When the locking level reaches NO_LOCK, delete the lock file.
2306*/
drh308c2a52010-05-14 11:30:18 +00002307static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002308 unixFile *pFile = (unixFile*)id;
2309 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002310 int rc;
drh734c9862008-11-28 15:37:20 +00002311
2312 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002313 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002314 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002315 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002316
2317 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002318 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002319 return SQLITE_OK;
2320 }
drh7708e972008-11-29 00:56:52 +00002321
2322 /* To downgrade to shared, simply update our internal notion of the
2323 ** lock state. No need to mess with the file on disk.
2324 */
drh308c2a52010-05-14 11:30:18 +00002325 if( eFileLock==SHARED_LOCK ){
2326 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002327 return SQLITE_OK;
2328 }
2329
drh7708e972008-11-29 00:56:52 +00002330 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002331 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002332 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002333 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002334 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002335 if( tErrno==ENOENT ){
2336 rc = SQLITE_OK;
2337 }else{
danea83bc62011-04-01 11:56:32 +00002338 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002339 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002340 }
2341 return rc;
2342 }
drh308c2a52010-05-14 11:30:18 +00002343 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002344 return SQLITE_OK;
2345}
2346
2347/*
drh9b35ea62008-11-29 02:20:26 +00002348** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002349*/
2350static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002351 unixFile *pFile = (unixFile*)id;
2352 assert( id!=0 );
2353 dotlockUnlock(id, NO_LOCK);
2354 sqlite3_free(pFile->lockingContext);
2355 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002356}
2357/****************** End of the dot-file lock implementation *******************
2358******************************************************************************/
2359
2360/******************************************************************************
2361************************** Begin flock Locking ********************************
2362**
2363** Use the flock() system call to do file locking.
2364**
drh6b9d6dd2008-12-03 19:34:47 +00002365** flock() locking is like dot-file locking in that the various
2366** fine-grain locking levels supported by SQLite are collapsed into
2367** a single exclusive lock. In other words, SHARED, RESERVED, and
2368** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2369** still works when you do this, but concurrency is reduced since
2370** only a single process can be reading the database at a time.
2371**
drhe89b2912015-03-03 20:42:01 +00002372** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002373*/
drhe89b2912015-03-03 20:42:01 +00002374#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002375
drh6b9d6dd2008-12-03 19:34:47 +00002376/*
drhff812312011-02-23 13:33:46 +00002377** Retry flock() calls that fail with EINTR
2378*/
2379#ifdef EINTR
2380static int robust_flock(int fd, int op){
2381 int rc;
2382 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2383 return rc;
2384}
2385#else
drh5c819272011-02-23 14:00:12 +00002386# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002387#endif
2388
2389
2390/*
drh6b9d6dd2008-12-03 19:34:47 +00002391** This routine checks if there is a RESERVED lock held on the specified
2392** file by this or any other process. If such a lock is held, set *pResOut
2393** to a non-zero value otherwise *pResOut is set to zero. The return value
2394** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2395*/
drh734c9862008-11-28 15:37:20 +00002396static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2397 int rc = SQLITE_OK;
2398 int reserved = 0;
2399 unixFile *pFile = (unixFile*)id;
2400
2401 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2402
2403 assert( pFile );
2404
2405 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002406 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002407 reserved = 1;
2408 }
2409
2410 /* Otherwise see if some other process holds it. */
2411 if( !reserved ){
2412 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002413 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002414 if( !lrc ){
2415 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002416 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002417 if ( lrc ) {
2418 int tErrno = errno;
2419 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002420 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002421 storeLastErrno(pFile, tErrno);
2422 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002423 }
2424 } else {
2425 int tErrno = errno;
2426 reserved = 1;
2427 /* someone else might have it reserved */
2428 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2429 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002430 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002431 rc = lrc;
2432 }
2433 }
2434 }
drh308c2a52010-05-14 11:30:18 +00002435 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002436
2437#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002438 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002439 rc = SQLITE_OK;
2440 reserved=1;
2441 }
2442#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2443 *pResOut = reserved;
2444 return rc;
2445}
2446
drh6b9d6dd2008-12-03 19:34:47 +00002447/*
drh308c2a52010-05-14 11:30:18 +00002448** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002449** of the following:
2450**
2451** (1) SHARED_LOCK
2452** (2) RESERVED_LOCK
2453** (3) PENDING_LOCK
2454** (4) EXCLUSIVE_LOCK
2455**
2456** Sometimes when requesting one lock state, additional lock states
2457** are inserted in between. The locking might fail on one of the later
2458** transitions leaving the lock state different from what it started but
2459** still short of its goal. The following chart shows the allowed
2460** transitions and the inserted intermediate states:
2461**
2462** UNLOCKED -> SHARED
2463** SHARED -> RESERVED
2464** SHARED -> (PENDING) -> EXCLUSIVE
2465** RESERVED -> (PENDING) -> EXCLUSIVE
2466** PENDING -> EXCLUSIVE
2467**
2468** flock() only really support EXCLUSIVE locks. We track intermediate
2469** lock states in the sqlite3_file structure, but all locks SHARED or
2470** above are really EXCLUSIVE locks and exclude all other processes from
2471** access the file.
2472**
2473** This routine will only increase a lock. Use the sqlite3OsUnlock()
2474** routine to lower a locking level.
2475*/
drh308c2a52010-05-14 11:30:18 +00002476static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002477 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002478 unixFile *pFile = (unixFile*)id;
2479
2480 assert( pFile );
2481
2482 /* if we already have a lock, it is exclusive.
2483 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002484 if (pFile->eFileLock > NO_LOCK) {
2485 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002486 return SQLITE_OK;
2487 }
2488
2489 /* grab an exclusive lock */
2490
drhff812312011-02-23 13:33:46 +00002491 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002492 int tErrno = errno;
2493 /* didn't get, must be busy */
2494 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2495 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002496 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002497 }
2498 } else {
2499 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002500 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002501 }
drh308c2a52010-05-14 11:30:18 +00002502 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2503 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002504#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002505 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002506 rc = SQLITE_BUSY;
2507 }
2508#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2509 return rc;
2510}
2511
drh6b9d6dd2008-12-03 19:34:47 +00002512
2513/*
drh308c2a52010-05-14 11:30:18 +00002514** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002515** must be either NO_LOCK or SHARED_LOCK.
2516**
2517** If the locking level of the file descriptor is already at or below
2518** the requested locking level, this routine is a no-op.
2519*/
drh308c2a52010-05-14 11:30:18 +00002520static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002521 unixFile *pFile = (unixFile*)id;
2522
2523 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002524 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002525 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002526 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002527
2528 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002529 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002530 return SQLITE_OK;
2531 }
2532
2533 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002534 if (eFileLock==SHARED_LOCK) {
2535 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002536 return SQLITE_OK;
2537 }
2538
2539 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002540 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002541#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002542 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002543#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002544 return SQLITE_IOERR_UNLOCK;
2545 }else{
drh308c2a52010-05-14 11:30:18 +00002546 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002547 return SQLITE_OK;
2548 }
2549}
2550
2551/*
2552** Close a file.
2553*/
2554static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002555 assert( id!=0 );
2556 flockUnlock(id, NO_LOCK);
2557 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002558}
2559
2560#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2561
2562/******************* End of the flock lock implementation *********************
2563******************************************************************************/
2564
2565/******************************************************************************
2566************************ Begin Named Semaphore Locking ************************
2567**
2568** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002569**
2570** Semaphore locking is like dot-lock and flock in that it really only
2571** supports EXCLUSIVE locking. Only a single process can read or write
2572** the database file at a time. This reduces potential concurrency, but
2573** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002574*/
2575#if OS_VXWORKS
2576
drh6b9d6dd2008-12-03 19:34:47 +00002577/*
2578** This routine checks if there is a RESERVED lock held on the specified
2579** file by this or any other process. If such a lock is held, set *pResOut
2580** to a non-zero value otherwise *pResOut is set to zero. The return value
2581** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2582*/
drh8cd5b252015-03-02 22:06:43 +00002583static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002584 int rc = SQLITE_OK;
2585 int reserved = 0;
2586 unixFile *pFile = (unixFile*)id;
2587
2588 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2589
2590 assert( pFile );
2591
2592 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002593 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002594 reserved = 1;
2595 }
2596
2597 /* Otherwise see if some other process holds it. */
2598 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002599 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002600
2601 if( sem_trywait(pSem)==-1 ){
2602 int tErrno = errno;
2603 if( EAGAIN != tErrno ){
2604 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002605 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002606 } else {
2607 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002608 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002609 }
2610 }else{
2611 /* we could have it if we want it */
2612 sem_post(pSem);
2613 }
2614 }
drh308c2a52010-05-14 11:30:18 +00002615 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002616
2617 *pResOut = reserved;
2618 return rc;
2619}
2620
drh6b9d6dd2008-12-03 19:34:47 +00002621/*
drh308c2a52010-05-14 11:30:18 +00002622** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002623** of the following:
2624**
2625** (1) SHARED_LOCK
2626** (2) RESERVED_LOCK
2627** (3) PENDING_LOCK
2628** (4) EXCLUSIVE_LOCK
2629**
2630** Sometimes when requesting one lock state, additional lock states
2631** are inserted in between. The locking might fail on one of the later
2632** transitions leaving the lock state different from what it started but
2633** still short of its goal. The following chart shows the allowed
2634** transitions and the inserted intermediate states:
2635**
2636** UNLOCKED -> SHARED
2637** SHARED -> RESERVED
2638** SHARED -> (PENDING) -> EXCLUSIVE
2639** RESERVED -> (PENDING) -> EXCLUSIVE
2640** PENDING -> EXCLUSIVE
2641**
2642** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2643** lock states in the sqlite3_file structure, but all locks SHARED or
2644** above are really EXCLUSIVE locks and exclude all other processes from
2645** access the file.
2646**
2647** This routine will only increase a lock. Use the sqlite3OsUnlock()
2648** routine to lower a locking level.
2649*/
drh8cd5b252015-03-02 22:06:43 +00002650static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002651 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002652 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002653 int rc = SQLITE_OK;
2654
2655 /* if we already have a lock, it is exclusive.
2656 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002657 if (pFile->eFileLock > NO_LOCK) {
2658 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002659 rc = SQLITE_OK;
2660 goto sem_end_lock;
2661 }
2662
2663 /* lock semaphore now but bail out when already locked. */
2664 if( sem_trywait(pSem)==-1 ){
2665 rc = SQLITE_BUSY;
2666 goto sem_end_lock;
2667 }
2668
2669 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002670 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002671
2672 sem_end_lock:
2673 return rc;
2674}
2675
drh6b9d6dd2008-12-03 19:34:47 +00002676/*
drh308c2a52010-05-14 11:30:18 +00002677** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002678** must be either NO_LOCK or SHARED_LOCK.
2679**
2680** If the locking level of the file descriptor is already at or below
2681** the requested locking level, this routine is a no-op.
2682*/
drh8cd5b252015-03-02 22:06:43 +00002683static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002684 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002685 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002686
2687 assert( pFile );
2688 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002689 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002690 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002691 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002692
2693 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002694 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002695 return SQLITE_OK;
2696 }
2697
2698 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002699 if (eFileLock==SHARED_LOCK) {
2700 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002701 return SQLITE_OK;
2702 }
2703
2704 /* no, really unlock. */
2705 if ( sem_post(pSem)==-1 ) {
2706 int rc, tErrno = errno;
2707 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2708 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002709 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002710 }
2711 return rc;
2712 }
drh308c2a52010-05-14 11:30:18 +00002713 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002714 return SQLITE_OK;
2715}
2716
2717/*
2718 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002719 */
drh8cd5b252015-03-02 22:06:43 +00002720static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002721 if( id ){
2722 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002723 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002724 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002725 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002726 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002727 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002728 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002729 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002730 }
2731 return SQLITE_OK;
2732}
2733
2734#endif /* OS_VXWORKS */
2735/*
2736** Named semaphore locking is only available on VxWorks.
2737**
2738*************** End of the named semaphore lock implementation ****************
2739******************************************************************************/
2740
2741
2742/******************************************************************************
2743*************************** Begin AFP Locking *********************************
2744**
2745** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2746** on Apple Macintosh computers - both OS9 and OSX.
2747**
2748** Third-party implementations of AFP are available. But this code here
2749** only works on OSX.
2750*/
2751
drhd2cb50b2009-01-09 21:41:17 +00002752#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002753/*
2754** The afpLockingContext structure contains all afp lock specific state
2755*/
drhbfe66312006-10-03 17:40:40 +00002756typedef struct afpLockingContext afpLockingContext;
2757struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002758 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002759 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002760};
2761
2762struct ByteRangeLockPB2
2763{
2764 unsigned long long offset; /* offset to first byte to lock */
2765 unsigned long long length; /* nbr of bytes to lock */
2766 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2767 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2768 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2769 int fd; /* file desc to assoc this lock with */
2770};
2771
drhfd131da2007-08-07 17:13:03 +00002772#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002773
drh6b9d6dd2008-12-03 19:34:47 +00002774/*
2775** This is a utility for setting or clearing a bit-range lock on an
2776** AFP filesystem.
2777**
2778** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2779*/
2780static int afpSetLock(
2781 const char *path, /* Name of the file to be locked or unlocked */
2782 unixFile *pFile, /* Open file descriptor on path */
2783 unsigned long long offset, /* First byte to be locked */
2784 unsigned long long length, /* Number of bytes to lock */
2785 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002786){
drh6b9d6dd2008-12-03 19:34:47 +00002787 struct ByteRangeLockPB2 pb;
2788 int err;
drhbfe66312006-10-03 17:40:40 +00002789
2790 pb.unLockFlag = setLockFlag ? 0 : 1;
2791 pb.startEndFlag = 0;
2792 pb.offset = offset;
2793 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002794 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002795
drh308c2a52010-05-14 11:30:18 +00002796 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002797 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002798 offset, length));
drhbfe66312006-10-03 17:40:40 +00002799 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2800 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002801 int rc;
2802 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002803 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2804 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002805#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2806 rc = SQLITE_BUSY;
2807#else
drh734c9862008-11-28 15:37:20 +00002808 rc = sqliteErrorFromPosixError(tErrno,
2809 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002810#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002811 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002812 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002813 }
2814 return rc;
drhbfe66312006-10-03 17:40:40 +00002815 } else {
aswift5b1a2562008-08-22 00:22:35 +00002816 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002817 }
2818}
2819
drh6b9d6dd2008-12-03 19:34:47 +00002820/*
2821** This routine checks if there is a RESERVED lock held on the specified
2822** file by this or any other process. If such a lock is held, set *pResOut
2823** to a non-zero value otherwise *pResOut is set to zero. The return value
2824** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2825*/
danielk1977e339d652008-06-28 11:23:00 +00002826static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002827 int rc = SQLITE_OK;
2828 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002829 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002830 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002831
aswift5b1a2562008-08-22 00:22:35 +00002832 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2833
2834 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002835 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002836 if( context->reserved ){
2837 *pResOut = 1;
2838 return SQLITE_OK;
2839 }
drhda6dc242018-07-23 21:10:37 +00002840 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002841 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002842 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002843 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002844 }
2845
2846 /* Otherwise see if some other process holds it.
2847 */
aswift5b1a2562008-08-22 00:22:35 +00002848 if( !reserved ){
2849 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002850 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002851 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002852 /* if we succeeded in taking the reserved lock, unlock it to restore
2853 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002854 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002855 } else {
2856 /* if we failed to get the lock then someone else must have it */
2857 reserved = 1;
2858 }
2859 if( IS_LOCK_ERROR(lrc) ){
2860 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002861 }
2862 }
drhbfe66312006-10-03 17:40:40 +00002863
drhda6dc242018-07-23 21:10:37 +00002864 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002865 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002866
2867 *pResOut = reserved;
2868 return rc;
drhbfe66312006-10-03 17:40:40 +00002869}
2870
drh6b9d6dd2008-12-03 19:34:47 +00002871/*
drh308c2a52010-05-14 11:30:18 +00002872** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002873** of the following:
2874**
2875** (1) SHARED_LOCK
2876** (2) RESERVED_LOCK
2877** (3) PENDING_LOCK
2878** (4) EXCLUSIVE_LOCK
2879**
2880** Sometimes when requesting one lock state, additional lock states
2881** are inserted in between. The locking might fail on one of the later
2882** transitions leaving the lock state different from what it started but
2883** still short of its goal. The following chart shows the allowed
2884** transitions and the inserted intermediate states:
2885**
2886** UNLOCKED -> SHARED
2887** SHARED -> RESERVED
2888** SHARED -> (PENDING) -> EXCLUSIVE
2889** RESERVED -> (PENDING) -> EXCLUSIVE
2890** PENDING -> EXCLUSIVE
2891**
2892** This routine will only increase a lock. Use the sqlite3OsUnlock()
2893** routine to lower a locking level.
2894*/
drh308c2a52010-05-14 11:30:18 +00002895static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002896 int rc = SQLITE_OK;
2897 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002898 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002899 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002900
2901 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002902 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2903 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002904 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002905
drhbfe66312006-10-03 17:40:40 +00002906 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002907 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002908 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002909 */
drh308c2a52010-05-14 11:30:18 +00002910 if( pFile->eFileLock>=eFileLock ){
2911 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2912 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002913 return SQLITE_OK;
2914 }
2915
2916 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002917 ** (1) We never move from unlocked to anything higher than shared lock.
2918 ** (2) SQLite never explicitly requests a pendig lock.
2919 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002920 */
drh308c2a52010-05-14 11:30:18 +00002921 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2922 assert( eFileLock!=PENDING_LOCK );
2923 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002924
drh8af6c222010-05-14 12:43:01 +00002925 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002926 */
drh8af6c222010-05-14 12:43:01 +00002927 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002928 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002929
2930 /* If some thread using this PID has a lock via a different unixFile*
2931 ** handle that precludes the requested lock, return BUSY.
2932 */
drh8af6c222010-05-14 12:43:01 +00002933 if( (pFile->eFileLock!=pInode->eFileLock &&
2934 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002935 ){
2936 rc = SQLITE_BUSY;
2937 goto afp_end_lock;
2938 }
2939
2940 /* If a SHARED lock is requested, and some thread using this PID already
2941 ** has a SHARED or RESERVED lock, then increment reference counts and
2942 ** return SQLITE_OK.
2943 */
drh308c2a52010-05-14 11:30:18 +00002944 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002945 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002946 assert( eFileLock==SHARED_LOCK );
2947 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002948 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002949 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002950 pInode->nShared++;
2951 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002952 goto afp_end_lock;
2953 }
drhbfe66312006-10-03 17:40:40 +00002954
2955 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002956 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2957 ** be released.
2958 */
drh308c2a52010-05-14 11:30:18 +00002959 if( eFileLock==SHARED_LOCK
2960 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002961 ){
2962 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002963 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002964 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002965 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002966 goto afp_end_lock;
2967 }
2968 }
2969
2970 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002971 ** operating system calls for the specified lock.
2972 */
drh308c2a52010-05-14 11:30:18 +00002973 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002974 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002975 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002976
drh8af6c222010-05-14 12:43:01 +00002977 assert( pInode->nShared==0 );
2978 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002979
2980 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002981 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002982 /* note that the quality of the randomness doesn't matter that much */
2983 lk = random();
drh8af6c222010-05-14 12:43:01 +00002984 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00002985 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00002986 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00002987 if( IS_LOCK_ERROR(lrc1) ){
2988 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00002989 }
aswift5b1a2562008-08-22 00:22:35 +00002990 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00002991 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00002992
aswift5b1a2562008-08-22 00:22:35 +00002993 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00002994 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00002995 rc = lrc1;
2996 goto afp_end_lock;
2997 } else if( IS_LOCK_ERROR(lrc2) ){
2998 rc = lrc2;
2999 goto afp_end_lock;
3000 } else if( lrc1 != SQLITE_OK ) {
3001 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003002 } else {
drh308c2a52010-05-14 11:30:18 +00003003 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003004 pInode->nLock++;
3005 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003006 }
drh8af6c222010-05-14 12:43:01 +00003007 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003008 /* We are trying for an exclusive lock but another thread in this
3009 ** same process is still holding a shared lock. */
3010 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003011 }else{
3012 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3013 ** assumed that there is a SHARED or greater lock on the file
3014 ** already.
3015 */
3016 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003017 assert( 0!=pFile->eFileLock );
3018 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003019 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003020 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003021 if( !failed ){
3022 context->reserved = 1;
3023 }
drhbfe66312006-10-03 17:40:40 +00003024 }
drh308c2a52010-05-14 11:30:18 +00003025 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003026 /* Acquire an EXCLUSIVE lock */
3027
3028 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003029 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003030 */
drh6b9d6dd2008-12-03 19:34:47 +00003031 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003032 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003033 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003034 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003035 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003036 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003037 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003038 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003039 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3040 ** a critical I/O error
3041 */
drh2e233812017-08-22 15:21:54 +00003042 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003043 SQLITE_IOERR_LOCK;
3044 goto afp_end_lock;
3045 }
3046 }else{
aswift5b1a2562008-08-22 00:22:35 +00003047 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003048 }
3049 }
aswift5b1a2562008-08-22 00:22:35 +00003050 if( failed ){
3051 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003052 }
3053 }
3054
3055 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003056 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003057 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003058 }else if( eFileLock==EXCLUSIVE_LOCK ){
3059 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003060 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003061 }
3062
3063afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003064 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003065 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3066 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003067 return rc;
3068}
3069
3070/*
drh308c2a52010-05-14 11:30:18 +00003071** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003072** must be either NO_LOCK or SHARED_LOCK.
3073**
3074** If the locking level of the file descriptor is already at or below
3075** the requested locking level, this routine is a no-op.
3076*/
drh308c2a52010-05-14 11:30:18 +00003077static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003078 int rc = SQLITE_OK;
3079 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003080 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003081 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3082 int skipShared = 0;
3083#ifdef SQLITE_TEST
3084 int h = pFile->h;
3085#endif
drhbfe66312006-10-03 17:40:40 +00003086
3087 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003088 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003089 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003090 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003091
drh308c2a52010-05-14 11:30:18 +00003092 assert( eFileLock<=SHARED_LOCK );
3093 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003094 return SQLITE_OK;
3095 }
drh8af6c222010-05-14 12:43:01 +00003096 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003097 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003098 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003099 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003100 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003101 SimulateIOErrorBenign(1);
3102 SimulateIOError( h=(-1) )
3103 SimulateIOErrorBenign(0);
3104
drhd3d8c042012-05-29 17:02:40 +00003105#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003106 /* When reducing a lock such that other processes can start
3107 ** reading the database file again, make sure that the
3108 ** transaction counter was updated if any part of the database
3109 ** file changed. If the transaction counter is not updated,
3110 ** other connections to the same file might not realize that
3111 ** the file has changed and hence might not know to flush their
3112 ** cache. The use of a stale cache can lead to database corruption.
3113 */
3114 assert( pFile->inNormalWrite==0
3115 || pFile->dbUpdate==0
3116 || pFile->transCntrChng==1 );
3117 pFile->inNormalWrite = 0;
3118#endif
aswiftaebf4132008-11-21 00:10:35 +00003119
drh308c2a52010-05-14 11:30:18 +00003120 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003121 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003122 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003123 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003124 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003125 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3126 } else {
3127 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003128 }
3129 }
drh308c2a52010-05-14 11:30:18 +00003130 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003131 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003132 }
drh308c2a52010-05-14 11:30:18 +00003133 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003134 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3135 if( !rc ){
3136 context->reserved = 0;
3137 }
aswiftaebf4132008-11-21 00:10:35 +00003138 }
drh8af6c222010-05-14 12:43:01 +00003139 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3140 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003141 }
aswiftaebf4132008-11-21 00:10:35 +00003142 }
drh308c2a52010-05-14 11:30:18 +00003143 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003144
drh7ed97b92010-01-20 13:07:21 +00003145 /* Decrement the shared lock counter. Release the lock using an
3146 ** OS call only when all threads in this same process have released
3147 ** the lock.
3148 */
drh8af6c222010-05-14 12:43:01 +00003149 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3150 pInode->nShared--;
3151 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003152 SimulateIOErrorBenign(1);
3153 SimulateIOError( h=(-1) )
3154 SimulateIOErrorBenign(0);
3155 if( !skipShared ){
3156 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3157 }
3158 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003159 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003160 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003161 }
3162 }
3163 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003164 pInode->nLock--;
3165 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003166 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003167 }
drhbfe66312006-10-03 17:40:40 +00003168 }
drh7ed97b92010-01-20 13:07:21 +00003169
drhda6dc242018-07-23 21:10:37 +00003170 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003171 if( rc==SQLITE_OK ){
3172 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003173 }
drhbfe66312006-10-03 17:40:40 +00003174 return rc;
3175}
3176
3177/*
drh339eb0b2008-03-07 15:34:11 +00003178** Close a file & cleanup AFP specific locking context
3179*/
danielk1977e339d652008-06-28 11:23:00 +00003180static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003181 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003182 unixFile *pFile = (unixFile*)id;
3183 assert( id!=0 );
3184 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003185 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003186 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003187 if( pFile->pInode ){
3188 unixInodeInfo *pInode = pFile->pInode;
3189 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003190 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003191 /* If there are outstanding locks, do not actually close the file just
3192 ** yet because that would clear those locks. Instead, add the file
3193 ** descriptor to pInode->aPending. It will be automatically closed when
3194 ** the last lock is cleared.
3195 */
3196 setPendingFd(pFile);
3197 }
3198 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003199 }
drha8de1e12015-11-30 00:05:39 +00003200 releaseInodeInfo(pFile);
3201 sqlite3_free(pFile->lockingContext);
3202 rc = closeUnixFile(id);
3203 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003204 return rc;
drhbfe66312006-10-03 17:40:40 +00003205}
3206
drhd2cb50b2009-01-09 21:41:17 +00003207#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003208/*
3209** The code above is the AFP lock implementation. The code is specific
3210** to MacOSX and does not work on other unix platforms. No alternative
3211** is available. If you don't compile for a mac, then the "unix-afp"
3212** VFS is not available.
3213**
3214********************* End of the AFP lock implementation **********************
3215******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003216
drh7ed97b92010-01-20 13:07:21 +00003217/******************************************************************************
3218*************************** Begin NFS Locking ********************************/
3219
3220#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3221/*
drh308c2a52010-05-14 11:30:18 +00003222 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003223 ** must be either NO_LOCK or SHARED_LOCK.
3224 **
3225 ** If the locking level of the file descriptor is already at or below
3226 ** the requested locking level, this routine is a no-op.
3227 */
drh308c2a52010-05-14 11:30:18 +00003228static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003229 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003230}
3231
3232#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3233/*
3234** The code above is the NFS lock implementation. The code is specific
3235** to MacOSX and does not work on other unix platforms. No alternative
3236** is available.
3237**
3238********************* End of the NFS lock implementation **********************
3239******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003240
3241/******************************************************************************
3242**************** Non-locking sqlite3_file methods *****************************
3243**
3244** The next division contains implementations for all methods of the
3245** sqlite3_file object other than the locking methods. The locking
3246** methods were defined in divisions above (one locking method per
3247** division). Those methods that are common to all locking modes
3248** are gather together into this division.
3249*/
drhbfe66312006-10-03 17:40:40 +00003250
3251/*
drh734c9862008-11-28 15:37:20 +00003252** Seek to the offset passed as the second argument, then read cnt
3253** bytes into pBuf. Return the number of bytes actually read.
3254**
3255** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3256** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3257** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003258** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003259** See tickets #2741 and #2681.
3260**
3261** To avoid stomping the errno value on a failed read the lastErrno value
3262** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003263*/
drh734c9862008-11-28 15:37:20 +00003264static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3265 int got;
drh58024642011-11-07 18:16:00 +00003266 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003267#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3268 i64 newOffset;
3269#endif
drh734c9862008-11-28 15:37:20 +00003270 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003271 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003272 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003273 do{
drh734c9862008-11-28 15:37:20 +00003274#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003275 got = osPread(id->h, pBuf, cnt, offset);
3276 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003277#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003278 got = osPread64(id->h, pBuf, cnt, offset);
3279 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003280#else
drha46cadc2016-03-04 03:02:06 +00003281 newOffset = lseek(id->h, offset, SEEK_SET);
3282 SimulateIOError( newOffset = -1 );
3283 if( newOffset<0 ){
3284 storeLastErrno((unixFile*)id, errno);
3285 return -1;
3286 }
3287 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003288#endif
drh58024642011-11-07 18:16:00 +00003289 if( got==cnt ) break;
3290 if( got<0 ){
3291 if( errno==EINTR ){ got = 1; continue; }
3292 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003293 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003294 break;
3295 }else if( got>0 ){
3296 cnt -= got;
3297 offset += got;
3298 prior += got;
3299 pBuf = (void*)(got + (char*)pBuf);
3300 }
3301 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003302 TIMER_END;
drh58024642011-11-07 18:16:00 +00003303 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3304 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3305 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003306}
3307
3308/*
drh734c9862008-11-28 15:37:20 +00003309** Read data from a file into a buffer. Return SQLITE_OK if all
3310** bytes were read successfully and SQLITE_IOERR if anything goes
3311** wrong.
drh339eb0b2008-03-07 15:34:11 +00003312*/
drh734c9862008-11-28 15:37:20 +00003313static int unixRead(
3314 sqlite3_file *id,
3315 void *pBuf,
3316 int amt,
3317 sqlite3_int64 offset
3318){
dan08da86a2009-08-21 17:18:03 +00003319 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003320 int got;
3321 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003322 assert( offset>=0 );
3323 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003324
dan08da86a2009-08-21 17:18:03 +00003325 /* If this is a database file (not a journal, master-journal or temp
3326 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003327#if 0
drhc68886b2017-08-18 16:09:52 +00003328 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003329 || offset>=PENDING_BYTE+512
3330 || offset+amt<=PENDING_BYTE
3331 );
dan7c246102010-04-12 19:00:29 +00003332#endif
drh08c6d442009-02-09 17:34:07 +00003333
drh9b4c59f2013-04-15 17:03:42 +00003334#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003335 /* Deal with as much of this read request as possible by transfering
3336 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003337 if( offset<pFile->mmapSize ){
3338 if( offset+amt <= pFile->mmapSize ){
3339 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3340 return SQLITE_OK;
3341 }else{
3342 int nCopy = pFile->mmapSize - offset;
3343 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3344 pBuf = &((u8 *)pBuf)[nCopy];
3345 amt -= nCopy;
3346 offset += nCopy;
3347 }
3348 }
drh6e0b6d52013-04-09 16:19:20 +00003349#endif
danf23da962013-03-23 21:00:41 +00003350
dan08da86a2009-08-21 17:18:03 +00003351 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003352 if( got==amt ){
3353 return SQLITE_OK;
3354 }else if( got<0 ){
3355 /* lastErrno set by seekAndRead */
3356 return SQLITE_IOERR_READ;
3357 }else{
drh4bf66fd2015-02-19 02:43:02 +00003358 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003359 /* Unread parts of the buffer must be zero-filled */
3360 memset(&((char*)pBuf)[got], 0, amt-got);
3361 return SQLITE_IOERR_SHORT_READ;
3362 }
3363}
3364
3365/*
dan47a2b4a2013-04-26 16:09:29 +00003366** Attempt to seek the file-descriptor passed as the first argument to
3367** absolute offset iOff, then attempt to write nBuf bytes of data from
3368** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3369** return the actual number of bytes written (which may be less than
3370** nBuf).
3371*/
3372static int seekAndWriteFd(
3373 int fd, /* File descriptor to write to */
3374 i64 iOff, /* File offset to begin writing at */
3375 const void *pBuf, /* Copy data from this buffer to the file */
3376 int nBuf, /* Size of buffer pBuf in bytes */
3377 int *piErrno /* OUT: Error number if error occurs */
3378){
3379 int rc = 0; /* Value returned by system call */
3380
3381 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003382 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003383 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003384 nBuf &= 0x1ffff;
3385 TIMER_START;
3386
3387#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003388 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003389#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003390 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003391#else
3392 do{
3393 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003394 SimulateIOError( iSeek = -1 );
3395 if( iSeek<0 ){
3396 rc = -1;
3397 break;
dan47a2b4a2013-04-26 16:09:29 +00003398 }
3399 rc = osWrite(fd, pBuf, nBuf);
3400 }while( rc<0 && errno==EINTR );
3401#endif
3402
3403 TIMER_END;
3404 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3405
drhe1818ec2015-12-01 16:21:35 +00003406 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003407 return rc;
3408}
3409
3410
3411/*
drh734c9862008-11-28 15:37:20 +00003412** Seek to the offset in id->offset then read cnt bytes into pBuf.
3413** Return the number of bytes actually read. Update the offset.
3414**
3415** To avoid stomping the errno value on a failed write the lastErrno value
3416** is set before returning.
3417*/
3418static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003419 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003420}
3421
3422
3423/*
3424** Write data from a buffer into a file. Return SQLITE_OK on success
3425** or some other error code on failure.
3426*/
3427static int unixWrite(
3428 sqlite3_file *id,
3429 const void *pBuf,
3430 int amt,
3431 sqlite3_int64 offset
3432){
dan08da86a2009-08-21 17:18:03 +00003433 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003434 int wrote = 0;
3435 assert( id );
3436 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003437
dan08da86a2009-08-21 17:18:03 +00003438 /* If this is a database file (not a journal, master-journal or temp
3439 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003440#if 0
drhc68886b2017-08-18 16:09:52 +00003441 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003442 || offset>=PENDING_BYTE+512
3443 || offset+amt<=PENDING_BYTE
3444 );
dan7c246102010-04-12 19:00:29 +00003445#endif
drh08c6d442009-02-09 17:34:07 +00003446
drhd3d8c042012-05-29 17:02:40 +00003447#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003448 /* If we are doing a normal write to a database file (as opposed to
3449 ** doing a hot-journal rollback or a write to some file other than a
3450 ** normal database file) then record the fact that the database
3451 ** has changed. If the transaction counter is modified, record that
3452 ** fact too.
3453 */
dan08da86a2009-08-21 17:18:03 +00003454 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003455 pFile->dbUpdate = 1; /* The database has been modified */
3456 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003457 int rc;
drh8f941bc2009-01-14 23:03:40 +00003458 char oldCntr[4];
3459 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003460 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003461 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003462 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003463 pFile->transCntrChng = 1; /* The transaction counter has changed */
3464 }
3465 }
3466 }
3467#endif
3468
danfe33e392015-11-17 20:56:06 +00003469#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003470 /* Deal with as much of this write request as possible by transfering
3471 ** data from the memory mapping using memcpy(). */
3472 if( offset<pFile->mmapSize ){
3473 if( offset+amt <= pFile->mmapSize ){
3474 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3475 return SQLITE_OK;
3476 }else{
3477 int nCopy = pFile->mmapSize - offset;
3478 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3479 pBuf = &((u8 *)pBuf)[nCopy];
3480 amt -= nCopy;
3481 offset += nCopy;
3482 }
3483 }
drh6e0b6d52013-04-09 16:19:20 +00003484#endif
drh02bf8b42015-09-01 23:51:53 +00003485
3486 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003487 amt -= wrote;
3488 offset += wrote;
3489 pBuf = &((char*)pBuf)[wrote];
3490 }
3491 SimulateIOError(( wrote=(-1), amt=1 ));
3492 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003493
drh02bf8b42015-09-01 23:51:53 +00003494 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003495 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003496 /* lastErrno set by seekAndWrite */
3497 return SQLITE_IOERR_WRITE;
3498 }else{
drh4bf66fd2015-02-19 02:43:02 +00003499 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003500 return SQLITE_FULL;
3501 }
3502 }
dan6e09d692010-07-27 18:34:15 +00003503
drh734c9862008-11-28 15:37:20 +00003504 return SQLITE_OK;
3505}
3506
3507#ifdef SQLITE_TEST
3508/*
3509** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003510** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003511*/
3512int sqlite3_sync_count = 0;
3513int sqlite3_fullsync_count = 0;
3514#endif
3515
3516/*
drh89240432009-03-25 01:06:01 +00003517** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003518** Others do no. To be safe, we will stick with the (slightly slower)
3519** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003520** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003521*/
drhf7a4a1b2015-01-10 18:02:45 +00003522#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003523# define fdatasync fsync
3524#endif
3525
3526/*
3527** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3528** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3529** only available on Mac OS X. But that could change.
3530*/
3531#ifdef F_FULLFSYNC
3532# define HAVE_FULLFSYNC 1
3533#else
3534# define HAVE_FULLFSYNC 0
3535#endif
3536
3537
3538/*
3539** The fsync() system call does not work as advertised on many
3540** unix systems. The following procedure is an attempt to make
3541** it work better.
3542**
3543** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3544** for testing when we want to run through the test suite quickly.
3545** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3546** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3547** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003548**
3549** SQLite sets the dataOnly flag if the size of the file is unchanged.
3550** The idea behind dataOnly is that it should only write the file content
3551** to disk, not the inode. We only set dataOnly if the file size is
3552** unchanged since the file size is part of the inode. However,
3553** Ted Ts'o tells us that fdatasync() will also write the inode if the
3554** file size has changed. The only real difference between fdatasync()
3555** and fsync(), Ted tells us, is that fdatasync() will not flush the
3556** inode if the mtime or owner or other inode attributes have changed.
3557** We only care about the file size, not the other file attributes, so
3558** as far as SQLite is concerned, an fdatasync() is always adequate.
3559** So, we always use fdatasync() if it is available, regardless of
3560** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003561*/
3562static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003563 int rc;
drh734c9862008-11-28 15:37:20 +00003564
3565 /* The following "ifdef/elif/else/" block has the same structure as
3566 ** the one below. It is replicated here solely to avoid cluttering
3567 ** up the real code with the UNUSED_PARAMETER() macros.
3568 */
3569#ifdef SQLITE_NO_SYNC
3570 UNUSED_PARAMETER(fd);
3571 UNUSED_PARAMETER(fullSync);
3572 UNUSED_PARAMETER(dataOnly);
3573#elif HAVE_FULLFSYNC
3574 UNUSED_PARAMETER(dataOnly);
3575#else
3576 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003577 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003578#endif
3579
3580 /* Record the number of times that we do a normal fsync() and
3581 ** FULLSYNC. This is used during testing to verify that this procedure
3582 ** gets called with the correct arguments.
3583 */
3584#ifdef SQLITE_TEST
3585 if( fullSync ) sqlite3_fullsync_count++;
3586 sqlite3_sync_count++;
3587#endif
3588
3589 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003590 ** no-op. But go ahead and call fstat() to validate the file
3591 ** descriptor as we need a method to provoke a failure during
3592 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003593 */
3594#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003595 {
3596 struct stat buf;
3597 rc = osFstat(fd, &buf);
3598 }
drh734c9862008-11-28 15:37:20 +00003599#elif HAVE_FULLFSYNC
3600 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003601 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003602 }else{
3603 rc = 1;
3604 }
3605 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003606 ** It shouldn't be possible for fullfsync to fail on the local
3607 ** file system (on OSX), so failure indicates that FULLFSYNC
3608 ** isn't supported for this file system. So, attempt an fsync
3609 ** and (for now) ignore the overhead of a superfluous fcntl call.
3610 ** It'd be better to detect fullfsync support once and avoid
3611 ** the fcntl call every time sync is called.
3612 */
drh734c9862008-11-28 15:37:20 +00003613 if( rc ) rc = fsync(fd);
3614
drh7ed97b92010-01-20 13:07:21 +00003615#elif defined(__APPLE__)
3616 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3617 ** so currently we default to the macro that redefines fdatasync to fsync
3618 */
3619 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003620#else
drh0b647ff2009-03-21 14:41:04 +00003621 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003622#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003623 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003624 rc = fsync(fd);
3625 }
drh0b647ff2009-03-21 14:41:04 +00003626#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003627#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3628
3629 if( OS_VXWORKS && rc!= -1 ){
3630 rc = 0;
3631 }
chw97185482008-11-17 08:05:31 +00003632 return rc;
drhbfe66312006-10-03 17:40:40 +00003633}
3634
drh734c9862008-11-28 15:37:20 +00003635/*
drh0059eae2011-08-08 23:48:40 +00003636** Open a file descriptor to the directory containing file zFilename.
3637** If successful, *pFd is set to the opened file descriptor and
3638** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3639** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3640** value.
3641**
drh90315a22011-08-10 01:52:12 +00003642** The directory file descriptor is used for only one thing - to
3643** fsync() a directory to make sure file creation and deletion events
3644** are flushed to disk. Such fsyncs are not needed on newer
3645** journaling filesystems, but are required on older filesystems.
3646**
3647** This routine can be overridden using the xSetSysCall interface.
3648** The ability to override this routine was added in support of the
3649** chromium sandbox. Opening a directory is a security risk (we are
3650** told) so making it overrideable allows the chromium sandbox to
3651** replace this routine with a harmless no-op. To make this routine
3652** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3653** *pFd set to a negative number.
3654**
drh0059eae2011-08-08 23:48:40 +00003655** If SQLITE_OK is returned, the caller is responsible for closing
3656** the file descriptor *pFd using close().
3657*/
3658static int openDirectory(const char *zFilename, int *pFd){
3659 int ii;
3660 int fd = -1;
3661 char zDirname[MAX_PATHNAME+1];
3662
3663 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003664 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3665 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003666 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003667 }else{
3668 if( zDirname[0]!='/' ) zDirname[0] = '.';
3669 zDirname[1] = 0;
3670 }
3671 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
3672 if( fd>=0 ){
3673 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003674 }
3675 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003676 if( fd>=0 ) return SQLITE_OK;
3677 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003678}
3679
3680/*
drh734c9862008-11-28 15:37:20 +00003681** Make sure all writes to a particular file are committed to disk.
3682**
3683** If dataOnly==0 then both the file itself and its metadata (file
3684** size, access time, etc) are synced. If dataOnly!=0 then only the
3685** file data is synced.
3686**
3687** Under Unix, also make sure that the directory entry for the file
3688** has been created by fsync-ing the directory that contains the file.
3689** If we do not do this and we encounter a power failure, the directory
3690** entry for the journal might not exist after we reboot. The next
3691** SQLite to access the file will not know that the journal exists (because
3692** the directory entry for the journal was never created) and the transaction
3693** will not roll back - possibly leading to database corruption.
3694*/
3695static int unixSync(sqlite3_file *id, int flags){
3696 int rc;
3697 unixFile *pFile = (unixFile*)id;
3698
3699 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3700 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3701
3702 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3703 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3704 || (flags&0x0F)==SQLITE_SYNC_FULL
3705 );
3706
3707 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3708 ** line is to test that doing so does not cause any problems.
3709 */
3710 SimulateDiskfullError( return SQLITE_FULL );
3711
3712 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003713 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003714 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3715 SimulateIOError( rc=1 );
3716 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003717 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003718 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003719 }
drh0059eae2011-08-08 23:48:40 +00003720
3721 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003722 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003723 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003724 */
3725 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3726 int dirfd;
3727 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003728 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003729 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003730 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003731 full_fsync(dirfd, 0, 0);
3732 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003733 }else{
3734 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003735 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003736 }
drh0059eae2011-08-08 23:48:40 +00003737 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003738 }
3739 return rc;
3740}
3741
3742/*
3743** Truncate an open file to a specified size
3744*/
3745static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003746 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003747 int rc;
dan6e09d692010-07-27 18:34:15 +00003748 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003749 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003750
3751 /* If the user has configured a chunk-size for this file, truncate the
3752 ** file so that it consists of an integer number of chunks (i.e. the
3753 ** actual file size after the operation may be larger than the requested
3754 ** size).
3755 */
drhb8af4b72012-04-05 20:04:39 +00003756 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003757 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3758 }
3759
dan2ee53412014-09-06 16:49:40 +00003760 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003761 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003762 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003763 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003764 }else{
drhd3d8c042012-05-29 17:02:40 +00003765#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003766 /* If we are doing a normal write to a database file (as opposed to
3767 ** doing a hot-journal rollback or a write to some file other than a
3768 ** normal database file) and we truncate the file to zero length,
3769 ** that effectively updates the change counter. This might happen
3770 ** when restoring a database using the backup API from a zero-length
3771 ** source.
3772 */
dan6e09d692010-07-27 18:34:15 +00003773 if( pFile->inNormalWrite && nByte==0 ){
3774 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003775 }
danf23da962013-03-23 21:00:41 +00003776#endif
danc0003312013-03-22 17:46:11 +00003777
mistachkine98844f2013-08-24 00:59:24 +00003778#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003779 /* If the file was just truncated to a size smaller than the currently
3780 ** mapped region, reduce the effective mapping size as well. SQLite will
3781 ** use read() and write() to access data beyond this point from now on.
3782 */
3783 if( nByte<pFile->mmapSize ){
3784 pFile->mmapSize = nByte;
3785 }
mistachkine98844f2013-08-24 00:59:24 +00003786#endif
drh3313b142009-11-06 04:13:18 +00003787
drh734c9862008-11-28 15:37:20 +00003788 return SQLITE_OK;
3789 }
3790}
3791
3792/*
3793** Determine the current size of a file in bytes
3794*/
3795static int unixFileSize(sqlite3_file *id, i64 *pSize){
3796 int rc;
3797 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003798 assert( id );
3799 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003800 SimulateIOError( rc=1 );
3801 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003802 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003803 return SQLITE_IOERR_FSTAT;
3804 }
3805 *pSize = buf.st_size;
3806
drh8af6c222010-05-14 12:43:01 +00003807 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003808 ** writes a single byte into that file in order to work around a bug
3809 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3810 ** layers, we need to report this file size as zero even though it is
3811 ** really 1. Ticket #3260.
3812 */
3813 if( *pSize==1 ) *pSize = 0;
3814
3815
3816 return SQLITE_OK;
3817}
3818
drhd2cb50b2009-01-09 21:41:17 +00003819#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003820/*
3821** Handler for proxy-locking file-control verbs. Defined below in the
3822** proxying locking division.
3823*/
3824static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003825#endif
drh715ff302008-12-03 22:32:44 +00003826
dan502019c2010-07-28 14:26:17 +00003827/*
3828** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003829** file-control operation. Enlarge the database to nBytes in size
3830** (rounded up to the next chunk-size). If the database is already
3831** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003832*/
3833static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003834 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003835 i64 nSize; /* Required file size */
3836 struct stat buf; /* Used to hold return values of fstat() */
3837
drh4bf66fd2015-02-19 02:43:02 +00003838 if( osFstat(pFile->h, &buf) ){
3839 return SQLITE_IOERR_FSTAT;
3840 }
dan502019c2010-07-28 14:26:17 +00003841
3842 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3843 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003844
dan502019c2010-07-28 14:26:17 +00003845#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003846 /* The code below is handling the return value of osFallocate()
3847 ** correctly. posix_fallocate() is defined to "returns zero on success,
3848 ** or an error number on failure". See the manpage for details. */
3849 int err;
drhff812312011-02-23 13:33:46 +00003850 do{
dan661d71a2011-03-30 19:08:03 +00003851 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3852 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003853 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003854#else
dan592bf7f2014-12-30 19:58:31 +00003855 /* If the OS does not have posix_fallocate(), fake it. Write a
3856 ** single byte to the last byte in each block that falls entirely
3857 ** within the extended region. Then, if required, a single byte
3858 ** at offset (nSize-1), to set the size of the file correctly.
3859 ** This is a similar technique to that used by glibc on systems
3860 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003861 */
3862 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003863 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003864 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003865
drh053378d2015-12-01 22:09:42 +00003866 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003867 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003868 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003869 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3870 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003871 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003872 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003873 }
dan502019c2010-07-28 14:26:17 +00003874#endif
3875 }
3876 }
3877
mistachkine98844f2013-08-24 00:59:24 +00003878#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003879 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003880 int rc;
3881 if( pFile->szChunk<=0 ){
3882 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003883 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003884 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3885 }
3886 }
3887
3888 rc = unixMapfile(pFile, nByte);
3889 return rc;
3890 }
mistachkine98844f2013-08-24 00:59:24 +00003891#endif
danf23da962013-03-23 21:00:41 +00003892
dan502019c2010-07-28 14:26:17 +00003893 return SQLITE_OK;
3894}
danielk1977ad94b582007-08-20 06:44:22 +00003895
danielk1977e3026632004-06-22 11:29:02 +00003896/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003897** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003898** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3899**
3900** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3901*/
3902static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3903 if( *pArg<0 ){
3904 *pArg = (pFile->ctrlFlags & mask)!=0;
3905 }else if( (*pArg)==0 ){
3906 pFile->ctrlFlags &= ~mask;
3907 }else{
3908 pFile->ctrlFlags |= mask;
3909 }
3910}
3911
drh696b33e2012-12-06 19:01:42 +00003912/* Forward declaration */
3913static int unixGetTempname(int nBuf, char *zBuf);
3914
drhf12b3f62011-12-21 14:42:29 +00003915/*
drh9e33c2c2007-08-31 18:34:59 +00003916** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003917*/
drhcc6bb3e2007-08-31 16:11:35 +00003918static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003919 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003920 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003921#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003922 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3923 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003924 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003925 }
3926 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3927 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003928 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003929 }
3930 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3931 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003932 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003933 }
drhd76dba72017-07-22 16:00:34 +00003934#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003935
drh9e33c2c2007-08-31 18:34:59 +00003936 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003937 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003938 return SQLITE_OK;
3939 }
drh4bf66fd2015-02-19 02:43:02 +00003940 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003941 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003942 return SQLITE_OK;
3943 }
dan6e09d692010-07-27 18:34:15 +00003944 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003945 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003946 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003947 }
drh9ff27ec2010-05-19 19:26:05 +00003948 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003949 int rc;
3950 SimulateIOErrorBenign(1);
3951 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3952 SimulateIOErrorBenign(0);
3953 return rc;
drhf0b190d2011-07-26 16:03:07 +00003954 }
3955 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003956 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3957 return SQLITE_OK;
3958 }
drhcb15f352011-12-23 01:04:17 +00003959 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3960 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003961 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003962 }
drhde60fc22011-12-14 17:53:36 +00003963 case SQLITE_FCNTL_VFSNAME: {
3964 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3965 return SQLITE_OK;
3966 }
drh696b33e2012-12-06 19:01:42 +00003967 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003968 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003969 if( zTFile ){
3970 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3971 *(char**)pArg = zTFile;
3972 }
3973 return SQLITE_OK;
3974 }
drhb959a012013-12-07 12:29:22 +00003975 case SQLITE_FCNTL_HAS_MOVED: {
3976 *(int*)pArg = fileHasMoved(pFile);
3977 return SQLITE_OK;
3978 }
drhf0119b22018-03-26 17:40:53 +00003979#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3980 case SQLITE_FCNTL_LOCK_TIMEOUT: {
3981 pFile->iBusyTimeout = *(int*)pArg;
3982 return SQLITE_OK;
3983 }
3984#endif
mistachkine98844f2013-08-24 00:59:24 +00003985#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003986 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00003987 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00003988 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00003989 if( newLimit>sqlite3GlobalConfig.mxMmap ){
3990 newLimit = sqlite3GlobalConfig.mxMmap;
3991 }
dan43c1e622017-08-07 18:13:28 +00003992
3993 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00003994 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
3995 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00003996 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00003997 newLimit = (newLimit & 0x7FFFFFFF);
3998 }
3999
drh9b4c59f2013-04-15 17:03:42 +00004000 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004001 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004002 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004003 if( pFile->mmapSize>0 ){
4004 unixUnmapfile(pFile);
4005 rc = unixMapfile(pFile, -1);
4006 }
danbcb8a862013-04-08 15:30:41 +00004007 }
drh34e258c2013-05-23 01:40:53 +00004008 return rc;
danb2d3de32013-03-14 18:34:37 +00004009 }
mistachkine98844f2013-08-24 00:59:24 +00004010#endif
drhd3d8c042012-05-29 17:02:40 +00004011#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004012 /* The pager calls this method to signal that it has done
4013 ** a rollback and that the database is therefore unchanged and
4014 ** it hence it is OK for the transaction change counter to be
4015 ** unchanged.
4016 */
4017 case SQLITE_FCNTL_DB_UNCHANGED: {
4018 ((unixFile*)id)->dbUpdate = 0;
4019 return SQLITE_OK;
4020 }
4021#endif
drhd2cb50b2009-01-09 21:41:17 +00004022#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004023 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4024 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004025 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004026 }
drhd2cb50b2009-01-09 21:41:17 +00004027#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00004028 }
drh0b52b7d2011-01-26 19:46:22 +00004029 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004030}
4031
4032/*
danefe16972017-07-20 19:49:14 +00004033** If pFd->sectorSize is non-zero when this function is called, it is a
4034** no-op. Otherwise, the values of pFd->sectorSize and
4035** pFd->deviceCharacteristics are set according to the file-system
4036** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004037**
danefe16972017-07-20 19:49:14 +00004038** There are two versions of this function. One for QNX and one for all
4039** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004040*/
danefe16972017-07-20 19:49:14 +00004041#ifndef __QNXNTO__
4042static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004043 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004044 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004045#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004046 int res;
dan9d709542017-07-21 21:06:24 +00004047 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004048
danefe16972017-07-20 19:49:14 +00004049 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004050 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4051 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004052 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004053 }
drhd76dba72017-07-22 16:00:34 +00004054#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004055
4056 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4057 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4058 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4059 }
4060
4061 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4062 }
4063}
4064#else
drh537dddf2012-10-26 13:46:24 +00004065#include <sys/dcmd_blk.h>
4066#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004067static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004068 if( pFile->sectorSize == 0 ){
4069 struct statvfs fsInfo;
4070
4071 /* Set defaults for non-supported filesystems */
4072 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4073 pFile->deviceCharacteristics = 0;
4074 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004075 return;
drh537dddf2012-10-26 13:46:24 +00004076 }
4077
4078 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4079 pFile->sectorSize = fsInfo.f_bsize;
4080 pFile->deviceCharacteristics =
4081 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4082 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4083 ** the write succeeds */
4084 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4085 ** so it is ordered */
4086 0;
4087 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4088 pFile->sectorSize = fsInfo.f_bsize;
4089 pFile->deviceCharacteristics =
4090 /* etfs cluster size writes are atomic */
4091 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4092 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4093 ** the write succeeds */
4094 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4095 ** so it is ordered */
4096 0;
4097 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4098 pFile->sectorSize = fsInfo.f_bsize;
4099 pFile->deviceCharacteristics =
4100 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4101 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4102 ** the write succeeds */
4103 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4104 ** so it is ordered */
4105 0;
4106 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4107 pFile->sectorSize = fsInfo.f_bsize;
4108 pFile->deviceCharacteristics =
4109 /* full bitset of atomics from max sector size and smaller */
4110 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4111 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4112 ** so it is ordered */
4113 0;
4114 }else if( strstr(fsInfo.f_basetype, "dos") ){
4115 pFile->sectorSize = fsInfo.f_bsize;
4116 pFile->deviceCharacteristics =
4117 /* full bitset of atomics from max sector size and smaller */
4118 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4119 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4120 ** so it is ordered */
4121 0;
4122 }else{
4123 pFile->deviceCharacteristics =
4124 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4125 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4126 ** the write succeeds */
4127 0;
4128 }
4129 }
4130 /* Last chance verification. If the sector size isn't a multiple of 512
4131 ** then it isn't valid.*/
4132 if( pFile->sectorSize % 512 != 0 ){
4133 pFile->deviceCharacteristics = 0;
4134 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4135 }
drh537dddf2012-10-26 13:46:24 +00004136}
danefe16972017-07-20 19:49:14 +00004137#endif
4138
4139/*
4140** Return the sector size in bytes of the underlying block device for
4141** the specified file. This is almost always 512 bytes, but may be
4142** larger for some devices.
4143**
4144** SQLite code assumes this function cannot fail. It also assumes that
4145** if two files are created in the same file-system directory (i.e.
4146** a database and its journal file) that the sector size will be the
4147** same for both.
4148*/
4149static int unixSectorSize(sqlite3_file *id){
4150 unixFile *pFd = (unixFile*)id;
4151 setDeviceCharacteristics(pFd);
4152 return pFd->sectorSize;
4153}
danielk1977a3d4c882007-03-23 10:08:38 +00004154
danielk197790949c22007-08-17 16:50:38 +00004155/*
drhf12b3f62011-12-21 14:42:29 +00004156** Return the device characteristics for the file.
4157**
drhcb15f352011-12-23 01:04:17 +00004158** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004159** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004160** file system does not always provide powersafe overwrites. (In other
4161** words, after a power-loss event, parts of the file that were never
4162** written might end up being altered.) However, non-PSOW behavior is very,
4163** very rare. And asserting PSOW makes a large reduction in the amount
4164** of required I/O for journaling, since a lot of padding is eliminated.
4165** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4166** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004167*/
drhf12b3f62011-12-21 14:42:29 +00004168static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004169 unixFile *pFd = (unixFile*)id;
4170 setDeviceCharacteristics(pFd);
4171 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004172}
4173
dan702eec12014-06-23 10:04:58 +00004174#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004175
dan702eec12014-06-23 10:04:58 +00004176/*
4177** Return the system page size.
4178**
4179** This function should not be called directly by other code in this file.
4180** Instead, it should be called via macro osGetpagesize().
4181*/
4182static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004183#if OS_VXWORKS
4184 return 1024;
4185#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004186 return getpagesize();
4187#else
4188 return (int)sysconf(_SC_PAGESIZE);
4189#endif
4190}
4191
4192#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4193
4194#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004195
4196/*
drhd91c68f2010-05-14 14:52:25 +00004197** Object used to represent an shared memory buffer.
4198**
4199** When multiple threads all reference the same wal-index, each thread
4200** has its own unixShm object, but they all point to a single instance
4201** of this unixShmNode object. In other words, each wal-index is opened
4202** only once per process.
4203**
4204** Each unixShmNode object is connected to a single unixInodeInfo object.
4205** We could coalesce this object into unixInodeInfo, but that would mean
4206** every open file that does not use shared memory (in other words, most
4207** open files) would have to carry around this extra information. So
4208** the unixInodeInfo object contains a pointer to this unixShmNode object
4209** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004210**
4211** unixMutexHeld() must be true when creating or destroying
4212** this object or while reading or writing the following fields:
4213**
4214** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004215**
4216** The following fields are read-only after the object is created:
4217**
drh8820c8d2018-10-02 19:58:08 +00004218** hShm
drhd9e5c4f2010-05-12 18:01:39 +00004219** zFilename
4220**
drh8820c8d2018-10-02 19:58:08 +00004221** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004222** unixMutexHeld() is true when reading or writing any other field
4223** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004224*/
drhd91c68f2010-05-14 14:52:25 +00004225struct unixShmNode {
4226 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drh24efa542018-10-02 19:36:40 +00004227 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004228 char *zFilename; /* Name of the mmapped file */
drh8820c8d2018-10-02 19:58:08 +00004229 int hShm; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004230 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004231 u16 nRegion; /* Size of array apRegion */
4232 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004233 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004234 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004235 int nRef; /* Number of unixShm objects pointing to this */
4236 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004237#ifdef SQLITE_DEBUG
4238 u8 exclMask; /* Mask of exclusive locks held */
4239 u8 sharedMask; /* Mask of shared locks held */
4240 u8 nextShmId; /* Next available unixShm.id value */
4241#endif
4242};
4243
4244/*
drhd9e5c4f2010-05-12 18:01:39 +00004245** Structure used internally by this VFS to record the state of an
4246** open shared memory connection.
4247**
drhd91c68f2010-05-14 14:52:25 +00004248** The following fields are initialized when this object is created and
4249** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004250**
drh24efa542018-10-02 19:36:40 +00004251** unixShm.pShmNode
drhd91c68f2010-05-14 14:52:25 +00004252** unixShm.id
4253**
drh24efa542018-10-02 19:36:40 +00004254** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4255** be held while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004256*/
4257struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004258 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4259 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drh24efa542018-10-02 19:36:40 +00004260 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
drhfd532312011-08-31 18:35:34 +00004261 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004262 u16 sharedMask; /* Mask of shared locks held */
4263 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004264};
4265
4266/*
drhd9e5c4f2010-05-12 18:01:39 +00004267** Constants used for locking
4268*/
drhbd9676c2010-06-23 17:58:38 +00004269#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004270#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004271
drhd9e5c4f2010-05-12 18:01:39 +00004272/*
drh73b64e42010-05-30 19:55:15 +00004273** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004274**
4275** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4276** otherwise.
4277*/
4278static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004279 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004280 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004281 int ofst, /* First byte of the locking range */
4282 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004283){
drhbbf76ee2015-03-10 20:22:35 +00004284 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4285 struct flock f; /* The posix advisory locking structure */
4286 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004287
drhd91c68f2010-05-14 14:52:25 +00004288 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004289 pShmNode = pFile->pInode->pShmNode;
drh24efa542018-10-02 19:36:40 +00004290 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
drh9b7e8e12018-10-02 20:16:41 +00004291 assert( pShmNode->nRef>0 || unixMutexHeld() );
drhd9e5c4f2010-05-12 18:01:39 +00004292
dan9181ae92017-10-26 17:05:22 +00004293 /* Shared locks never span more than one byte */
4294 assert( n==1 || lockType!=F_RDLCK );
4295
4296 /* Locks are within range */
4297 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4298
drh8820c8d2018-10-02 19:58:08 +00004299 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004300 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004301 f.l_type = lockType;
4302 f.l_whence = SEEK_SET;
4303 f.l_start = ofst;
4304 f.l_len = n;
drh8820c8d2018-10-02 19:58:08 +00004305 rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
drh3cb93392011-03-12 18:10:44 +00004306 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4307 }
drhd9e5c4f2010-05-12 18:01:39 +00004308
4309 /* Update the global lock state and do debug tracing */
4310#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004311 { u16 mask;
4312 OSTRACE(("SHM-LOCK "));
4313 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4314 if( rc==SQLITE_OK ){
4315 if( lockType==F_UNLCK ){
4316 OSTRACE(("unlock %d ok", ofst));
4317 pShmNode->exclMask &= ~mask;
4318 pShmNode->sharedMask &= ~mask;
4319 }else if( lockType==F_RDLCK ){
4320 OSTRACE(("read-lock %d ok", ofst));
4321 pShmNode->exclMask &= ~mask;
4322 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004323 }else{
dan9181ae92017-10-26 17:05:22 +00004324 assert( lockType==F_WRLCK );
4325 OSTRACE(("write-lock %d ok", ofst));
4326 pShmNode->exclMask |= mask;
4327 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004328 }
dan9181ae92017-10-26 17:05:22 +00004329 }else{
4330 if( lockType==F_UNLCK ){
4331 OSTRACE(("unlock %d failed", ofst));
4332 }else if( lockType==F_RDLCK ){
4333 OSTRACE(("read-lock failed"));
4334 }else{
4335 assert( lockType==F_WRLCK );
4336 OSTRACE(("write-lock %d failed", ofst));
4337 }
4338 }
4339 OSTRACE((" - afterwards %03x,%03x\n",
4340 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004341 }
drhd9e5c4f2010-05-12 18:01:39 +00004342#endif
4343
4344 return rc;
4345}
4346
dan781e34c2014-03-20 08:59:47 +00004347/*
dan781e34c2014-03-20 08:59:47 +00004348** Return the minimum number of 32KB shm regions that should be mapped at
4349** a time, assuming that each mapping must be an integer multiple of the
4350** current system page-size.
4351**
4352** Usually, this is 1. The exception seems to be systems that are configured
4353** to use 64KB pages - in this case each mapping must cover at least two
4354** shm regions.
4355*/
4356static int unixShmRegionPerMap(void){
4357 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004358 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004359 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4360 if( pgsz<shmsz ) return 1;
4361 return pgsz/shmsz;
4362}
drhd9e5c4f2010-05-12 18:01:39 +00004363
4364/*
drhd91c68f2010-05-14 14:52:25 +00004365** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004366**
4367** This is not a VFS shared-memory method; it is a utility function called
4368** by VFS shared-memory methods.
4369*/
drhd91c68f2010-05-14 14:52:25 +00004370static void unixShmPurge(unixFile *pFd){
4371 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004372 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004373 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004374 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004375 int i;
drhd91c68f2010-05-14 14:52:25 +00004376 assert( p->pInode==pFd->pInode );
drh24efa542018-10-02 19:36:40 +00004377 sqlite3_mutex_free(p->pShmMutex);
dan781e34c2014-03-20 08:59:47 +00004378 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh8820c8d2018-10-02 19:58:08 +00004379 if( p->hShm>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004380 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004381 }else{
4382 sqlite3_free(p->apRegion[i]);
4383 }
dan13a3cb82010-06-11 19:04:21 +00004384 }
dan18801912010-06-14 14:07:50 +00004385 sqlite3_free(p->apRegion);
drh8820c8d2018-10-02 19:58:08 +00004386 if( p->hShm>=0 ){
4387 robust_close(pFd, p->hShm, __LINE__);
4388 p->hShm = -1;
drh0e9365c2011-03-02 02:08:13 +00004389 }
drhd91c68f2010-05-14 14:52:25 +00004390 p->pInode->pShmNode = 0;
4391 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004392 }
4393}
4394
4395/*
dan92c02da2017-11-01 20:59:28 +00004396** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4397** take it now. Return SQLITE_OK if successful, or an SQLite error
4398** code otherwise.
4399**
4400** If the DMS cannot be locked because this is a readonly_shm=1
4401** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004402** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004403*/
4404static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4405 struct flock lock;
4406 int rc = SQLITE_OK;
4407
4408 /* Use F_GETLK to determine the locks other processes are holding
4409 ** on the DMS byte. If it indicates that another process is holding
4410 ** a SHARED lock, then this process may also take a SHARED lock
4411 ** and proceed with opening the *-shm file.
4412 **
4413 ** Or, if no other process is holding any lock, then this process
4414 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4415 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4416 ** downgrade to a SHARED lock on the DMS byte.
4417 **
4418 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4419 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4420 ** version of this code attempted the SHARED lock at this point. But
4421 ** this introduced a subtle race condition: if the process holding
4422 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4423 ** process might open and use the *-shm file without truncating it.
4424 ** And if the *-shm file has been corrupted by a power failure or
4425 ** system crash, the database itself may also become corrupt. */
4426 lock.l_whence = SEEK_SET;
4427 lock.l_start = UNIX_SHM_DMS;
4428 lock.l_len = 1;
4429 lock.l_type = F_WRLCK;
drh8820c8d2018-10-02 19:58:08 +00004430 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
dan92c02da2017-11-01 20:59:28 +00004431 rc = SQLITE_IOERR_LOCK;
4432 }else if( lock.l_type==F_UNLCK ){
4433 if( pShmNode->isReadonly ){
4434 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004435 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004436 }else{
4437 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
drhf7f2a822018-10-11 13:51:48 +00004438 /* The first connection to attach must truncate the -shm file. We
4439 ** truncate to 3 bytes (an arbitrary small number, less than the
4440 ** -shm header size) rather than 0 as a system debugging aid, to
4441 ** help detect if a -shm file truncation is legitimate or is the work
4442 ** or a rogue process. */
4443 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
dan92c02da2017-11-01 20:59:28 +00004444 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4445 }
4446 }
4447 }else if( lock.l_type==F_WRLCK ){
4448 rc = SQLITE_BUSY;
4449 }
4450
4451 if( rc==SQLITE_OK ){
4452 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4453 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4454 }
4455 return rc;
4456}
4457
4458/*
danda9fe0c2010-07-13 18:44:03 +00004459** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004460** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004461**
drh7234c6d2010-06-19 15:10:09 +00004462** The file used to implement shared-memory is in the same directory
4463** as the open database file and has the same name as the open database
4464** file with the "-shm" suffix added. For example, if the database file
4465** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004466** for shared memory will be called "/home/user1/config.db-shm".
4467**
4468** Another approach to is to use files in /dev/shm or /dev/tmp or an
4469** some other tmpfs mount. But if a file in a different directory
4470** from the database file is used, then differing access permissions
4471** or a chroot() might cause two different processes on the same
4472** database to end up using different files for shared memory -
4473** meaning that their memory would not really be shared - resulting
4474** in database corruption. Nevertheless, this tmpfs file usage
4475** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4476** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4477** option results in an incompatible build of SQLite; builds of SQLite
4478** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4479** same database file at the same time, database corruption will likely
4480** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4481** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004482**
4483** When opening a new shared-memory file, if no other instances of that
4484** file are currently open, in this process or in other processes, then
4485** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004486**
4487** If the original database file (pDbFd) is using the "unix-excl" VFS
4488** that means that an exclusive lock is held on the database file and
4489** that no other processes are able to read or write the database. In
4490** that case, we do not really need shared memory. No shared memory
4491** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004492*/
danda9fe0c2010-07-13 18:44:03 +00004493static int unixOpenSharedMemory(unixFile *pDbFd){
4494 struct unixShm *p = 0; /* The connection to be opened */
4495 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004496 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004497 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004498 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004499 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004500
danda9fe0c2010-07-13 18:44:03 +00004501 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004502 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004503 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004504 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004505 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004506
danda9fe0c2010-07-13 18:44:03 +00004507 /* Check to see if a unixShmNode object already exists. Reuse an existing
4508 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004509 */
drh095908e2018-08-13 20:46:18 +00004510 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004511 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004512 pInode = pDbFd->pInode;
4513 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004514 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004515 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004516#ifndef SQLITE_SHM_DIRECTORY
4517 const char *zBasePath = pDbFd->zPath;
4518#endif
danddb0ac42010-07-14 14:48:58 +00004519
4520 /* Call fstat() to figure out the permissions on the database file. If
4521 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004522 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004523 */
drhf3b1ed02015-12-02 13:11:03 +00004524 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004525 rc = SQLITE_IOERR_FSTAT;
4526 goto shm_open_err;
4527 }
4528
drha4ced192010-07-15 18:32:40 +00004529#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004530 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004531#else
drh4bf66fd2015-02-19 02:43:02 +00004532 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004533#endif
drhf3cdcdc2015-04-29 16:50:28 +00004534 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004535 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004536 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004537 goto shm_open_err;
4538 }
drh9cb5a0d2012-01-05 21:19:54 +00004539 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004540 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004541#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004542 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004543 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4544 (u32)sStat.st_ino, (u32)sStat.st_dev);
4545#else
danf12ba662017-11-07 15:43:52 +00004546 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4547 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004548#endif
drh8820c8d2018-10-02 19:58:08 +00004549 pShmNode->hShm = -1;
drhd91c68f2010-05-14 14:52:25 +00004550 pDbFd->pInode->pShmNode = pShmNode;
4551 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004552 if( sqlite3GlobalConfig.bCoreMutex ){
drh24efa542018-10-02 19:36:40 +00004553 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4554 if( pShmNode->pShmMutex==0 ){
drh97a7e5e2016-04-26 18:58:54 +00004555 rc = SQLITE_NOMEM_BKPT;
4556 goto shm_open_err;
4557 }
drhd91c68f2010-05-14 14:52:25 +00004558 }
drhd9e5c4f2010-05-12 18:01:39 +00004559
drh3cb93392011-03-12 18:10:44 +00004560 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004561 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drh8820c8d2018-10-02 19:58:08 +00004562 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004563 }
drh8820c8d2018-10-02 19:58:08 +00004564 if( pShmNode->hShm<0 ){
4565 pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
4566 if( pShmNode->hShm<0 ){
danf12ba662017-11-07 15:43:52 +00004567 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4568 goto shm_open_err;
4569 }
4570 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004571 }
drhac7c3ac2012-02-11 19:23:48 +00004572
4573 /* If this process is running as root, make sure that the SHM file
4574 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004575 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004576 */
drh8820c8d2018-10-02 19:58:08 +00004577 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004578
dan92c02da2017-11-01 20:59:28 +00004579 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004580 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004581 }
drhd9e5c4f2010-05-12 18:01:39 +00004582 }
4583
drhd91c68f2010-05-14 14:52:25 +00004584 /* Make the new connection a child of the unixShmNode */
4585 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004586#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004587 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004588#endif
drhd91c68f2010-05-14 14:52:25 +00004589 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004590 pDbFd->pShm = p;
4591 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004592
4593 /* The reference count on pShmNode has already been incremented under
4594 ** the cover of the unixEnterMutex() mutex and the pointer from the
4595 ** new (struct unixShm) object to the pShmNode has been set. All that is
4596 ** left to do is to link the new object into the linked list starting
drh24efa542018-10-02 19:36:40 +00004597 ** at pShmNode->pFirst. This must be done while holding the
4598 ** pShmNode->pShmMutex.
dan0668f592010-07-20 18:59:00 +00004599 */
drh24efa542018-10-02 19:36:40 +00004600 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan0668f592010-07-20 18:59:00 +00004601 p->pNext = pShmNode->pFirst;
4602 pShmNode->pFirst = p;
drh24efa542018-10-02 19:36:40 +00004603 sqlite3_mutex_leave(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004604 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004605
4606 /* Jump here on any error */
4607shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004608 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004609 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004610 unixLeaveMutex();
4611 return rc;
4612}
4613
4614/*
danda9fe0c2010-07-13 18:44:03 +00004615** This function is called to obtain a pointer to region iRegion of the
4616** shared-memory associated with the database file fd. Shared-memory regions
4617** are numbered starting from zero. Each shared-memory region is szRegion
4618** bytes in size.
4619**
4620** If an error occurs, an error code is returned and *pp is set to NULL.
4621**
4622** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4623** region has not been allocated (by any client, including one running in a
4624** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4625** bExtend is non-zero and the requested shared-memory region has not yet
4626** been allocated, it is allocated by this function.
4627**
4628** If the shared-memory region has already been allocated or is allocated by
4629** this call as described above, then it is mapped into this processes
4630** address space (if it is not already), *pp is set to point to the mapped
4631** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004632*/
danda9fe0c2010-07-13 18:44:03 +00004633static int unixShmMap(
4634 sqlite3_file *fd, /* Handle open on database file */
4635 int iRegion, /* Region to retrieve */
4636 int szRegion, /* Size of regions */
4637 int bExtend, /* True to extend file if necessary */
4638 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004639){
danda9fe0c2010-07-13 18:44:03 +00004640 unixFile *pDbFd = (unixFile*)fd;
4641 unixShm *p;
4642 unixShmNode *pShmNode;
4643 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004644 int nShmPerMap = unixShmRegionPerMap();
4645 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004646
danda9fe0c2010-07-13 18:44:03 +00004647 /* If the shared-memory file has not yet been opened, open it now. */
4648 if( pDbFd->pShm==0 ){
4649 rc = unixOpenSharedMemory(pDbFd);
4650 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004651 }
drhd9e5c4f2010-05-12 18:01:39 +00004652
danda9fe0c2010-07-13 18:44:03 +00004653 p = pDbFd->pShm;
4654 pShmNode = p->pShmNode;
drh24efa542018-10-02 19:36:40 +00004655 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004656 if( pShmNode->isUnlocked ){
4657 rc = unixLockSharedMemory(pDbFd, pShmNode);
4658 if( rc!=SQLITE_OK ) goto shmpage_out;
4659 pShmNode->isUnlocked = 0;
4660 }
danda9fe0c2010-07-13 18:44:03 +00004661 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004662 assert( pShmNode->pInode==pDbFd->pInode );
drh8820c8d2018-10-02 19:58:08 +00004663 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4664 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004665
dan781e34c2014-03-20 08:59:47 +00004666 /* Minimum number of regions required to be mapped. */
4667 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4668
4669 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004670 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004671 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004672 struct stat sStat; /* Used by fstat() */
4673
4674 pShmNode->szRegion = szRegion;
4675
drh8820c8d2018-10-02 19:58:08 +00004676 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004677 /* The requested region is not mapped into this processes address space.
4678 ** Check to see if it has been allocated (i.e. if the wal-index file is
4679 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004680 */
drh8820c8d2018-10-02 19:58:08 +00004681 if( osFstat(pShmNode->hShm, &sStat) ){
drh3cb93392011-03-12 18:10:44 +00004682 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004683 goto shmpage_out;
4684 }
drh3cb93392011-03-12 18:10:44 +00004685
4686 if( sStat.st_size<nByte ){
4687 /* The requested memory region does not exist. If bExtend is set to
4688 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004689 */
dan47a2b4a2013-04-26 16:09:29 +00004690 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004691 goto shmpage_out;
4692 }
dan47a2b4a2013-04-26 16:09:29 +00004693
4694 /* Alternatively, if bExtend is true, extend the file. Do this by
4695 ** writing a single byte to the end of each (OS) page being
4696 ** allocated or extended. Technically, we need only write to the
4697 ** last page in order to extend the file. But writing to all new
4698 ** pages forces the OS to allocate them immediately, which reduces
4699 ** the chances of SIGBUS while accessing the mapped region later on.
4700 */
4701 else{
4702 static const int pgsz = 4096;
4703 int iPg;
4704
4705 /* Write to the last byte of each newly allocated or extended page */
4706 assert( (nByte % pgsz)==0 );
4707 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004708 int x = 0;
drh8820c8d2018-10-02 19:58:08 +00004709 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004710 const char *zFile = pShmNode->zFilename;
4711 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4712 goto shmpage_out;
4713 }
4714 }
drh3cb93392011-03-12 18:10:44 +00004715 }
4716 }
danda9fe0c2010-07-13 18:44:03 +00004717 }
4718
4719 /* Map the requested memory region into this processes address space. */
4720 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004721 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004722 );
4723 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004724 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004725 goto shmpage_out;
4726 }
4727 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004728 while( pShmNode->nRegion<nReqRegion ){
4729 int nMap = szRegion*nShmPerMap;
4730 int i;
drh3cb93392011-03-12 18:10:44 +00004731 void *pMem;
drh8820c8d2018-10-02 19:58:08 +00004732 if( pShmNode->hShm>=0 ){
dan781e34c2014-03-20 08:59:47 +00004733 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004734 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh8820c8d2018-10-02 19:58:08 +00004735 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004736 );
4737 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004738 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004739 goto shmpage_out;
4740 }
4741 }else{
drhb6c4d592018-10-11 02:39:11 +00004742 pMem = sqlite3_malloc64(nMap);
drh3cb93392011-03-12 18:10:44 +00004743 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004744 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004745 goto shmpage_out;
4746 }
drhb6c4d592018-10-11 02:39:11 +00004747 memset(pMem, 0, nMap);
danda9fe0c2010-07-13 18:44:03 +00004748 }
dan781e34c2014-03-20 08:59:47 +00004749
4750 for(i=0; i<nShmPerMap; i++){
4751 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4752 }
4753 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004754 }
4755 }
4756
4757shmpage_out:
4758 if( pShmNode->nRegion>iRegion ){
4759 *pp = pShmNode->apRegion[iRegion];
4760 }else{
4761 *pp = 0;
4762 }
drh66dfec8b2011-06-01 20:01:49 +00004763 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
drh24efa542018-10-02 19:36:40 +00004764 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004765 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004766}
4767
4768/*
drhd9e5c4f2010-05-12 18:01:39 +00004769** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004770**
4771** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4772** different here than in posix. In xShmLock(), one can go from unlocked
4773** to shared and back or from unlocked to exclusive and back. But one may
4774** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004775*/
4776static int unixShmLock(
4777 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004778 int ofst, /* First lock to acquire or release */
4779 int n, /* Number of locks to acquire or release */
4780 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004781){
drh73b64e42010-05-30 19:55:15 +00004782 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4783 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4784 unixShm *pX; /* For looping over all siblings */
4785 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4786 int rc = SQLITE_OK; /* Result code */
4787 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004788
drhd91c68f2010-05-14 14:52:25 +00004789 assert( pShmNode==pDbFd->pInode->pShmNode );
4790 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004791 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004792 assert( n>=1 );
4793 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4794 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4795 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4796 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4797 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh8820c8d2018-10-02 19:58:08 +00004798 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4799 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004800
drhc99597c2010-05-31 01:41:15 +00004801 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004802 assert( n>1 || mask==(1<<ofst) );
drh24efa542018-10-02 19:36:40 +00004803 sqlite3_mutex_enter(pShmNode->pShmMutex);
drh73b64e42010-05-30 19:55:15 +00004804 if( flags & SQLITE_SHM_UNLOCK ){
4805 u16 allMask = 0; /* Mask of locks held by siblings */
4806
4807 /* See if any siblings hold this same lock */
4808 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4809 if( pX==p ) continue;
4810 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4811 allMask |= pX->sharedMask;
4812 }
4813
4814 /* Unlock the system-level locks */
4815 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004816 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004817 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004818 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004819 }
drh73b64e42010-05-30 19:55:15 +00004820
4821 /* Undo the local locks */
4822 if( rc==SQLITE_OK ){
4823 p->exclMask &= ~mask;
4824 p->sharedMask &= ~mask;
4825 }
4826 }else if( flags & SQLITE_SHM_SHARED ){
4827 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4828
4829 /* Find out which shared locks are already held by sibling connections.
4830 ** If any sibling already holds an exclusive lock, go ahead and return
4831 ** SQLITE_BUSY.
4832 */
4833 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004834 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004835 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004836 break;
4837 }
4838 allShared |= pX->sharedMask;
4839 }
4840
4841 /* Get shared locks at the system level, if necessary */
4842 if( rc==SQLITE_OK ){
4843 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004844 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004845 }else{
drh73b64e42010-05-30 19:55:15 +00004846 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004847 }
drhd9e5c4f2010-05-12 18:01:39 +00004848 }
drh73b64e42010-05-30 19:55:15 +00004849
4850 /* Get the local shared locks */
4851 if( rc==SQLITE_OK ){
4852 p->sharedMask |= mask;
4853 }
4854 }else{
4855 /* Make sure no sibling connections hold locks that will block this
4856 ** lock. If any do, return SQLITE_BUSY right away.
4857 */
4858 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004859 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4860 rc = SQLITE_BUSY;
4861 break;
4862 }
4863 }
4864
4865 /* Get the exclusive locks at the system level. Then if successful
4866 ** also mark the local connection as being locked.
4867 */
4868 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004869 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004870 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004871 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004872 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004873 }
drhd9e5c4f2010-05-12 18:01:39 +00004874 }
4875 }
drh24efa542018-10-02 19:36:40 +00004876 sqlite3_mutex_leave(pShmNode->pShmMutex);
drh20e1f082010-05-31 16:10:12 +00004877 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004878 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004879 return rc;
4880}
4881
drh286a2882010-05-20 23:51:06 +00004882/*
4883** Implement a memory barrier or memory fence on shared memory.
4884**
4885** All loads and stores begun before the barrier must complete before
4886** any load or store begun after the barrier.
4887*/
4888static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004889 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004890){
drhff828942010-06-26 21:34:06 +00004891 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004892 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00004893 assert( fd->pMethods->xLock==nolockLock
4894 || unixFileMutexNotheld((unixFile*)fd)
4895 );
drh22c733d2015-09-24 12:40:43 +00004896 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004897 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004898}
4899
dan18801912010-06-14 14:07:50 +00004900/*
danda9fe0c2010-07-13 18:44:03 +00004901** Close a connection to shared-memory. Delete the underlying
4902** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004903**
4904** If there is no shared memory associated with the connection then this
4905** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004906*/
danda9fe0c2010-07-13 18:44:03 +00004907static int unixShmUnmap(
4908 sqlite3_file *fd, /* The underlying database file */
4909 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004910){
danda9fe0c2010-07-13 18:44:03 +00004911 unixShm *p; /* The connection to be closed */
4912 unixShmNode *pShmNode; /* The underlying shared-memory file */
4913 unixShm **pp; /* For looping over sibling connections */
4914 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004915
danda9fe0c2010-07-13 18:44:03 +00004916 pDbFd = (unixFile*)fd;
4917 p = pDbFd->pShm;
4918 if( p==0 ) return SQLITE_OK;
4919 pShmNode = p->pShmNode;
4920
4921 assert( pShmNode==pDbFd->pInode->pShmNode );
4922 assert( pShmNode->pInode==pDbFd->pInode );
4923
4924 /* Remove connection p from the set of connections associated
4925 ** with pShmNode */
drh24efa542018-10-02 19:36:40 +00004926 sqlite3_mutex_enter(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004927 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4928 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004929
danda9fe0c2010-07-13 18:44:03 +00004930 /* Free the connection p */
4931 sqlite3_free(p);
4932 pDbFd->pShm = 0;
drh24efa542018-10-02 19:36:40 +00004933 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004934
4935 /* If pShmNode->nRef has reached 0, then close the underlying
4936 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00004937 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00004938 unixEnterMutex();
4939 assert( pShmNode->nRef>0 );
4940 pShmNode->nRef--;
4941 if( pShmNode->nRef==0 ){
drh8820c8d2018-10-02 19:58:08 +00004942 if( deleteFlag && pShmNode->hShm>=0 ){
drh4bf66fd2015-02-19 02:43:02 +00004943 osUnlink(pShmNode->zFilename);
4944 }
danda9fe0c2010-07-13 18:44:03 +00004945 unixShmPurge(pDbFd);
4946 }
4947 unixLeaveMutex();
4948
4949 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004950}
drh286a2882010-05-20 23:51:06 +00004951
danda9fe0c2010-07-13 18:44:03 +00004952
drhd9e5c4f2010-05-12 18:01:39 +00004953#else
drh6b017cc2010-06-14 18:01:46 +00004954# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004955# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004956# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004957# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004958#endif /* #ifndef SQLITE_OMIT_WAL */
4959
mistachkine98844f2013-08-24 00:59:24 +00004960#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00004961/*
danaef49d72013-03-25 16:28:54 +00004962** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00004963*/
danf23da962013-03-23 21:00:41 +00004964static void unixUnmapfile(unixFile *pFd){
4965 assert( pFd->nFetchOut==0 );
4966 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00004967 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00004968 pFd->pMapRegion = 0;
4969 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00004970 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00004971 }
4972}
dan5d8a1372013-03-19 19:28:06 +00004973
danaef49d72013-03-25 16:28:54 +00004974/*
dane6ecd662013-04-01 17:56:59 +00004975** Attempt to set the size of the memory mapping maintained by file
4976** descriptor pFd to nNew bytes. Any existing mapping is discarded.
4977**
4978** If successful, this function sets the following variables:
4979**
4980** unixFile.pMapRegion
4981** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00004982** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00004983**
4984** If unsuccessful, an error message is logged via sqlite3_log() and
4985** the three variables above are zeroed. In this case SQLite should
4986** continue accessing the database using the xRead() and xWrite()
4987** methods.
4988*/
4989static void unixRemapfile(
4990 unixFile *pFd, /* File descriptor object */
4991 i64 nNew /* Required mapping size */
4992){
dan4ff7bc42013-04-02 12:04:09 +00004993 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00004994 int h = pFd->h; /* File descriptor open on db file */
4995 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00004996 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00004997 u8 *pNew = 0; /* Location of new mapping */
4998 int flags = PROT_READ; /* Flags to pass to mmap() */
4999
5000 assert( pFd->nFetchOut==0 );
5001 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00005002 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00005003 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00005004 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00005005 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00005006
danfe33e392015-11-17 20:56:06 +00005007#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005008 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005009#endif
dane6ecd662013-04-01 17:56:59 +00005010
5011 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005012#if HAVE_MREMAP
5013 i64 nReuse = pFd->mmapSize;
5014#else
danbc760632014-03-20 09:42:09 +00005015 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005016 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005017#endif
dane6ecd662013-04-01 17:56:59 +00005018 u8 *pReq = &pOrig[nReuse];
5019
5020 /* Unmap any pages of the existing mapping that cannot be reused. */
5021 if( nReuse!=nOrig ){
5022 osMunmap(pReq, nOrig-nReuse);
5023 }
5024
5025#if HAVE_MREMAP
5026 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005027 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005028#else
5029 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5030 if( pNew!=MAP_FAILED ){
5031 if( pNew!=pReq ){
5032 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005033 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005034 }else{
5035 pNew = pOrig;
5036 }
5037 }
5038#endif
5039
dan48ccef82013-04-02 20:55:01 +00005040 /* The attempt to extend the existing mapping failed. Free it. */
5041 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005042 osMunmap(pOrig, nReuse);
5043 }
5044 }
5045
5046 /* If pNew is still NULL, try to create an entirely new mapping. */
5047 if( pNew==0 ){
5048 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005049 }
5050
dan4ff7bc42013-04-02 12:04:09 +00005051 if( pNew==MAP_FAILED ){
5052 pNew = 0;
5053 nNew = 0;
5054 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5055
5056 /* If the mmap() above failed, assume that all subsequent mmap() calls
5057 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5058 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005059 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005060 }
dane6ecd662013-04-01 17:56:59 +00005061 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005062 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005063}
5064
5065/*
danaef49d72013-03-25 16:28:54 +00005066** Memory map or remap the file opened by file-descriptor pFd (if the file
5067** is already mapped, the existing mapping is replaced by the new). Or, if
5068** there already exists a mapping for this file, and there are still
5069** outstanding xFetch() references to it, this function is a no-op.
5070**
5071** If parameter nByte is non-negative, then it is the requested size of
5072** the mapping to create. Otherwise, if nByte is less than zero, then the
5073** requested size is the size of the file on disk. The actual size of the
5074** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005075** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005076**
5077** SQLITE_OK is returned if no error occurs (even if the mapping is not
5078** recreated as a result of outstanding references) or an SQLite error
5079** code otherwise.
5080*/
drhf3b1ed02015-12-02 13:11:03 +00005081static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005082 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005083 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005084 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5085
5086 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005087 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005088 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005089 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005090 }
drh3044b512014-06-16 16:41:52 +00005091 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005092 }
drh9b4c59f2013-04-15 17:03:42 +00005093 if( nMap>pFd->mmapSizeMax ){
5094 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005095 }
5096
drh333e6ca2015-12-02 15:44:39 +00005097 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005098 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005099 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005100 }
5101
danf23da962013-03-23 21:00:41 +00005102 return SQLITE_OK;
5103}
mistachkine98844f2013-08-24 00:59:24 +00005104#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005105
danaef49d72013-03-25 16:28:54 +00005106/*
5107** If possible, return a pointer to a mapping of file fd starting at offset
5108** iOff. The mapping must be valid for at least nAmt bytes.
5109**
5110** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5111** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5112** Finally, if an error does occur, return an SQLite error code. The final
5113** value of *pp is undefined in this case.
5114**
5115** If this function does return a pointer, the caller must eventually
5116** release the reference by calling unixUnfetch().
5117*/
danf23da962013-03-23 21:00:41 +00005118static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005119#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005120 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005121#endif
danf23da962013-03-23 21:00:41 +00005122 *pp = 0;
5123
drh9b4c59f2013-04-15 17:03:42 +00005124#if SQLITE_MAX_MMAP_SIZE>0
5125 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005126 if( pFd->pMapRegion==0 ){
5127 int rc = unixMapfile(pFd, -1);
5128 if( rc!=SQLITE_OK ) return rc;
5129 }
5130 if( pFd->mmapSize >= iOff+nAmt ){
5131 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5132 pFd->nFetchOut++;
5133 }
5134 }
drh6e0b6d52013-04-09 16:19:20 +00005135#endif
danf23da962013-03-23 21:00:41 +00005136 return SQLITE_OK;
5137}
5138
danaef49d72013-03-25 16:28:54 +00005139/*
dandf737fe2013-03-25 17:00:24 +00005140** If the third argument is non-NULL, then this function releases a
5141** reference obtained by an earlier call to unixFetch(). The second
5142** argument passed to this function must be the same as the corresponding
5143** argument that was passed to the unixFetch() invocation.
5144**
5145** Or, if the third argument is NULL, then this function is being called
5146** to inform the VFS layer that, according to POSIX, any existing mapping
5147** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005148*/
dandf737fe2013-03-25 17:00:24 +00005149static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005150#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005151 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005152 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005153
danaef49d72013-03-25 16:28:54 +00005154 /* If p==0 (unmap the entire file) then there must be no outstanding
5155 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5156 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005157 assert( (p==0)==(pFd->nFetchOut==0) );
5158
dandf737fe2013-03-25 17:00:24 +00005159 /* If p!=0, it must match the iOff value. */
5160 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5161
danf23da962013-03-23 21:00:41 +00005162 if( p ){
5163 pFd->nFetchOut--;
5164 }else{
5165 unixUnmapfile(pFd);
5166 }
5167
5168 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005169#else
5170 UNUSED_PARAMETER(fd);
5171 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005172 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005173#endif
danf23da962013-03-23 21:00:41 +00005174 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005175}
5176
5177/*
drh734c9862008-11-28 15:37:20 +00005178** Here ends the implementation of all sqlite3_file methods.
5179**
5180********************** End sqlite3_file Methods *******************************
5181******************************************************************************/
5182
5183/*
drh6b9d6dd2008-12-03 19:34:47 +00005184** This division contains definitions of sqlite3_io_methods objects that
5185** implement various file locking strategies. It also contains definitions
5186** of "finder" functions. A finder-function is used to locate the appropriate
5187** sqlite3_io_methods object for a particular database file. The pAppData
5188** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5189** the correct finder-function for that VFS.
5190**
5191** Most finder functions return a pointer to a fixed sqlite3_io_methods
5192** object. The only interesting finder-function is autolockIoFinder, which
5193** looks at the filesystem type and tries to guess the best locking
5194** strategy from that.
5195**
peter.d.reid60ec9142014-09-06 16:39:46 +00005196** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005197**
5198** (1) The real finder-function named "FImpt()".
5199**
dane946c392009-08-22 11:39:46 +00005200** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005201**
5202**
5203** A pointer to the F pointer is used as the pAppData value for VFS
5204** objects. We have to do this instead of letting pAppData point
5205** directly at the finder-function since C90 rules prevent a void*
5206** from be cast into a function pointer.
5207**
drh6b9d6dd2008-12-03 19:34:47 +00005208**
drh7708e972008-11-29 00:56:52 +00005209** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005210**
drh7708e972008-11-29 00:56:52 +00005211** * A constant sqlite3_io_methods object call METHOD that has locking
5212** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5213**
5214** * An I/O method finder function called FINDER that returns a pointer
5215** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005216*/
drhe6d41732015-02-21 00:49:00 +00005217#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005218static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005219 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005220 CLOSE, /* xClose */ \
5221 unixRead, /* xRead */ \
5222 unixWrite, /* xWrite */ \
5223 unixTruncate, /* xTruncate */ \
5224 unixSync, /* xSync */ \
5225 unixFileSize, /* xFileSize */ \
5226 LOCK, /* xLock */ \
5227 UNLOCK, /* xUnlock */ \
5228 CKLOCK, /* xCheckReservedLock */ \
5229 unixFileControl, /* xFileControl */ \
5230 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005231 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005232 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005233 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005234 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005235 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005236 unixFetch, /* xFetch */ \
5237 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005238}; \
drh0c2694b2009-09-03 16:23:44 +00005239static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5240 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005241 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005242} \
drh0c2694b2009-09-03 16:23:44 +00005243static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005244 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005245
5246/*
5247** Here are all of the sqlite3_io_methods objects for each of the
5248** locking strategies. Functions that return pointers to these methods
5249** are also created.
5250*/
5251IOMETHODS(
5252 posixIoFinder, /* Finder function name */
5253 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005254 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005255 unixClose, /* xClose method */
5256 unixLock, /* xLock method */
5257 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005258 unixCheckReservedLock, /* xCheckReservedLock method */
5259 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005260)
drh7708e972008-11-29 00:56:52 +00005261IOMETHODS(
5262 nolockIoFinder, /* Finder function name */
5263 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005264 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005265 nolockClose, /* xClose method */
5266 nolockLock, /* xLock method */
5267 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005268 nolockCheckReservedLock, /* xCheckReservedLock method */
5269 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005270)
drh7708e972008-11-29 00:56:52 +00005271IOMETHODS(
5272 dotlockIoFinder, /* Finder function name */
5273 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005274 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005275 dotlockClose, /* xClose method */
5276 dotlockLock, /* xLock method */
5277 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005278 dotlockCheckReservedLock, /* xCheckReservedLock method */
5279 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005280)
drh7708e972008-11-29 00:56:52 +00005281
drhe89b2912015-03-03 20:42:01 +00005282#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005283IOMETHODS(
5284 flockIoFinder, /* Finder function name */
5285 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005286 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005287 flockClose, /* xClose method */
5288 flockLock, /* xLock method */
5289 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005290 flockCheckReservedLock, /* xCheckReservedLock method */
5291 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005292)
drh7708e972008-11-29 00:56:52 +00005293#endif
5294
drh6c7d5c52008-11-21 20:32:33 +00005295#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005296IOMETHODS(
5297 semIoFinder, /* Finder function name */
5298 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005299 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005300 semXClose, /* xClose method */
5301 semXLock, /* xLock method */
5302 semXUnlock, /* xUnlock method */
5303 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005304 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005305)
aswiftaebf4132008-11-21 00:10:35 +00005306#endif
drh7708e972008-11-29 00:56:52 +00005307
drhd2cb50b2009-01-09 21:41:17 +00005308#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005309IOMETHODS(
5310 afpIoFinder, /* Finder function name */
5311 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005312 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005313 afpClose, /* xClose method */
5314 afpLock, /* xLock method */
5315 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005316 afpCheckReservedLock, /* xCheckReservedLock method */
5317 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005318)
drh715ff302008-12-03 22:32:44 +00005319#endif
5320
5321/*
5322** The proxy locking method is a "super-method" in the sense that it
5323** opens secondary file descriptors for the conch and lock files and
5324** it uses proxy, dot-file, AFP, and flock() locking methods on those
5325** secondary files. For this reason, the division that implements
5326** proxy locking is located much further down in the file. But we need
5327** to go ahead and define the sqlite3_io_methods and finder function
5328** for proxy locking here. So we forward declare the I/O methods.
5329*/
drhd2cb50b2009-01-09 21:41:17 +00005330#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005331static int proxyClose(sqlite3_file*);
5332static int proxyLock(sqlite3_file*, int);
5333static int proxyUnlock(sqlite3_file*, int);
5334static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005335IOMETHODS(
5336 proxyIoFinder, /* Finder function name */
5337 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005338 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005339 proxyClose, /* xClose method */
5340 proxyLock, /* xLock method */
5341 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005342 proxyCheckReservedLock, /* xCheckReservedLock method */
5343 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005344)
aswiftaebf4132008-11-21 00:10:35 +00005345#endif
drh7708e972008-11-29 00:56:52 +00005346
drh7ed97b92010-01-20 13:07:21 +00005347/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5348#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5349IOMETHODS(
5350 nfsIoFinder, /* Finder function name */
5351 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005352 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005353 unixClose, /* xClose method */
5354 unixLock, /* xLock method */
5355 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005356 unixCheckReservedLock, /* xCheckReservedLock method */
5357 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005358)
5359#endif
drh7708e972008-11-29 00:56:52 +00005360
drhd2cb50b2009-01-09 21:41:17 +00005361#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005362/*
drh6b9d6dd2008-12-03 19:34:47 +00005363** This "finder" function attempts to determine the best locking strategy
5364** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005365** object that implements that strategy.
5366**
5367** This is for MacOSX only.
5368*/
drh1875f7a2008-12-08 18:19:17 +00005369static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005370 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005371 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005372){
5373 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005374 const char *zFilesystem; /* Filesystem type name */
5375 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005376 } aMap[] = {
5377 { "hfs", &posixIoMethods },
5378 { "ufs", &posixIoMethods },
5379 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005380 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005381 { "webdav", &nolockIoMethods },
5382 { 0, 0 }
5383 };
5384 int i;
5385 struct statfs fsInfo;
5386 struct flock lockInfo;
5387
5388 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005389 /* If filePath==NULL that means we are dealing with a transient file
5390 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005391 return &nolockIoMethods;
5392 }
5393 if( statfs(filePath, &fsInfo) != -1 ){
5394 if( fsInfo.f_flags & MNT_RDONLY ){
5395 return &nolockIoMethods;
5396 }
5397 for(i=0; aMap[i].zFilesystem; i++){
5398 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5399 return aMap[i].pMethods;
5400 }
5401 }
5402 }
5403
5404 /* Default case. Handles, amongst others, "nfs".
5405 ** Test byte-range lock using fcntl(). If the call succeeds,
5406 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005407 */
drh7708e972008-11-29 00:56:52 +00005408 lockInfo.l_len = 1;
5409 lockInfo.l_start = 0;
5410 lockInfo.l_whence = SEEK_SET;
5411 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005412 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005413 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5414 return &nfsIoMethods;
5415 } else {
5416 return &posixIoMethods;
5417 }
drh7708e972008-11-29 00:56:52 +00005418 }else{
5419 return &dotlockIoMethods;
5420 }
5421}
drh0c2694b2009-09-03 16:23:44 +00005422static const sqlite3_io_methods
5423 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005424
drhd2cb50b2009-01-09 21:41:17 +00005425#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005426
drhe89b2912015-03-03 20:42:01 +00005427#if OS_VXWORKS
5428/*
5429** This "finder" function for VxWorks checks to see if posix advisory
5430** locking works. If it does, then that is what is used. If it does not
5431** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005432*/
drhe89b2912015-03-03 20:42:01 +00005433static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005434 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005435 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005436){
5437 struct flock lockInfo;
5438
5439 if( !filePath ){
5440 /* If filePath==NULL that means we are dealing with a transient file
5441 ** that does not need to be locked. */
5442 return &nolockIoMethods;
5443 }
5444
5445 /* Test if fcntl() is supported and use POSIX style locks.
5446 ** Otherwise fall back to the named semaphore method.
5447 */
5448 lockInfo.l_len = 1;
5449 lockInfo.l_start = 0;
5450 lockInfo.l_whence = SEEK_SET;
5451 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005452 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005453 return &posixIoMethods;
5454 }else{
5455 return &semIoMethods;
5456 }
5457}
drh0c2694b2009-09-03 16:23:44 +00005458static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005459 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005460
drhe89b2912015-03-03 20:42:01 +00005461#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005462
drh7708e972008-11-29 00:56:52 +00005463/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005464** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005465*/
drh0c2694b2009-09-03 16:23:44 +00005466typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005467
aswiftaebf4132008-11-21 00:10:35 +00005468
drh734c9862008-11-28 15:37:20 +00005469/****************************************************************************
5470**************************** sqlite3_vfs methods ****************************
5471**
5472** This division contains the implementation of methods on the
5473** sqlite3_vfs object.
5474*/
5475
danielk1977a3d4c882007-03-23 10:08:38 +00005476/*
danielk1977e339d652008-06-28 11:23:00 +00005477** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005478*/
5479static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005480 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005481 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005482 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005483 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005484 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005485){
drh7708e972008-11-29 00:56:52 +00005486 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005487 unixFile *pNew = (unixFile *)pId;
5488 int rc = SQLITE_OK;
5489
drh8af6c222010-05-14 12:43:01 +00005490 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005491
drhb07028f2011-10-14 21:49:18 +00005492 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005493 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005494
drh308c2a52010-05-14 11:30:18 +00005495 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005496 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005497 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005498 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005499 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005500#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005501 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005502#endif
drhc02a43a2012-01-10 23:18:38 +00005503 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5504 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005505 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005506 }
drh503a6862013-03-01 01:07:17 +00005507 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005508 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005509 }
drh339eb0b2008-03-07 15:34:11 +00005510
drh6c7d5c52008-11-21 20:32:33 +00005511#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005512 pNew->pId = vxworksFindFileId(zFilename);
5513 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005514 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005515 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005516 }
5517#endif
5518
drhc02a43a2012-01-10 23:18:38 +00005519 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005520 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005521 }else{
drh0c2694b2009-09-03 16:23:44 +00005522 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005523#if SQLITE_ENABLE_LOCKING_STYLE
5524 /* Cache zFilename in the locking context (AFP and dotlock override) for
5525 ** proxyLock activation is possible (remote proxy is based on db name)
5526 ** zFilename remains valid until file is closed, to support */
5527 pNew->lockingContext = (void*)zFilename;
5528#endif
drhda0e7682008-07-30 15:27:54 +00005529 }
danielk1977e339d652008-06-28 11:23:00 +00005530
drh7ed97b92010-01-20 13:07:21 +00005531 if( pLockingStyle == &posixIoMethods
5532#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5533 || pLockingStyle == &nfsIoMethods
5534#endif
5535 ){
drh7708e972008-11-29 00:56:52 +00005536 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005537 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005538 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005539 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005540 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005541 ** in two scenarios:
5542 **
5543 ** (a) A call to fstat() failed.
5544 ** (b) A malloc failed.
5545 **
5546 ** Scenario (b) may only occur if the process is holding no other
5547 ** file descriptors open on the same file. If there were other file
5548 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005549 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005550 ** handle h - as it is guaranteed that no posix locks will be released
5551 ** by doing so.
5552 **
5553 ** If scenario (a) caused the error then things are not so safe. The
5554 ** implicit assumption here is that if fstat() fails, things are in
5555 ** such bad shape that dropping a lock or two doesn't matter much.
5556 */
drh0e9365c2011-03-02 02:08:13 +00005557 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005558 h = -1;
5559 }
drh7708e972008-11-29 00:56:52 +00005560 unixLeaveMutex();
5561 }
danielk1977e339d652008-06-28 11:23:00 +00005562
drhd2cb50b2009-01-09 21:41:17 +00005563#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005564 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005565 /* AFP locking uses the file path so it needs to be included in
5566 ** the afpLockingContext.
5567 */
5568 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005569 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005570 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005571 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005572 }else{
5573 /* NB: zFilename exists and remains valid until the file is closed
5574 ** according to requirement F11141. So we do not need to make a
5575 ** copy of the filename. */
5576 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005577 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005578 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005579 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005580 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005581 if( rc!=SQLITE_OK ){
5582 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005583 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005584 h = -1;
5585 }
drh7708e972008-11-29 00:56:52 +00005586 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005587 }
drh7708e972008-11-29 00:56:52 +00005588 }
5589#endif
danielk1977e339d652008-06-28 11:23:00 +00005590
drh7708e972008-11-29 00:56:52 +00005591 else if( pLockingStyle == &dotlockIoMethods ){
5592 /* Dotfile locking uses the file path so it needs to be included in
5593 ** the dotlockLockingContext
5594 */
5595 char *zLockFile;
5596 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005597 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005598 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005599 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005600 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005601 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005602 }else{
5603 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005604 }
drh7708e972008-11-29 00:56:52 +00005605 pNew->lockingContext = zLockFile;
5606 }
danielk1977e339d652008-06-28 11:23:00 +00005607
drh6c7d5c52008-11-21 20:32:33 +00005608#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005609 else if( pLockingStyle == &semIoMethods ){
5610 /* Named semaphore locking uses the file path so it needs to be
5611 ** included in the semLockingContext
5612 */
5613 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005614 rc = findInodeInfo(pNew, &pNew->pInode);
5615 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5616 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005617 int n;
drh2238dcc2009-08-27 17:56:20 +00005618 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005619 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005620 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005621 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005622 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5623 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005624 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005625 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005626 }
chw97185482008-11-17 08:05:31 +00005627 }
drh7708e972008-11-29 00:56:52 +00005628 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005629 }
drh7708e972008-11-29 00:56:52 +00005630#endif
aswift5b1a2562008-08-22 00:22:35 +00005631
drh4bf66fd2015-02-19 02:43:02 +00005632 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005633#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005634 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005635 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005636 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005637 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005638 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005639 }
chw97185482008-11-17 08:05:31 +00005640#endif
danielk1977e339d652008-06-28 11:23:00 +00005641 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005642 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005643 }else{
drh7708e972008-11-29 00:56:52 +00005644 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005645 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005646 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005647 }
danielk1977e339d652008-06-28 11:23:00 +00005648 return rc;
drh054889e2005-11-30 03:20:31 +00005649}
drh9c06c952005-11-26 00:25:00 +00005650
danielk1977ad94b582007-08-20 06:44:22 +00005651/*
drh8b3cf822010-06-01 21:02:51 +00005652** Return the name of a directory in which to put temporary files.
5653** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005654*/
drh7234c6d2010-06-19 15:10:09 +00005655static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005656 static const char *azDirs[] = {
5657 0,
aswiftaebf4132008-11-21 00:10:35 +00005658 0,
danielk197717b90b52008-06-06 11:11:25 +00005659 "/var/tmp",
5660 "/usr/tmp",
5661 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005662 "."
danielk197717b90b52008-06-06 11:11:25 +00005663 };
drh2aab11f2016-04-29 20:30:56 +00005664 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005665 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005666 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005667
drhb7e50ad2015-11-28 21:49:53 +00005668 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5669 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005670 while(1){
5671 if( zDir!=0
5672 && osStat(zDir, &buf)==0
5673 && S_ISDIR(buf.st_mode)
5674 && osAccess(zDir, 03)==0
5675 ){
5676 return zDir;
5677 }
5678 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5679 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005680 }
drh7694e062016-04-21 23:37:24 +00005681 return 0;
drh8b3cf822010-06-01 21:02:51 +00005682}
5683
5684/*
5685** Create a temporary file name in zBuf. zBuf must be allocated
5686** by the calling process and must be big enough to hold at least
5687** pVfs->mxPathname bytes.
5688*/
5689static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005690 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005691 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005692
5693 /* It's odd to simulate an io-error here, but really this is just
5694 ** using the io-error infrastructure to test that SQLite handles this
5695 ** function failing.
5696 */
drh7694e062016-04-21 23:37:24 +00005697 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005698 SimulateIOError( return SQLITE_IOERR );
5699
drh7234c6d2010-06-19 15:10:09 +00005700 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005701 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005702 do{
drh970942e2015-11-25 23:13:14 +00005703 u64 r;
5704 sqlite3_randomness(sizeof(r), &r);
5705 assert( nBuf>2 );
5706 zBuf[nBuf-2] = 0;
5707 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5708 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005709 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005710 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005711 return SQLITE_OK;
5712}
5713
drhd2cb50b2009-01-09 21:41:17 +00005714#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005715/*
5716** Routine to transform a unixFile into a proxy-locking unixFile.
5717** Implementation in the proxy-lock division, but used by unixOpen()
5718** if SQLITE_PREFER_PROXY_LOCKING is defined.
5719*/
5720static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005721#endif
drhc66d5b62008-12-03 22:48:32 +00005722
dan08da86a2009-08-21 17:18:03 +00005723/*
5724** Search for an unused file descriptor that was opened on the database
5725** file (not a journal or master-journal file) identified by pathname
5726** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5727** argument to this function.
5728**
5729** Such a file descriptor may exist if a database connection was closed
5730** but the associated file descriptor could not be closed because some
5731** other file descriptor open on the same file is holding a file-lock.
5732** Refer to comments in the unixClose() function and the lengthy comment
5733** describing "Posix Advisory Locking" at the start of this file for
5734** further details. Also, ticket #4018.
5735**
5736** If a suitable file descriptor is found, then it is returned. If no
5737** such file descriptor is located, -1 is returned.
5738*/
dane946c392009-08-22 11:39:46 +00005739static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5740 UnixUnusedFd *pUnused = 0;
5741
5742 /* Do not search for an unused file descriptor on vxworks. Not because
5743 ** vxworks would not benefit from the change (it might, we're not sure),
5744 ** but because no way to test it is currently available. It is better
5745 ** not to risk breaking vxworks support for the sake of such an obscure
5746 ** feature. */
5747#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005748 struct stat sStat; /* Results of stat() call */
5749
drhc68886b2017-08-18 16:09:52 +00005750 unixEnterMutex();
5751
dan08da86a2009-08-21 17:18:03 +00005752 /* A stat() call may fail for various reasons. If this happens, it is
5753 ** almost certain that an open() call on the same path will also fail.
5754 ** For this reason, if an error occurs in the stat() call here, it is
5755 ** ignored and -1 is returned. The caller will try to open a new file
5756 ** descriptor on the same path, fail, and return an error to SQLite.
5757 **
5758 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005759 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005760 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005761 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005762
drh8af6c222010-05-14 12:43:01 +00005763 pInode = inodeList;
5764 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005765 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005766 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005767 }
drh8af6c222010-05-14 12:43:01 +00005768 if( pInode ){
dane946c392009-08-22 11:39:46 +00005769 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005770 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5771 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00005772 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005773 pUnused = *pp;
5774 if( pUnused ){
5775 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005776 }
drh095908e2018-08-13 20:46:18 +00005777 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005778 }
dan08da86a2009-08-21 17:18:03 +00005779 }
drhc68886b2017-08-18 16:09:52 +00005780 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005781#endif /* if !OS_VXWORKS */
5782 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005783}
danielk197717b90b52008-06-06 11:11:25 +00005784
5785/*
dan1bf4ca72016-08-11 18:05:47 +00005786** Find the mode, uid and gid of file zFile.
5787*/
5788static int getFileMode(
5789 const char *zFile, /* File name */
5790 mode_t *pMode, /* OUT: Permissions of zFile */
5791 uid_t *pUid, /* OUT: uid of zFile. */
5792 gid_t *pGid /* OUT: gid of zFile. */
5793){
5794 struct stat sStat; /* Output of stat() on database file */
5795 int rc = SQLITE_OK;
5796 if( 0==osStat(zFile, &sStat) ){
5797 *pMode = sStat.st_mode & 0777;
5798 *pUid = sStat.st_uid;
5799 *pGid = sStat.st_gid;
5800 }else{
5801 rc = SQLITE_IOERR_FSTAT;
5802 }
5803 return rc;
5804}
5805
5806/*
danddb0ac42010-07-14 14:48:58 +00005807** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005808** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005809** and a value suitable for passing as the third argument to open(2) is
5810** written to *pMode. If an IO error occurs, an SQLite error code is
5811** returned and the value of *pMode is not modified.
5812**
peter.d.reid60ec9142014-09-06 16:39:46 +00005813** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005814** an indication to robust_open() to create the file using
5815** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5816** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005817** this function queries the file-system for the permissions on the
5818** corresponding database file and sets *pMode to this value. Whenever
5819** possible, WAL and journal files are created using the same permissions
5820** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005821**
5822** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5823** original filename is unavailable. But 8_3_NAMES is only used for
5824** FAT filesystems and permissions do not matter there, so just use
5825** the default permissions.
danddb0ac42010-07-14 14:48:58 +00005826*/
5827static int findCreateFileMode(
5828 const char *zPath, /* Path of file (possibly) being created */
5829 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005830 mode_t *pMode, /* OUT: Permissions to open file with */
5831 uid_t *pUid, /* OUT: uid to set on the file */
5832 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005833){
5834 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005835 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005836 *pUid = 0;
5837 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005838 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005839 char zDb[MAX_PATHNAME+1]; /* Database file path */
5840 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005841
dana0c989d2010-11-05 18:07:37 +00005842 /* zPath is a path to a WAL or journal file. The following block derives
5843 ** the path to the associated database file from zPath. This block handles
5844 ** the following naming conventions:
5845 **
5846 ** "<path to db>-journal"
5847 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005848 ** "<path to db>-journalNN"
5849 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005850 **
drhd337c5b2011-10-20 18:23:35 +00005851 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005852 ** used by the test_multiplex.c module.
5853 */
5854 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005855 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005856 /* In normal operation, the journal file name will always contain
5857 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5858 ** rollback journal specifies a master journal with a goofy name, then
5859 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005860 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005861 nDb--;
5862 }
danddb0ac42010-07-14 14:48:58 +00005863 memcpy(zDb, zPath, nDb);
5864 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005865
dan1bf4ca72016-08-11 18:05:47 +00005866 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005867 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5868 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005869 }else if( flags & SQLITE_OPEN_URI ){
5870 /* If this is a main database file and the file was opened using a URI
5871 ** filename, check for the "modeof" parameter. If present, interpret
5872 ** its value as a filename and try to copy the mode, uid and gid from
5873 ** that file. */
5874 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5875 if( z ){
5876 rc = getFileMode(z, pMode, pUid, pGid);
5877 }
danddb0ac42010-07-14 14:48:58 +00005878 }
5879 return rc;
5880}
5881
5882/*
danielk1977ad94b582007-08-20 06:44:22 +00005883** Open the file zPath.
5884**
danielk1977b4b47412007-08-17 15:53:36 +00005885** Previously, the SQLite OS layer used three functions in place of this
5886** one:
5887**
5888** sqlite3OsOpenReadWrite();
5889** sqlite3OsOpenReadOnly();
5890** sqlite3OsOpenExclusive();
5891**
5892** These calls correspond to the following combinations of flags:
5893**
5894** ReadWrite() -> (READWRITE | CREATE)
5895** ReadOnly() -> (READONLY)
5896** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5897**
5898** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5899** true, the file was configured to be automatically deleted when the
5900** file handle closed. To achieve the same effect using this new
5901** interface, add the DELETEONCLOSE flag to those specified above for
5902** OpenExclusive().
5903*/
5904static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005905 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5906 const char *zPath, /* Pathname of file to be opened */
5907 sqlite3_file *pFile, /* The file descriptor to be filled in */
5908 int flags, /* Input flags to control the opening */
5909 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005910){
dan08da86a2009-08-21 17:18:03 +00005911 unixFile *p = (unixFile *)pFile;
5912 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005913 int openFlags = 0; /* Flags to pass to open() */
danielk1977fee2d252007-08-18 10:59:19 +00005914 int eType = flags&0xFFFFFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005915 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005916 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005917 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005918
5919 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5920 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5921 int isCreate = (flags & SQLITE_OPEN_CREATE);
5922 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5923 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005924#if SQLITE_ENABLE_LOCKING_STYLE
5925 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5926#endif
drh3d4435b2011-08-26 20:55:50 +00005927#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5928 struct statfs fsInfo;
5929#endif
danielk1977b4b47412007-08-17 15:53:36 +00005930
danielk1977fee2d252007-08-18 10:59:19 +00005931 /* If creating a master or main-file journal, this function will open
5932 ** a file-descriptor on the directory too. The first time unixSync()
5933 ** is called the directory file descriptor will be fsync()ed and close()d.
5934 */
drha803a2c2017-12-13 20:02:29 +00005935 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005936 eType==SQLITE_OPEN_MASTER_JOURNAL
5937 || eType==SQLITE_OPEN_MAIN_JOURNAL
5938 || eType==SQLITE_OPEN_WAL
5939 ));
danielk1977fee2d252007-08-18 10:59:19 +00005940
danielk197717b90b52008-06-06 11:11:25 +00005941 /* If argument zPath is a NULL pointer, this function is required to open
5942 ** a temporary file. Use this buffer to store the file name in.
5943 */
drhc02a43a2012-01-10 23:18:38 +00005944 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005945 const char *zName = zPath;
5946
danielk1977fee2d252007-08-18 10:59:19 +00005947 /* Check the following statements are true:
5948 **
5949 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5950 ** (b) if CREATE is set, then READWRITE must also be set, and
5951 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005952 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005953 */
danielk1977b4b47412007-08-17 15:53:36 +00005954 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005955 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005956 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005957 assert(isDelete==0 || isCreate);
5958
danddb0ac42010-07-14 14:48:58 +00005959 /* The main DB, main journal, WAL file and master journal are never
5960 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00005961 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
5962 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
5963 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00005964 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00005965
danielk1977fee2d252007-08-18 10:59:19 +00005966 /* Assert that the upper layer has set one of the "file-type" flags. */
5967 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
5968 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
5969 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00005970 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00005971 );
5972
drhb00d8622014-01-01 15:18:36 +00005973 /* Detect a pid change and reset the PRNG. There is a race condition
5974 ** here such that two or more threads all trying to open databases at
5975 ** the same instant might all reset the PRNG. But multiple resets
5976 ** are harmless.
5977 */
drh5ac93652015-03-21 20:59:43 +00005978 if( randomnessPid!=osGetpid(0) ){
5979 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00005980 sqlite3_randomness(0,0);
5981 }
dan08da86a2009-08-21 17:18:03 +00005982 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00005983
dan08da86a2009-08-21 17:18:03 +00005984 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00005985 UnixUnusedFd *pUnused;
5986 pUnused = findReusableFd(zName, flags);
5987 if( pUnused ){
5988 fd = pUnused->fd;
5989 }else{
drhf3cdcdc2015-04-29 16:50:28 +00005990 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00005991 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00005992 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00005993 }
5994 }
drhc68886b2017-08-18 16:09:52 +00005995 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00005996
5997 /* Database filenames are double-zero terminated if they are not
5998 ** URIs with parameters. Hence, they can always be passed into
5999 ** sqlite3_uri_parameter(). */
6000 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6001
dan08da86a2009-08-21 17:18:03 +00006002 }else if( !zName ){
6003 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00006004 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00006005 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00006006 if( rc!=SQLITE_OK ){
6007 return rc;
6008 }
6009 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006010
6011 /* Generated temporary filenames are always double-zero terminated
6012 ** for use by sqlite3_uri_parameter(). */
6013 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006014 }
6015
dan08da86a2009-08-21 17:18:03 +00006016 /* Determine the value of the flags parameter passed to POSIX function
6017 ** open(). These must be calculated even if open() is not called, as
6018 ** they may be stored as part of the file handle and used by the
6019 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006020 if( isReadonly ) openFlags |= O_RDONLY;
6021 if( isReadWrite ) openFlags |= O_RDWR;
6022 if( isCreate ) openFlags |= O_CREAT;
6023 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
6024 openFlags |= (O_LARGEFILE|O_BINARY);
danielk1977b4b47412007-08-17 15:53:36 +00006025
danielk1977b4b47412007-08-17 15:53:36 +00006026 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006027 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006028 uid_t uid; /* Userid for the file */
6029 gid_t gid; /* Groupid for the file */
6030 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006031 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006032 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006033 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006034 return rc;
6035 }
drhad4f1e52011-03-04 15:43:57 +00006036 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006037 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006038 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006039 if( fd<0 ){
6040 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6041 /* If unable to create a journal because the directory is not
6042 ** writable, change the error code to indicate that. */
6043 rc = SQLITE_READONLY_DIRECTORY;
6044 }else if( errno!=EISDIR && isReadWrite ){
6045 /* Failed to open the file for read/write access. Try read-only. */
6046 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6047 openFlags &= ~(O_RDWR|O_CREAT);
6048 flags |= SQLITE_OPEN_READONLY;
6049 openFlags |= O_RDONLY;
6050 isReadonly = 1;
6051 fd = robust_open(zName, openFlags, openMode);
6052 }
dan08da86a2009-08-21 17:18:03 +00006053 }
6054 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006055 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6056 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006057 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006058 }
drhac7c3ac2012-02-11 19:23:48 +00006059
6060 /* If this process is running as root and if creating a new rollback
6061 ** journal or WAL file, set the ownership of the journal or WAL to be
drhed466822012-05-31 13:10:49 +00006062 ** the same as the original database.
drhac7c3ac2012-02-11 19:23:48 +00006063 */
6064 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
drh6226ca22015-11-24 15:06:28 +00006065 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006066 }
danielk1977b4b47412007-08-17 15:53:36 +00006067 }
dan08da86a2009-08-21 17:18:03 +00006068 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006069 if( pOutFlags ){
6070 *pOutFlags = flags;
6071 }
6072
drhc68886b2017-08-18 16:09:52 +00006073 if( p->pPreallocatedUnused ){
6074 p->pPreallocatedUnused->fd = fd;
6075 p->pPreallocatedUnused->flags = flags;
dane946c392009-08-22 11:39:46 +00006076 }
6077
danielk1977b4b47412007-08-17 15:53:36 +00006078 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006079#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006080 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006081#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6082 zPath = sqlite3_mprintf("%s", zName);
6083 if( zPath==0 ){
6084 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006085 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006086 }
chw97185482008-11-17 08:05:31 +00006087#else
drh036ac7f2011-08-08 23:18:05 +00006088 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006089#endif
danielk1977b4b47412007-08-17 15:53:36 +00006090 }
drh41022642008-11-21 00:24:42 +00006091#if SQLITE_ENABLE_LOCKING_STYLE
6092 else{
dan08da86a2009-08-21 17:18:03 +00006093 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006094 }
6095#endif
drh7ed97b92010-01-20 13:07:21 +00006096
6097#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006098 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006099 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006100 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006101 return SQLITE_IOERR_ACCESS;
6102 }
6103 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6104 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6105 }
drh4bf66fd2015-02-19 02:43:02 +00006106 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6107 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6108 }
drh7ed97b92010-01-20 13:07:21 +00006109#endif
drhc02a43a2012-01-10 23:18:38 +00006110
6111 /* Set up appropriate ctrlFlags */
6112 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6113 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006114 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006115 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006116 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006117 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6118
drh7ed97b92010-01-20 13:07:21 +00006119#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006120#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006121 isAutoProxy = 1;
6122#endif
6123 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006124 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6125 int useProxy = 0;
6126
dan08da86a2009-08-21 17:18:03 +00006127 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6128 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006129 if( envforce!=NULL ){
6130 useProxy = atoi(envforce)>0;
6131 }else{
aswiftaebf4132008-11-21 00:10:35 +00006132 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6133 }
6134 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006135 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006136 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006137 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006138 if( rc!=SQLITE_OK ){
6139 /* Use unixClose to clean up the resources added in fillInUnixFile
6140 ** and clear all the structure's references. Specifically,
6141 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6142 */
6143 unixClose(pFile);
6144 return rc;
6145 }
aswiftaebf4132008-11-21 00:10:35 +00006146 }
dane946c392009-08-22 11:39:46 +00006147 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006148 }
6149 }
6150#endif
6151
dan3ed0f1c2017-09-14 21:12:07 +00006152 assert( zPath==0 || zPath[0]=='/'
6153 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6154 );
drhc02a43a2012-01-10 23:18:38 +00006155 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6156
dane946c392009-08-22 11:39:46 +00006157open_finished:
6158 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006159 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006160 }
6161 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006162}
6163
dane946c392009-08-22 11:39:46 +00006164
danielk1977b4b47412007-08-17 15:53:36 +00006165/*
danielk1977fee2d252007-08-18 10:59:19 +00006166** Delete the file at zPath. If the dirSync argument is true, fsync()
6167** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006168*/
drh6b9d6dd2008-12-03 19:34:47 +00006169static int unixDelete(
6170 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6171 const char *zPath, /* Name of file to be deleted */
6172 int dirSync /* If true, fsync() directory after deleting file */
6173){
danielk1977fee2d252007-08-18 10:59:19 +00006174 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006175 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006176 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006177 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006178 if( errno==ENOENT
6179#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006180 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006181#endif
6182 ){
dan9fc5b4a2012-11-09 20:17:26 +00006183 rc = SQLITE_IOERR_DELETE_NOENT;
6184 }else{
drhb4308162012-11-09 21:40:02 +00006185 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006186 }
drhb4308162012-11-09 21:40:02 +00006187 return rc;
drh5d4feff2010-07-14 01:45:22 +00006188 }
danielk1977d39fa702008-10-16 13:27:40 +00006189#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006190 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006191 int fd;
drh90315a22011-08-10 01:52:12 +00006192 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006193 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006194 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006195 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006196 }
drh0e9365c2011-03-02 02:08:13 +00006197 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006198 }else{
6199 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006200 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006201 }
6202 }
danielk1977d138dd82008-10-15 16:02:48 +00006203#endif
danielk1977fee2d252007-08-18 10:59:19 +00006204 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006205}
6206
danielk197790949c22007-08-17 16:50:38 +00006207/*
mistachkin48864df2013-03-21 21:20:32 +00006208** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006209** test performed depends on the value of flags:
6210**
6211** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6212** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6213** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6214**
6215** Otherwise return 0.
6216*/
danielk1977861f7452008-06-05 11:39:11 +00006217static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006218 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6219 const char *zPath, /* Path of the file to examine */
6220 int flags, /* What do we want to learn about the zPath file? */
6221 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006222){
danielk1977397d65f2008-11-19 11:35:39 +00006223 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006224 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006225 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006226
drhd260b5b2015-11-25 18:03:33 +00006227 /* The spec says there are three possible values for flags. But only
6228 ** two of them are actually used */
6229 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
6230
6231 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006232 struct stat buf;
drhd260b5b2015-11-25 18:03:33 +00006233 *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
6234 }else{
6235 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006236 }
danielk1977861f7452008-06-05 11:39:11 +00006237 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006238}
6239
danielk1977b4b47412007-08-17 15:53:36 +00006240/*
danielk1977b4b47412007-08-17 15:53:36 +00006241**
danielk1977b4b47412007-08-17 15:53:36 +00006242*/
dane88ec182016-01-25 17:04:48 +00006243static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006244 const char *zPath, /* Input path */
6245 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006246 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006247){
dancaf6b152016-01-25 18:05:49 +00006248 int nPath = sqlite3Strlen30(zPath);
6249 int iOff = 0;
6250 if( zPath[0]!='/' ){
6251 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006252 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006253 }
dancaf6b152016-01-25 18:05:49 +00006254 iOff = sqlite3Strlen30(zOut);
6255 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006256 }
dan23496702016-01-26 13:56:42 +00006257 if( (iOff+nPath+1)>nOut ){
6258 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6259 ** even if it returns an error. */
6260 zOut[iOff] = '\0';
6261 return SQLITE_CANTOPEN_BKPT;
6262 }
dancaf6b152016-01-25 18:05:49 +00006263 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006264 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006265}
6266
dane88ec182016-01-25 17:04:48 +00006267/*
6268** Turn a relative pathname into a full pathname. The relative path
6269** is stored as a nul-terminated string in the buffer pointed to by
6270** zPath.
6271**
6272** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6273** (in this case, MAX_PATHNAME bytes). The full-path is written to
6274** this buffer before returning.
6275*/
6276static int unixFullPathname(
6277 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6278 const char *zPath, /* Possibly relative input path */
6279 int nOut, /* Size of output buffer in bytes */
6280 char *zOut /* Output buffer */
6281){
danaf1b36b2016-01-25 18:43:05 +00006282#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006283 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006284#else
6285 int rc = SQLITE_OK;
6286 int nByte;
dancaf6b152016-01-25 18:05:49 +00006287 int nLink = 1; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006288 const char *zIn = zPath; /* Input path for each iteration of loop */
6289 char *zDel = 0;
6290
6291 assert( pVfs->mxPathname==MAX_PATHNAME );
6292 UNUSED_PARAMETER(pVfs);
6293
6294 /* It's odd to simulate an io-error here, but really this is just
6295 ** using the io-error infrastructure to test that SQLite handles this
6296 ** function failing. This function could fail if, for example, the
6297 ** current working directory has been unlinked.
6298 */
6299 SimulateIOError( return SQLITE_ERROR );
6300
6301 do {
6302
dancaf6b152016-01-25 18:05:49 +00006303 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6304 ** link, or false otherwise. */
6305 int bLink = 0;
6306 struct stat buf;
6307 if( osLstat(zIn, &buf)!=0 ){
6308 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006309 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006310 }
dane88ec182016-01-25 17:04:48 +00006311 }else{
dancaf6b152016-01-25 18:05:49 +00006312 bLink = S_ISLNK(buf.st_mode);
6313 }
6314
6315 if( bLink ){
dane88ec182016-01-25 17:04:48 +00006316 if( zDel==0 ){
6317 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006318 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
dancaf6b152016-01-25 18:05:49 +00006319 }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
6320 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006321 }
dancaf6b152016-01-25 18:05:49 +00006322
6323 if( rc==SQLITE_OK ){
6324 nByte = osReadlink(zIn, zDel, nOut-1);
6325 if( nByte<0 ){
6326 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006327 }else{
6328 if( zDel[0]!='/' ){
6329 int n;
6330 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6331 if( nByte+n+1>nOut ){
6332 rc = SQLITE_CANTOPEN_BKPT;
6333 }else{
6334 memmove(&zDel[n], zDel, nByte+1);
6335 memcpy(zDel, zIn, n);
6336 nByte += n;
6337 }
dancaf6b152016-01-25 18:05:49 +00006338 }
6339 zDel[nByte] = '\0';
6340 }
6341 }
6342
6343 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006344 }
6345
dan23496702016-01-26 13:56:42 +00006346 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6347 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006348 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006349 }
dancaf6b152016-01-25 18:05:49 +00006350 if( bLink==0 ) break;
6351 zIn = zOut;
6352 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006353
6354 sqlite3_free(zDel);
6355 return rc;
danaf1b36b2016-01-25 18:43:05 +00006356#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006357}
6358
drh0ccebe72005-06-07 22:22:50 +00006359
drh761df872006-12-21 01:29:22 +00006360#ifndef SQLITE_OMIT_LOAD_EXTENSION
6361/*
6362** Interfaces for opening a shared library, finding entry points
6363** within the shared library, and closing the shared library.
6364*/
6365#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006366static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6367 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006368 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6369}
danielk197795c8a542007-09-01 06:51:27 +00006370
6371/*
6372** SQLite calls this function immediately after a call to unixDlSym() or
6373** unixDlOpen() fails (returns a null pointer). If a more detailed error
6374** message is available, it is written to zBufOut. If no error message
6375** is available, zBufOut is left unmodified and SQLite uses a default
6376** error message.
6377*/
danielk1977397d65f2008-11-19 11:35:39 +00006378static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006379 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006380 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006381 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006382 zErr = dlerror();
6383 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006384 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006385 }
drh6c7d5c52008-11-21 20:32:33 +00006386 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006387}
drh1875f7a2008-12-08 18:19:17 +00006388static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6389 /*
6390 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6391 ** cast into a pointer to a function. And yet the library dlsym() routine
6392 ** returns a void* which is really a pointer to a function. So how do we
6393 ** use dlsym() with -pedantic-errors?
6394 **
6395 ** Variable x below is defined to be a pointer to a function taking
6396 ** parameters void* and const char* and returning a pointer to a function.
6397 ** We initialize x by assigning it a pointer to the dlsym() function.
6398 ** (That assignment requires a cast.) Then we call the function that
6399 ** x points to.
6400 **
6401 ** This work-around is unlikely to work correctly on any system where
6402 ** you really cannot cast a function pointer into void*. But then, on the
6403 ** other hand, dlsym() will not work on such a system either, so we have
6404 ** not really lost anything.
6405 */
6406 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006407 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006408 x = (void(*(*)(void*,const char*))(void))dlsym;
6409 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006410}
danielk1977397d65f2008-11-19 11:35:39 +00006411static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6412 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006413 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006414}
danielk1977b4b47412007-08-17 15:53:36 +00006415#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6416 #define unixDlOpen 0
6417 #define unixDlError 0
6418 #define unixDlSym 0
6419 #define unixDlClose 0
6420#endif
6421
6422/*
danielk197790949c22007-08-17 16:50:38 +00006423** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006424*/
danielk1977397d65f2008-11-19 11:35:39 +00006425static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6426 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006427 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006428
drhbbd42a62004-05-22 17:41:58 +00006429 /* We have to initialize zBuf to prevent valgrind from reporting
6430 ** errors. The reports issued by valgrind are incorrect - we would
6431 ** prefer that the randomness be increased by making use of the
6432 ** uninitialized space in zBuf - but valgrind errors tend to worry
6433 ** some users. Rather than argue, it seems easier just to initialize
6434 ** the whole array and silence valgrind, even if that means less randomness
6435 ** in the random seed.
6436 **
6437 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006438 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006439 ** tests repeatable.
6440 */
danielk1977b4b47412007-08-17 15:53:36 +00006441 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006442 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006443#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006444 {
drhb00d8622014-01-01 15:18:36 +00006445 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006446 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006447 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006448 time_t t;
6449 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006450 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006451 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6452 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6453 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006454 }else{
drhc18b4042012-02-10 03:10:27 +00006455 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006456 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006457 }
drhbbd42a62004-05-22 17:41:58 +00006458 }
6459#endif
drh72cbd072008-10-14 17:58:38 +00006460 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006461}
6462
danielk1977b4b47412007-08-17 15:53:36 +00006463
drhbbd42a62004-05-22 17:41:58 +00006464/*
6465** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006466** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006467** The return value is the number of microseconds of sleep actually
6468** requested from the underlying operating system, a number which
6469** might be greater than or equal to the argument, but not less
6470** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006471*/
danielk1977397d65f2008-11-19 11:35:39 +00006472static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006473#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006474 struct timespec sp;
6475
6476 sp.tv_sec = microseconds / 1000000;
6477 sp.tv_nsec = (microseconds % 1000000) * 1000;
6478 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006479 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006480 return microseconds;
6481#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006482 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006483 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006484 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006485#else
danielk1977b4b47412007-08-17 15:53:36 +00006486 int seconds = (microseconds+999999)/1000000;
6487 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006488 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006489 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006490#endif
drh88f474a2006-01-02 20:00:12 +00006491}
6492
6493/*
drh6b9d6dd2008-12-03 19:34:47 +00006494** The following variable, if set to a non-zero value, is interpreted as
6495** the number of seconds since 1970 and is used to set the result of
6496** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006497*/
6498#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006499int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006500#endif
6501
6502/*
drhb7e8ea22010-05-03 14:32:30 +00006503** Find the current time (in Universal Coordinated Time). Write into *piNow
6504** the current time and date as a Julian Day number times 86_400_000. In
6505** other words, write into *piNow the number of milliseconds since the Julian
6506** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6507** proleptic Gregorian calendar.
6508**
drh31702252011-10-12 23:13:43 +00006509** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6510** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006511*/
6512static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6513 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006514 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006515#if defined(NO_GETTOD)
6516 time_t t;
6517 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006518 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006519#elif OS_VXWORKS
6520 struct timespec sNow;
6521 clock_gettime(CLOCK_REALTIME, &sNow);
6522 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6523#else
6524 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006525 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6526 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006527#endif
6528
6529#ifdef SQLITE_TEST
6530 if( sqlite3_current_time ){
6531 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6532 }
6533#endif
6534 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006535 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006536}
6537
drhc3dfa5e2016-01-22 19:44:03 +00006538#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006539/*
drhbbd42a62004-05-22 17:41:58 +00006540** Find the current time (in Universal Coordinated Time). Write the
6541** current time and date as a Julian Day number into *prNow and
6542** return 0. Return 1 if the time and date cannot be found.
6543*/
danielk1977397d65f2008-11-19 11:35:39 +00006544static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006545 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006546 int rc;
drhff828942010-06-26 21:34:06 +00006547 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006548 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006549 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006550 return rc;
drhbbd42a62004-05-22 17:41:58 +00006551}
drh5337dac2015-11-25 15:15:03 +00006552#else
6553# define unixCurrentTime 0
6554#endif
danielk1977b4b47412007-08-17 15:53:36 +00006555
drh6b9d6dd2008-12-03 19:34:47 +00006556/*
drh1b9f2142016-03-17 16:01:23 +00006557** The xGetLastError() method is designed to return a better
6558** low-level error message when operating-system problems come up
6559** during SQLite operation. Only the integer return code is currently
6560** used.
drh6b9d6dd2008-12-03 19:34:47 +00006561*/
danielk1977397d65f2008-11-19 11:35:39 +00006562static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6563 UNUSED_PARAMETER(NotUsed);
6564 UNUSED_PARAMETER(NotUsed2);
6565 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006566 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006567}
6568
drhf2424c52010-04-26 00:04:55 +00006569
6570/*
drh734c9862008-11-28 15:37:20 +00006571************************ End of sqlite3_vfs methods ***************************
6572******************************************************************************/
6573
drh715ff302008-12-03 22:32:44 +00006574/******************************************************************************
6575************************** Begin Proxy Locking ********************************
6576**
6577** Proxy locking is a "uber-locking-method" in this sense: It uses the
6578** other locking methods on secondary lock files. Proxy locking is a
6579** meta-layer over top of the primitive locking implemented above. For
6580** this reason, the division that implements of proxy locking is deferred
6581** until late in the file (here) after all of the other I/O methods have
6582** been defined - so that the primitive locking methods are available
6583** as services to help with the implementation of proxy locking.
6584**
6585****
6586**
6587** The default locking schemes in SQLite use byte-range locks on the
6588** database file to coordinate safe, concurrent access by multiple readers
6589** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6590** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6591** as POSIX read & write locks over fixed set of locations (via fsctl),
6592** on AFP and SMB only exclusive byte-range locks are available via fsctl
6593** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6594** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6595** address in the shared range is taken for a SHARED lock, the entire
6596** shared range is taken for an EXCLUSIVE lock):
6597**
drhf2f105d2012-08-20 15:53:54 +00006598** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006599** RESERVED_BYTE 0x40000001
6600** SHARED_RANGE 0x40000002 -> 0x40000200
6601**
6602** This works well on the local file system, but shows a nearly 100x
6603** slowdown in read performance on AFP because the AFP client disables
6604** the read cache when byte-range locks are present. Enabling the read
6605** cache exposes a cache coherency problem that is present on all OS X
6606** supported network file systems. NFS and AFP both observe the
6607** close-to-open semantics for ensuring cache coherency
6608** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6609** address the requirements for concurrent database access by multiple
6610** readers and writers
6611** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6612**
6613** To address the performance and cache coherency issues, proxy file locking
6614** changes the way database access is controlled by limiting access to a
6615** single host at a time and moving file locks off of the database file
6616** and onto a proxy file on the local file system.
6617**
6618**
6619** Using proxy locks
6620** -----------------
6621**
6622** C APIs
6623**
drh4bf66fd2015-02-19 02:43:02 +00006624** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006625** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006626** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6627** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006628**
6629**
6630** SQL pragmas
6631**
6632** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6633** PRAGMA [database.]lock_proxy_file
6634**
6635** Specifying ":auto:" means that if there is a conch file with a matching
6636** host ID in it, the proxy path in the conch file will be used, otherwise
6637** a proxy path based on the user's temp dir
6638** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6639** actual proxy file name is generated from the name and path of the
6640** database file. For example:
6641**
6642** For database path "/Users/me/foo.db"
6643** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6644**
6645** Once a lock proxy is configured for a database connection, it can not
6646** be removed, however it may be switched to a different proxy path via
6647** the above APIs (assuming the conch file is not being held by another
6648** connection or process).
6649**
6650**
6651** How proxy locking works
6652** -----------------------
6653**
6654** Proxy file locking relies primarily on two new supporting files:
6655**
6656** * conch file to limit access to the database file to a single host
6657** at a time
6658**
6659** * proxy file to act as a proxy for the advisory locks normally
6660** taken on the database
6661**
6662** The conch file - to use a proxy file, sqlite must first "hold the conch"
6663** by taking an sqlite-style shared lock on the conch file, reading the
6664** contents and comparing the host's unique host ID (see below) and lock
6665** proxy path against the values stored in the conch. The conch file is
6666** stored in the same directory as the database file and the file name
6667** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006668** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006669** host ID and/or proxy path, then the lock is escalated to an exclusive
6670** lock and the conch file contents is updated with the host ID and proxy
6671** path and the lock is downgraded to a shared lock again. If the conch
6672** is held by another process (with a shared lock), the exclusive lock
6673** will fail and SQLITE_BUSY is returned.
6674**
6675** The proxy file - a single-byte file used for all advisory file locks
6676** normally taken on the database file. This allows for safe sharing
6677** of the database file for multiple readers and writers on the same
6678** host (the conch ensures that they all use the same local lock file).
6679**
drh715ff302008-12-03 22:32:44 +00006680** Requesting the lock proxy does not immediately take the conch, it is
6681** only taken when the first request to lock database file is made.
6682** This matches the semantics of the traditional locking behavior, where
6683** opening a connection to a database file does not take a lock on it.
6684** The shared lock and an open file descriptor are maintained until
6685** the connection to the database is closed.
6686**
6687** The proxy file and the lock file are never deleted so they only need
6688** to be created the first time they are used.
6689**
6690** Configuration options
6691** ---------------------
6692**
6693** SQLITE_PREFER_PROXY_LOCKING
6694**
6695** Database files accessed on non-local file systems are
6696** automatically configured for proxy locking, lock files are
6697** named automatically using the same logic as
6698** PRAGMA lock_proxy_file=":auto:"
6699**
6700** SQLITE_PROXY_DEBUG
6701**
6702** Enables the logging of error messages during host id file
6703** retrieval and creation
6704**
drh715ff302008-12-03 22:32:44 +00006705** LOCKPROXYDIR
6706**
6707** Overrides the default directory used for lock proxy files that
6708** are named automatically via the ":auto:" setting
6709**
6710** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6711**
6712** Permissions to use when creating a directory for storing the
6713** lock proxy files, only used when LOCKPROXYDIR is not set.
6714**
6715**
6716** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6717** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6718** force proxy locking to be used for every database file opened, and 0
6719** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006720** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006721** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6722*/
6723
6724/*
6725** Proxy locking is only available on MacOSX
6726*/
drhd2cb50b2009-01-09 21:41:17 +00006727#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006728
drh715ff302008-12-03 22:32:44 +00006729/*
6730** The proxyLockingContext has the path and file structures for the remote
6731** and local proxy files in it
6732*/
6733typedef struct proxyLockingContext proxyLockingContext;
6734struct proxyLockingContext {
6735 unixFile *conchFile; /* Open conch file */
6736 char *conchFilePath; /* Name of the conch file */
6737 unixFile *lockProxy; /* Open proxy lock file */
6738 char *lockProxyPath; /* Name of the proxy lock file */
6739 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006740 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006741 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006742 void *oldLockingContext; /* Original lockingcontext to restore on close */
6743 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6744};
6745
drh7ed97b92010-01-20 13:07:21 +00006746/*
6747** The proxy lock file path for the database at dbPath is written into lPath,
6748** which must point to valid, writable memory large enough for a maxLen length
6749** file path.
drh715ff302008-12-03 22:32:44 +00006750*/
drh715ff302008-12-03 22:32:44 +00006751static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6752 int len;
6753 int dbLen;
6754 int i;
6755
6756#ifdef LOCKPROXYDIR
6757 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6758#else
6759# ifdef _CS_DARWIN_USER_TEMP_DIR
6760 {
drh7ed97b92010-01-20 13:07:21 +00006761 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006762 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006763 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006764 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006765 }
drh7ed97b92010-01-20 13:07:21 +00006766 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006767 }
6768# else
6769 len = strlcpy(lPath, "/tmp/", maxLen);
6770# endif
6771#endif
6772
6773 if( lPath[len-1]!='/' ){
6774 len = strlcat(lPath, "/", maxLen);
6775 }
6776
6777 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006778 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006779 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006780 char c = dbPath[i];
6781 lPath[i+len] = (c=='/')?'_':c;
6782 }
6783 lPath[i+len]='\0';
6784 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006785 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006786 return SQLITE_OK;
6787}
6788
drh7ed97b92010-01-20 13:07:21 +00006789/*
6790 ** Creates the lock file and any missing directories in lockPath
6791 */
6792static int proxyCreateLockPath(const char *lockPath){
6793 int i, len;
6794 char buf[MAXPATHLEN];
6795 int start = 0;
6796
6797 assert(lockPath!=NULL);
6798 /* try to create all the intermediate directories */
6799 len = (int)strlen(lockPath);
6800 buf[0] = lockPath[0];
6801 for( i=1; i<len; i++ ){
6802 if( lockPath[i] == '/' && (i - start > 0) ){
6803 /* only mkdir if leaf dir != "." or "/" or ".." */
6804 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6805 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6806 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006807 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006808 int err=errno;
6809 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006810 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006811 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006812 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006813 return err;
6814 }
6815 }
6816 }
6817 start=i+1;
6818 }
6819 buf[i] = lockPath[i];
6820 }
drh62aaa6c2015-11-21 17:27:42 +00006821 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006822 return 0;
6823}
6824
drh715ff302008-12-03 22:32:44 +00006825/*
6826** Create a new VFS file descriptor (stored in memory obtained from
6827** sqlite3_malloc) and open the file named "path" in the file descriptor.
6828**
6829** The caller is responsible not only for closing the file descriptor
6830** but also for freeing the memory associated with the file descriptor.
6831*/
drh7ed97b92010-01-20 13:07:21 +00006832static int proxyCreateUnixFile(
6833 const char *path, /* path for the new unixFile */
6834 unixFile **ppFile, /* unixFile created and returned by ref */
6835 int islockfile /* if non zero missing dirs will be created */
6836) {
6837 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006838 unixFile *pNew;
6839 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00006840 int openFlags = O_RDWR | O_CREAT;
drh715ff302008-12-03 22:32:44 +00006841 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006842 int terrno = 0;
6843 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006844
drh7ed97b92010-01-20 13:07:21 +00006845 /* 1. first try to open/create the file
6846 ** 2. if that fails, and this is a lock file (not-conch), try creating
6847 ** the parent directories and then try again.
6848 ** 3. if that fails, try to open the file read-only
6849 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6850 */
6851 pUnused = findReusableFd(path, openFlags);
6852 if( pUnused ){
6853 fd = pUnused->fd;
6854 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006855 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006856 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006857 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006858 }
6859 }
6860 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006861 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006862 terrno = errno;
6863 if( fd<0 && errno==ENOENT && islockfile ){
6864 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006865 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006866 }
6867 }
6868 }
6869 if( fd<0 ){
6870 openFlags = O_RDONLY;
drh8c815d12012-02-13 20:16:37 +00006871 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006872 terrno = errno;
6873 }
6874 if( fd<0 ){
6875 if( islockfile ){
6876 return SQLITE_BUSY;
6877 }
6878 switch (terrno) {
6879 case EACCES:
6880 return SQLITE_PERM;
6881 case EIO:
6882 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6883 default:
drh9978c972010-02-23 17:36:32 +00006884 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006885 }
6886 }
6887
drhf3cdcdc2015-04-29 16:50:28 +00006888 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006889 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006890 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006891 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006892 }
6893 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006894 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006895 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006896 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006897 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006898 pUnused->fd = fd;
6899 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006900 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006901
drhc02a43a2012-01-10 23:18:38 +00006902 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006903 if( rc==SQLITE_OK ){
6904 *ppFile = pNew;
6905 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006906 }
drh7ed97b92010-01-20 13:07:21 +00006907end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006908 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006909 sqlite3_free(pNew);
6910 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006911 return rc;
6912}
6913
drh7ed97b92010-01-20 13:07:21 +00006914#ifdef SQLITE_TEST
6915/* simulate multiple hosts by creating unique hostid file paths */
6916int sqlite3_hostid_num = 0;
6917#endif
6918
6919#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6920
drh6bca6512015-04-13 23:05:28 +00006921#ifdef HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006922/* Not always defined in the headers as it ought to be */
6923extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006924#endif
drh0ab216a2010-07-02 17:10:40 +00006925
drh7ed97b92010-01-20 13:07:21 +00006926/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6927** bytes of writable memory.
6928*/
6929static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006930 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6931 memset(pHostID, 0, PROXY_HOSTIDLEN);
drh6bca6512015-04-13 23:05:28 +00006932#ifdef HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006933 {
drh4bf66fd2015-02-19 02:43:02 +00006934 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006935 if( gethostuuid(pHostID, &timeout) ){
6936 int err = errno;
6937 if( pError ){
6938 *pError = err;
6939 }
6940 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006941 }
drh7ed97b92010-01-20 13:07:21 +00006942 }
drh3d4435b2011-08-26 20:55:50 +00006943#else
6944 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006945#endif
drh7ed97b92010-01-20 13:07:21 +00006946#ifdef SQLITE_TEST
6947 /* simulate multiple hosts by creating unique hostid file paths */
6948 if( sqlite3_hostid_num != 0){
6949 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
6950 }
6951#endif
6952
6953 return SQLITE_OK;
6954}
6955
6956/* The conch file contains the header, host id and lock file path
6957 */
6958#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
6959#define PROXY_HEADERLEN 1 /* conch file header length */
6960#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
6961#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
6962
6963/*
6964** Takes an open conch file, copies the contents to a new path and then moves
6965** it back. The newly created file's file descriptor is assigned to the
6966** conch file structure and finally the original conch file descriptor is
6967** closed. Returns zero if successful.
6968*/
6969static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
6970 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
6971 unixFile *conchFile = pCtx->conchFile;
6972 char tPath[MAXPATHLEN];
6973 char buf[PROXY_MAXCONCHLEN];
6974 char *cPath = pCtx->conchFilePath;
6975 size_t readLen = 0;
6976 size_t pathLen = 0;
6977 char errmsg[64] = "";
6978 int fd = -1;
6979 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00006980 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00006981
6982 /* create a new path by replace the trailing '-conch' with '-break' */
6983 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
6984 if( pathLen>MAXPATHLEN || pathLen<6 ||
6985 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00006986 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00006987 goto end_breaklock;
6988 }
6989 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00006990 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00006991 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00006992 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00006993 goto end_breaklock;
6994 }
6995 /* write it out to the temporary break file */
drh8c815d12012-02-13 20:16:37 +00006996 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
drh7ed97b92010-01-20 13:07:21 +00006997 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00006998 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00006999 goto end_breaklock;
7000 }
drhe562be52011-03-02 18:01:10 +00007001 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00007002 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007003 goto end_breaklock;
7004 }
7005 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00007006 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007007 goto end_breaklock;
7008 }
7009 rc = 0;
7010 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007011 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007012 conchFile->h = fd;
7013 conchFile->openFlags = O_RDWR | O_CREAT;
7014
7015end_breaklock:
7016 if( rc ){
7017 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007018 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007019 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007020 }
7021 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7022 }
7023 return rc;
7024}
7025
7026/* Take the requested lock on the conch file and break a stale lock if the
7027** host id matches.
7028*/
7029static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7030 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7031 unixFile *conchFile = pCtx->conchFile;
7032 int rc = SQLITE_OK;
7033 int nTries = 0;
7034 struct timespec conchModTime;
7035
drh3d4435b2011-08-26 20:55:50 +00007036 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007037 do {
7038 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7039 nTries ++;
7040 if( rc==SQLITE_BUSY ){
7041 /* If the lock failed (busy):
7042 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7043 * 2nd try: fail if the mod time changed or host id is different, wait
7044 * 10 sec and try again
7045 * 3rd try: break the lock unless the mod time has changed.
7046 */
7047 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007048 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007049 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007050 return SQLITE_IOERR_LOCK;
7051 }
7052
7053 if( nTries==1 ){
7054 conchModTime = buf.st_mtimespec;
7055 usleep(500000); /* wait 0.5 sec and try the lock again*/
7056 continue;
7057 }
7058
7059 assert( nTries>1 );
7060 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7061 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7062 return SQLITE_BUSY;
7063 }
7064
7065 if( nTries==2 ){
7066 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007067 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007068 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007069 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007070 return SQLITE_IOERR_LOCK;
7071 }
7072 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7073 /* don't break the lock if the host id doesn't match */
7074 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7075 return SQLITE_BUSY;
7076 }
7077 }else{
7078 /* don't break the lock on short read or a version mismatch */
7079 return SQLITE_BUSY;
7080 }
7081 usleep(10000000); /* wait 10 sec and try the lock again */
7082 continue;
7083 }
7084
7085 assert( nTries==3 );
7086 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7087 rc = SQLITE_OK;
7088 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007089 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007090 }
7091 if( !rc ){
7092 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7093 }
7094 }
7095 }
7096 } while( rc==SQLITE_BUSY && nTries<3 );
7097
7098 return rc;
7099}
7100
7101/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007102** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7103** lockPath means that the lockPath in the conch file will be used if the
7104** host IDs match, or a new lock path will be generated automatically
7105** and written to the conch file.
7106*/
7107static int proxyTakeConch(unixFile *pFile){
7108 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7109
drh7ed97b92010-01-20 13:07:21 +00007110 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007111 return SQLITE_OK;
7112 }else{
7113 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007114 uuid_t myHostID;
7115 int pError = 0;
7116 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007117 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007118 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007119 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007120 int createConch = 0;
7121 int hostIdMatch = 0;
7122 int readLen = 0;
7123 int tryOldLockPath = 0;
7124 int forceNewLockPath = 0;
7125
drh308c2a52010-05-14 11:30:18 +00007126 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007127 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007128 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007129
drh7ed97b92010-01-20 13:07:21 +00007130 rc = proxyGetHostID(myHostID, &pError);
7131 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007132 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007133 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007134 }
drh7ed97b92010-01-20 13:07:21 +00007135 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007136 if( rc!=SQLITE_OK ){
7137 goto end_takeconch;
7138 }
drh7ed97b92010-01-20 13:07:21 +00007139 /* read the existing conch file */
7140 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7141 if( readLen<0 ){
7142 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007143 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007144 rc = SQLITE_IOERR_READ;
7145 goto end_takeconch;
7146 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7147 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7148 /* a short read or version format mismatch means we need to create a new
7149 ** conch file.
7150 */
7151 createConch = 1;
7152 }
7153 /* if the host id matches and the lock path already exists in the conch
7154 ** we'll try to use the path there, if we can't open that path, we'll
7155 ** retry with a new auto-generated path
7156 */
7157 do { /* in case we need to try again for an :auto: named lock file */
7158
7159 if( !createConch && !forceNewLockPath ){
7160 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7161 PROXY_HOSTIDLEN);
7162 /* if the conch has data compare the contents */
7163 if( !pCtx->lockProxyPath ){
7164 /* for auto-named local lock file, just check the host ID and we'll
7165 ** use the local lock file path that's already in there
7166 */
7167 if( hostIdMatch ){
7168 size_t pathLen = (readLen - PROXY_PATHINDEX);
7169
7170 if( pathLen>=MAXPATHLEN ){
7171 pathLen=MAXPATHLEN-1;
7172 }
7173 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7174 lockPath[pathLen] = 0;
7175 tempLockPath = lockPath;
7176 tryOldLockPath = 1;
7177 /* create a copy of the lock path if the conch is taken */
7178 goto end_takeconch;
7179 }
7180 }else if( hostIdMatch
7181 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7182 readLen-PROXY_PATHINDEX)
7183 ){
7184 /* conch host and lock path match */
7185 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007186 }
drh7ed97b92010-01-20 13:07:21 +00007187 }
7188
7189 /* if the conch isn't writable and doesn't match, we can't take it */
7190 if( (conchFile->openFlags&O_RDWR) == 0 ){
7191 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007192 goto end_takeconch;
7193 }
drh7ed97b92010-01-20 13:07:21 +00007194
7195 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007196 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007197 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7198 tempLockPath = lockPath;
7199 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007200 }
drh7ed97b92010-01-20 13:07:21 +00007201
7202 /* update conch with host and path (this will fail if other process
7203 ** has a shared lock already), if the host id matches, use the big
7204 ** stick.
drh715ff302008-12-03 22:32:44 +00007205 */
drh7ed97b92010-01-20 13:07:21 +00007206 futimes(conchFile->h, NULL);
7207 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007208 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007209 /* We are trying for an exclusive lock but another thread in this
7210 ** same process is still holding a shared lock. */
7211 rc = SQLITE_BUSY;
7212 } else {
7213 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007214 }
drh715ff302008-12-03 22:32:44 +00007215 }else{
drh4bf66fd2015-02-19 02:43:02 +00007216 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007217 }
drh7ed97b92010-01-20 13:07:21 +00007218 if( rc==SQLITE_OK ){
7219 char writeBuffer[PROXY_MAXCONCHLEN];
7220 int writeSize = 0;
7221
7222 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7223 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7224 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007225 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7226 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007227 }else{
7228 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7229 }
7230 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007231 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007232 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007233 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007234 /* If we created a new conch file (not just updated the contents of a
7235 ** valid conch file), try to match the permissions of the database
7236 */
7237 if( rc==SQLITE_OK && createConch ){
7238 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007239 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007240 if( err==0 ){
7241 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7242 S_IROTH|S_IWOTH);
7243 /* try to match the database file R/W permissions, ignore failure */
7244#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007245 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007246#else
drhff812312011-02-23 13:33:46 +00007247 do{
drhe562be52011-03-02 18:01:10 +00007248 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007249 }while( rc==(-1) && errno==EINTR );
7250 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007251 int code = errno;
7252 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7253 cmode, code, strerror(code));
7254 } else {
7255 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7256 }
7257 }else{
7258 int code = errno;
7259 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7260 err, code, strerror(code));
7261#endif
7262 }
drh715ff302008-12-03 22:32:44 +00007263 }
7264 }
drh7ed97b92010-01-20 13:07:21 +00007265 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7266
7267 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007268 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007269 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007270 int fd;
drh7ed97b92010-01-20 13:07:21 +00007271 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007272 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007273 }
7274 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007275 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007276 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007277 if( fd>=0 ){
7278 pFile->h = fd;
7279 }else{
drh9978c972010-02-23 17:36:32 +00007280 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007281 during locking */
7282 }
7283 }
7284 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7285 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7286 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7287 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7288 /* we couldn't create the proxy lock file with the old lock file path
7289 ** so try again via auto-naming
7290 */
7291 forceNewLockPath = 1;
7292 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007293 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007294 }
7295 }
7296 if( rc==SQLITE_OK ){
7297 /* Need to make a copy of path if we extracted the value
7298 ** from the conch file or the path was allocated on the stack
7299 */
7300 if( tempLockPath ){
7301 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7302 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007303 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007304 }
7305 }
7306 }
7307 if( rc==SQLITE_OK ){
7308 pCtx->conchHeld = 1;
7309
7310 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7311 afpLockingContext *afpCtx;
7312 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7313 afpCtx->dbPath = pCtx->lockProxyPath;
7314 }
7315 } else {
7316 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7317 }
drh308c2a52010-05-14 11:30:18 +00007318 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7319 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007320 return rc;
drh308c2a52010-05-14 11:30:18 +00007321 } while (1); /* in case we need to retry the :auto: lock file -
7322 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007323 }
7324}
7325
7326/*
7327** If pFile holds a lock on a conch file, then release that lock.
7328*/
7329static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007330 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007331 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7332 unixFile *conchFile; /* Name of the conch file */
7333
7334 pCtx = (proxyLockingContext *)pFile->lockingContext;
7335 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007336 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007337 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007338 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007339 if( pCtx->conchHeld>0 ){
7340 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7341 }
drh715ff302008-12-03 22:32:44 +00007342 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007343 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7344 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007345 return rc;
7346}
7347
7348/*
7349** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007350** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007351** Make *pConchPath point to the new name. Return SQLITE_OK on success
7352** or SQLITE_NOMEM if unable to obtain memory.
7353**
7354** The caller is responsible for ensuring that the allocated memory
7355** space is eventually freed.
7356**
7357** *pConchPath is set to NULL if a memory allocation error occurs.
7358*/
7359static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7360 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007361 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007362 char *conchPath; /* buffer in which to construct conch name */
7363
7364 /* Allocate space for the conch filename and initialize the name to
7365 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007366 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007367 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007368 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007369 }
7370 memcpy(conchPath, dbPath, len+1);
7371
7372 /* now insert a "." before the last / character */
7373 for( i=(len-1); i>=0; i-- ){
7374 if( conchPath[i]=='/' ){
7375 i++;
7376 break;
7377 }
7378 }
7379 conchPath[i]='.';
7380 while ( i<len ){
7381 conchPath[i+1]=dbPath[i];
7382 i++;
7383 }
7384
7385 /* append the "-conch" suffix to the file */
7386 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007387 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007388
7389 return SQLITE_OK;
7390}
7391
7392
7393/* Takes a fully configured proxy locking-style unix file and switches
7394** the local lock file path
7395*/
7396static int switchLockProxyPath(unixFile *pFile, const char *path) {
7397 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7398 char *oldPath = pCtx->lockProxyPath;
7399 int rc = SQLITE_OK;
7400
drh308c2a52010-05-14 11:30:18 +00007401 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007402 return SQLITE_BUSY;
7403 }
7404
7405 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7406 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7407 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7408 return SQLITE_OK;
7409 }else{
7410 unixFile *lockProxy = pCtx->lockProxy;
7411 pCtx->lockProxy=NULL;
7412 pCtx->conchHeld = 0;
7413 if( lockProxy!=NULL ){
7414 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7415 if( rc ) return rc;
7416 sqlite3_free(lockProxy);
7417 }
7418 sqlite3_free(oldPath);
7419 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7420 }
7421
7422 return rc;
7423}
7424
7425/*
7426** pFile is a file that has been opened by a prior xOpen call. dbPath
7427** is a string buffer at least MAXPATHLEN+1 characters in size.
7428**
7429** This routine find the filename associated with pFile and writes it
7430** int dbPath.
7431*/
7432static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007433#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007434 if( pFile->pMethod == &afpIoMethods ){
7435 /* afp style keeps a reference to the db path in the filePath field
7436 ** of the struct */
drhea678832008-12-10 19:26:22 +00007437 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007438 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7439 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007440 } else
drh715ff302008-12-03 22:32:44 +00007441#endif
7442 if( pFile->pMethod == &dotlockIoMethods ){
7443 /* dot lock style uses the locking context to store the dot lock
7444 ** file path */
7445 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7446 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7447 }else{
7448 /* all other styles use the locking context to store the db file path */
7449 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007450 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007451 }
7452 return SQLITE_OK;
7453}
7454
7455/*
7456** Takes an already filled in unix file and alters it so all file locking
7457** will be performed on the local proxy lock file. The following fields
7458** are preserved in the locking context so that they can be restored and
7459** the unix structure properly cleaned up at close time:
7460** ->lockingContext
7461** ->pMethod
7462*/
7463static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7464 proxyLockingContext *pCtx;
7465 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7466 char *lockPath=NULL;
7467 int rc = SQLITE_OK;
7468
drh308c2a52010-05-14 11:30:18 +00007469 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007470 return SQLITE_BUSY;
7471 }
7472 proxyGetDbPathForUnixFile(pFile, dbPath);
7473 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7474 lockPath=NULL;
7475 }else{
7476 lockPath=(char *)path;
7477 }
7478
drh308c2a52010-05-14 11:30:18 +00007479 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007480 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007481
drhf3cdcdc2015-04-29 16:50:28 +00007482 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007483 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007484 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007485 }
7486 memset(pCtx, 0, sizeof(*pCtx));
7487
7488 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7489 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007490 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7491 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7492 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7493 ** (c) the file system is read-only, then enable no-locking access.
7494 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7495 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7496 */
7497 struct statfs fsInfo;
7498 struct stat conchInfo;
7499 int goLockless = 0;
7500
drh99ab3b12011-03-02 15:09:07 +00007501 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007502 int err = errno;
7503 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7504 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7505 }
7506 }
7507 if( goLockless ){
7508 pCtx->conchHeld = -1; /* read only FS/ lockless */
7509 rc = SQLITE_OK;
7510 }
7511 }
drh715ff302008-12-03 22:32:44 +00007512 }
7513 if( rc==SQLITE_OK && lockPath ){
7514 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7515 }
7516
7517 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007518 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7519 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007520 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007521 }
7522 }
7523 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007524 /* all memory is allocated, proxys are created and assigned,
7525 ** switch the locking context and pMethod then return.
7526 */
drh715ff302008-12-03 22:32:44 +00007527 pCtx->oldLockingContext = pFile->lockingContext;
7528 pFile->lockingContext = pCtx;
7529 pCtx->pOldMethod = pFile->pMethod;
7530 pFile->pMethod = &proxyIoMethods;
7531 }else{
7532 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007533 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007534 sqlite3_free(pCtx->conchFile);
7535 }
drhd56b1212010-08-11 06:14:15 +00007536 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007537 sqlite3_free(pCtx->conchFilePath);
7538 sqlite3_free(pCtx);
7539 }
drh308c2a52010-05-14 11:30:18 +00007540 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7541 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007542 return rc;
7543}
7544
7545
7546/*
7547** This routine handles sqlite3_file_control() calls that are specific
7548** to proxy locking.
7549*/
7550static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7551 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007552 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007553 unixFile *pFile = (unixFile*)id;
7554 if( pFile->pMethod == &proxyIoMethods ){
7555 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7556 proxyTakeConch(pFile);
7557 if( pCtx->lockProxyPath ){
7558 *(const char **)pArg = pCtx->lockProxyPath;
7559 }else{
7560 *(const char **)pArg = ":auto: (not held)";
7561 }
7562 } else {
7563 *(const char **)pArg = NULL;
7564 }
7565 return SQLITE_OK;
7566 }
drh4bf66fd2015-02-19 02:43:02 +00007567 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007568 unixFile *pFile = (unixFile*)id;
7569 int rc = SQLITE_OK;
7570 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7571 if( pArg==NULL || (const char *)pArg==0 ){
7572 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007573 /* turn off proxy locking - not supported. If support is added for
7574 ** switching proxy locking mode off then it will need to fail if
7575 ** the journal mode is WAL mode.
7576 */
drh715ff302008-12-03 22:32:44 +00007577 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7578 }else{
7579 /* turn off proxy locking - already off - NOOP */
7580 rc = SQLITE_OK;
7581 }
7582 }else{
7583 const char *proxyPath = (const char *)pArg;
7584 if( isProxyStyle ){
7585 proxyLockingContext *pCtx =
7586 (proxyLockingContext*)pFile->lockingContext;
7587 if( !strcmp(pArg, ":auto:")
7588 || (pCtx->lockProxyPath &&
7589 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7590 ){
7591 rc = SQLITE_OK;
7592 }else{
7593 rc = switchLockProxyPath(pFile, proxyPath);
7594 }
7595 }else{
7596 /* turn on proxy file locking */
7597 rc = proxyTransformUnixFile(pFile, proxyPath);
7598 }
7599 }
7600 return rc;
7601 }
7602 default: {
7603 assert( 0 ); /* The call assures that only valid opcodes are sent */
7604 }
7605 }
drh8616cff2019-07-13 16:15:23 +00007606 /*NOTREACHED*/ assert(0);
drh715ff302008-12-03 22:32:44 +00007607 return SQLITE_ERROR;
7608}
7609
7610/*
7611** Within this division (the proxying locking implementation) the procedures
7612** above this point are all utilities. The lock-related methods of the
7613** proxy-locking sqlite3_io_method object follow.
7614*/
7615
7616
7617/*
7618** This routine checks if there is a RESERVED lock held on the specified
7619** file by this or any other process. If such a lock is held, set *pResOut
7620** to a non-zero value otherwise *pResOut is set to zero. The return value
7621** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7622*/
7623static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7624 unixFile *pFile = (unixFile*)id;
7625 int rc = proxyTakeConch(pFile);
7626 if( rc==SQLITE_OK ){
7627 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007628 if( pCtx->conchHeld>0 ){
7629 unixFile *proxy = pCtx->lockProxy;
7630 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7631 }else{ /* conchHeld < 0 is lockless */
7632 pResOut=0;
7633 }
drh715ff302008-12-03 22:32:44 +00007634 }
7635 return rc;
7636}
7637
7638/*
drh308c2a52010-05-14 11:30:18 +00007639** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007640** of the following:
7641**
7642** (1) SHARED_LOCK
7643** (2) RESERVED_LOCK
7644** (3) PENDING_LOCK
7645** (4) EXCLUSIVE_LOCK
7646**
7647** Sometimes when requesting one lock state, additional lock states
7648** are inserted in between. The locking might fail on one of the later
7649** transitions leaving the lock state different from what it started but
7650** still short of its goal. The following chart shows the allowed
7651** transitions and the inserted intermediate states:
7652**
7653** UNLOCKED -> SHARED
7654** SHARED -> RESERVED
7655** SHARED -> (PENDING) -> EXCLUSIVE
7656** RESERVED -> (PENDING) -> EXCLUSIVE
7657** PENDING -> EXCLUSIVE
7658**
7659** This routine will only increase a lock. Use the sqlite3OsUnlock()
7660** routine to lower a locking level.
7661*/
drh308c2a52010-05-14 11:30:18 +00007662static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007663 unixFile *pFile = (unixFile*)id;
7664 int rc = proxyTakeConch(pFile);
7665 if( rc==SQLITE_OK ){
7666 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007667 if( pCtx->conchHeld>0 ){
7668 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007669 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7670 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007671 }else{
7672 /* conchHeld < 0 is lockless */
7673 }
drh715ff302008-12-03 22:32:44 +00007674 }
7675 return rc;
7676}
7677
7678
7679/*
drh308c2a52010-05-14 11:30:18 +00007680** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007681** must be either NO_LOCK or SHARED_LOCK.
7682**
7683** If the locking level of the file descriptor is already at or below
7684** the requested locking level, this routine is a no-op.
7685*/
drh308c2a52010-05-14 11:30:18 +00007686static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007687 unixFile *pFile = (unixFile*)id;
7688 int rc = proxyTakeConch(pFile);
7689 if( rc==SQLITE_OK ){
7690 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007691 if( pCtx->conchHeld>0 ){
7692 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007693 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7694 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007695 }else{
7696 /* conchHeld < 0 is lockless */
7697 }
drh715ff302008-12-03 22:32:44 +00007698 }
7699 return rc;
7700}
7701
7702/*
7703** Close a file that uses proxy locks.
7704*/
7705static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007706 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007707 unixFile *pFile = (unixFile*)id;
7708 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7709 unixFile *lockProxy = pCtx->lockProxy;
7710 unixFile *conchFile = pCtx->conchFile;
7711 int rc = SQLITE_OK;
7712
7713 if( lockProxy ){
7714 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7715 if( rc ) return rc;
7716 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7717 if( rc ) return rc;
7718 sqlite3_free(lockProxy);
7719 pCtx->lockProxy = 0;
7720 }
7721 if( conchFile ){
7722 if( pCtx->conchHeld ){
7723 rc = proxyReleaseConch(pFile);
7724 if( rc ) return rc;
7725 }
7726 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7727 if( rc ) return rc;
7728 sqlite3_free(conchFile);
7729 }
drhd56b1212010-08-11 06:14:15 +00007730 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007731 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007732 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007733 /* restore the original locking context and pMethod then close it */
7734 pFile->lockingContext = pCtx->oldLockingContext;
7735 pFile->pMethod = pCtx->pOldMethod;
7736 sqlite3_free(pCtx);
7737 return pFile->pMethod->xClose(id);
7738 }
7739 return SQLITE_OK;
7740}
7741
7742
7743
drhd2cb50b2009-01-09 21:41:17 +00007744#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007745/*
7746** The proxy locking style is intended for use with AFP filesystems.
7747** And since AFP is only supported on MacOSX, the proxy locking is also
7748** restricted to MacOSX.
7749**
7750**
7751******************* End of the proxy lock implementation **********************
7752******************************************************************************/
7753
drh734c9862008-11-28 15:37:20 +00007754/*
danielk1977e339d652008-06-28 11:23:00 +00007755** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007756**
7757** This routine registers all VFS implementations for unix-like operating
7758** systems. This routine, and the sqlite3_os_end() routine that follows,
7759** should be the only routines in this file that are visible from other
7760** files.
drh6b9d6dd2008-12-03 19:34:47 +00007761**
7762** This routine is called once during SQLite initialization and by a
7763** single thread. The memory allocation and mutex subsystems have not
7764** necessarily been initialized when this routine is called, and so they
7765** should not be used.
drh153c62c2007-08-24 03:51:33 +00007766*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007767int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007768 /*
7769 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007770 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7771 ** to the "finder" function. (pAppData is a pointer to a pointer because
7772 ** silly C90 rules prohibit a void* from being cast to a function pointer
7773 ** and so we have to go through the intermediate pointer to avoid problems
7774 ** when compiling with -pedantic-errors on GCC.)
7775 **
7776 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007777 ** finder-function. The finder-function returns a pointer to the
7778 ** sqlite_io_methods object that implements the desired locking
7779 ** behaviors. See the division above that contains the IOMETHODS
7780 ** macro for addition information on finder-functions.
7781 **
7782 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7783 ** object. But the "autolockIoFinder" available on MacOSX does a little
7784 ** more than that; it looks at the filesystem type that hosts the
7785 ** database file and tries to choose an locking method appropriate for
7786 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007787 */
drh7708e972008-11-29 00:56:52 +00007788 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007789 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007790 sizeof(unixFile), /* szOsFile */ \
7791 MAX_PATHNAME, /* mxPathname */ \
7792 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007793 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007794 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007795 unixOpen, /* xOpen */ \
7796 unixDelete, /* xDelete */ \
7797 unixAccess, /* xAccess */ \
7798 unixFullPathname, /* xFullPathname */ \
7799 unixDlOpen, /* xDlOpen */ \
7800 unixDlError, /* xDlError */ \
7801 unixDlSym, /* xDlSym */ \
7802 unixDlClose, /* xDlClose */ \
7803 unixRandomness, /* xRandomness */ \
7804 unixSleep, /* xSleep */ \
7805 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007806 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007807 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007808 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007809 unixGetSystemCall, /* xGetSystemCall */ \
7810 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007811 }
7812
drh6b9d6dd2008-12-03 19:34:47 +00007813 /*
7814 ** All default VFSes for unix are contained in the following array.
7815 **
7816 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7817 ** by the SQLite core when the VFS is registered. So the following
7818 ** array cannot be const.
7819 */
danielk1977e339d652008-06-28 11:23:00 +00007820 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007821#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007822 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007823#elif OS_VXWORKS
7824 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007825#else
7826 UNIXVFS("unix", posixIoFinder ),
7827#endif
7828 UNIXVFS("unix-none", nolockIoFinder ),
7829 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007830 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007831#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007832 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007833#endif
drhe89b2912015-03-03 20:42:01 +00007834#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007835 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007836#endif
drhe89b2912015-03-03 20:42:01 +00007837#if SQLITE_ENABLE_LOCKING_STYLE
7838 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007839#endif
drhd2cb50b2009-01-09 21:41:17 +00007840#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007841 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007842 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007843 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007844#endif
drh153c62c2007-08-24 03:51:33 +00007845 };
drh6b9d6dd2008-12-03 19:34:47 +00007846 unsigned int i; /* Loop counter */
7847
drh2aa5a002011-04-13 13:42:25 +00007848 /* Double-check that the aSyscall[] array has been constructed
7849 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007850 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007851
drh6b9d6dd2008-12-03 19:34:47 +00007852 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007853 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007854 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007855 }
drh56115892018-02-05 16:39:12 +00007856 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007857 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007858}
danielk1977e339d652008-06-28 11:23:00 +00007859
7860/*
drh6b9d6dd2008-12-03 19:34:47 +00007861** Shutdown the operating system interface.
7862**
7863** Some operating systems might need to do some cleanup in this routine,
7864** to release dynamically allocated objects. But not on unix.
7865** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007866*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007867int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007868 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007869 return SQLITE_OK;
7870}
drhdce8bdb2007-08-16 13:01:44 +00007871
danielk197729bafea2008-06-26 10:41:19 +00007872#endif /* SQLITE_OS_UNIX */