blob: a72f0629fe68f70916403fb3a0924f33caf42019 [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
drhe4079e12019-09-27 16:33:27 +0000108/*
109** Try to determine if gethostuuid() is available based on standard
110** macros. This might sometimes compute the wrong value for some
111** obscure platforms. For those cases, simply compile with one of
112** the following:
113**
114** -DHAVE_GETHOSTUUID=0
115** -DHAVE_GETHOSTUUID=1
116**
117** None if this matters except when building on Apple products with
118** -DSQLITE_ENABLE_LOCKING_STYLE.
119*/
120#ifndef HAVE_GETHOSTUUID
121# define HAVE_GETHOSTUUID 0
122# if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
123 (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
124# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
125 && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
126# undef HAVE_GETHOSTUUID
127# define HAVE_GETHOSTUUID 1
128# else
129# warning "gethostuuid() is disabled."
130# endif
drh6bca6512015-04-13 23:05:28 +0000131# endif
132#endif
133
134
drhe89b2912015-03-03 20:42:01 +0000135#if OS_VXWORKS
136# include <sys/ioctl.h>
137# include <semaphore.h>
138# include <limits.h>
139#endif /* OS_VXWORKS */
140
141#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh84a2bf62010-03-05 13:41:06 +0000142# include <sys/mount.h>
143#endif
144
drhdbe4b882011-06-20 18:00:17 +0000145#ifdef HAVE_UTIME
146# include <utime.h>
147#endif
148
drh9cbe6352005-11-29 03:13:21 +0000149/*
drh7ed97b92010-01-20 13:07:21 +0000150** Allowed values of unixFile.fsFlags
151*/
152#define SQLITE_FSFLAGS_IS_MSDOS 0x1
153
154/*
drh24efa542018-10-02 19:36:40 +0000155** If we are to be thread-safe, include the pthreads header.
drh9cbe6352005-11-29 03:13:21 +0000156*/
drhd677b3d2007-08-20 22:48:41 +0000157#if SQLITE_THREADSAFE
drh9cbe6352005-11-29 03:13:21 +0000158# include <pthread.h>
drh9cbe6352005-11-29 03:13:21 +0000159#endif
160
161/*
162** Default permissions when creating a new file
163*/
164#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
165# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
166#endif
167
danielk1977b4b47412007-08-17 15:53:36 +0000168/*
drh5adc60b2012-04-14 13:25:11 +0000169** Default permissions when creating auto proxy dir
170*/
aswiftaebf4132008-11-21 00:10:35 +0000171#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
172# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
173#endif
174
175/*
danielk1977b4b47412007-08-17 15:53:36 +0000176** Maximum supported path-length.
177*/
178#define MAX_PATHNAME 512
drh9cbe6352005-11-29 03:13:21 +0000179
dane88ec182016-01-25 17:04:48 +0000180/*
181** Maximum supported symbolic links
182*/
183#define SQLITE_MAX_SYMLINKS 100
184
drh91eb93c2015-03-03 19:56:20 +0000185/* Always cast the getpid() return type for compatibility with
186** kernel modules in VxWorks. */
187#define osGetpid(X) (pid_t)getpid()
188
drh734c9862008-11-28 15:37:20 +0000189/*
drh734c9862008-11-28 15:37:20 +0000190** Only set the lastErrno if the error code is a real error and not
191** a normal expected return code of SQLITE_BUSY or SQLITE_OK
192*/
193#define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
194
drhd91c68f2010-05-14 14:52:25 +0000195/* Forward references */
196typedef struct unixShm unixShm; /* Connection shared memory */
197typedef struct unixShmNode unixShmNode; /* Shared memory instance */
198typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
199typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
drh9cbe6352005-11-29 03:13:21 +0000200
201/*
dane946c392009-08-22 11:39:46 +0000202** Sometimes, after a file handle is closed by SQLite, the file descriptor
203** cannot be closed immediately. In these cases, instances of the following
204** structure are used to store the file descriptor while waiting for an
205** opportunity to either close or reuse it.
206*/
dane946c392009-08-22 11:39:46 +0000207struct UnixUnusedFd {
208 int fd; /* File descriptor to close */
209 int flags; /* Flags this file descriptor was opened with */
210 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
211};
212
213/*
drh9b35ea62008-11-29 02:20:26 +0000214** The unixFile structure is subclass of sqlite3_file specific to the unix
215** VFS implementations.
drh9cbe6352005-11-29 03:13:21 +0000216*/
drh054889e2005-11-30 03:20:31 +0000217typedef struct unixFile unixFile;
218struct unixFile {
danielk197762079062007-08-15 17:08:46 +0000219 sqlite3_io_methods const *pMethod; /* Always the first entry */
drhde60fc22011-12-14 17:53:36 +0000220 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
drhd91c68f2010-05-14 14:52:25 +0000221 unixInodeInfo *pInode; /* Info about locks on this inode */
drh8af6c222010-05-14 12:43:01 +0000222 int h; /* The file descriptor */
drh8af6c222010-05-14 12:43:01 +0000223 unsigned char eFileLock; /* The type of lock held on this fd */
drh3ee34842012-02-11 21:21:17 +0000224 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
drh8af6c222010-05-14 12:43:01 +0000225 int lastErrno; /* The unix errno from last I/O error */
226 void *lockingContext; /* Locking style specific state */
drhc68886b2017-08-18 16:09:52 +0000227 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
drh8af6c222010-05-14 12:43:01 +0000228 const char *zPath; /* Name of the file */
229 unixShm *pShm; /* Shared memory segment information */
dan6e09d692010-07-27 18:34:15 +0000230 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
mistachkine98844f2013-08-24 00:59:24 +0000231#if SQLITE_MAX_MMAP_SIZE>0
drh0d0614b2013-03-25 23:09:28 +0000232 int nFetchOut; /* Number of outstanding xFetch refs */
233 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
drh9b4c59f2013-04-15 17:03:42 +0000234 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
235 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
drh0d0614b2013-03-25 23:09:28 +0000236 void *pMapRegion; /* Memory mapped region */
mistachkine98844f2013-08-24 00:59:24 +0000237#endif
drh537dddf2012-10-26 13:46:24 +0000238 int sectorSize; /* Device sector size */
239 int deviceCharacteristics; /* Precomputed device characteristics */
drh08c6d442009-02-09 17:34:07 +0000240#if SQLITE_ENABLE_LOCKING_STYLE
drh8af6c222010-05-14 12:43:01 +0000241 int openFlags; /* The flags specified at open() */
drh08c6d442009-02-09 17:34:07 +0000242#endif
drh7ed97b92010-01-20 13:07:21 +0000243#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
drh8af6c222010-05-14 12:43:01 +0000244 unsigned fsFlags; /* cached details from statfs() */
drh6c7d5c52008-11-21 20:32:33 +0000245#endif
drhf0119b22018-03-26 17:40:53 +0000246#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
247 unsigned iBusyTimeout; /* Wait this many millisec on locks */
248#endif
drh6c7d5c52008-11-21 20:32:33 +0000249#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +0000250 struct vxworksFileId *pId; /* Unique file ID */
drh6c7d5c52008-11-21 20:32:33 +0000251#endif
drhd3d8c042012-05-29 17:02:40 +0000252#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +0000253 /* The next group of variables are used to track whether or not the
254 ** transaction counter in bytes 24-27 of database files are updated
255 ** whenever any part of the database changes. An assertion fault will
256 ** occur if a file is updated without also updating the transaction
257 ** counter. This test is made to avoid new problems similar to the
258 ** one described by ticket #3584.
259 */
260 unsigned char transCntrChng; /* True if the transaction counter changed */
261 unsigned char dbUpdate; /* True if any part of database file changed */
262 unsigned char inNormalWrite; /* True if in a normal write operation */
danf23da962013-03-23 21:00:41 +0000263
drh8f941bc2009-01-14 23:03:40 +0000264#endif
danf23da962013-03-23 21:00:41 +0000265
danielk1977967a4a12007-08-20 14:23:44 +0000266#ifdef SQLITE_TEST
267 /* In test mode, increase the size of this structure a bit so that
268 ** it is larger than the struct CrashFile defined in test6.c.
269 */
270 char aPadding[32];
271#endif
drh9cbe6352005-11-29 03:13:21 +0000272};
273
drhb00d8622014-01-01 15:18:36 +0000274/* This variable holds the process id (pid) from when the xRandomness()
275** method was called. If xOpen() is called from a different process id,
276** indicating that a fork() has occurred, the PRNG will be reset.
277*/
drh8cd5b252015-03-02 22:06:43 +0000278static pid_t randomnessPid = 0;
drhb00d8622014-01-01 15:18:36 +0000279
drh0ccebe72005-06-07 22:22:50 +0000280/*
drha7e61d82011-03-12 17:02:57 +0000281** Allowed values for the unixFile.ctrlFlags bitmask:
282*/
drhf0b190d2011-07-26 16:03:07 +0000283#define UNIXFILE_EXCL 0x01 /* Connections from one process only */
284#define UNIXFILE_RDONLY 0x02 /* Connection is read only */
285#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
danee140c42011-08-25 13:46:32 +0000286#ifndef SQLITE_DISABLE_DIRSYNC
287# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
288#else
289# define UNIXFILE_DIRSYNC 0x00
290#endif
drhcb15f352011-12-23 01:04:17 +0000291#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
drhc02a43a2012-01-10 23:18:38 +0000292#define UNIXFILE_DELETE 0x20 /* Delete on close */
293#define UNIXFILE_URI 0x40 /* Filename might have query parameters */
294#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
drha7e61d82011-03-12 17:02:57 +0000295
296/*
drh198bf392006-01-06 21:52:49 +0000297** Include code that is common to all os_*.c files
298*/
299#include "os_common.h"
300
301/*
drh0ccebe72005-06-07 22:22:50 +0000302** Define various macros that are missing from some systems.
303*/
drhbbd42a62004-05-22 17:41:58 +0000304#ifndef O_LARGEFILE
305# define O_LARGEFILE 0
306#endif
307#ifdef SQLITE_DISABLE_LFS
308# undef O_LARGEFILE
309# define O_LARGEFILE 0
310#endif
311#ifndef O_NOFOLLOW
312# define O_NOFOLLOW 0
313#endif
314#ifndef O_BINARY
315# define O_BINARY 0
316#endif
317
318/*
drh2b4b5962005-06-15 17:47:55 +0000319** The threadid macro resolves to the thread-id or to 0. Used for
320** testing and debugging only.
321*/
drhd677b3d2007-08-20 22:48:41 +0000322#if SQLITE_THREADSAFE
drh2b4b5962005-06-15 17:47:55 +0000323#define threadid pthread_self()
324#else
325#define threadid 0
326#endif
327
drh99ab3b12011-03-02 15:09:07 +0000328/*
dane6ecd662013-04-01 17:56:59 +0000329** HAVE_MREMAP defaults to true on Linux and false everywhere else.
330*/
331#if !defined(HAVE_MREMAP)
332# if defined(__linux__) && defined(_GNU_SOURCE)
333# define HAVE_MREMAP 1
334# else
335# define HAVE_MREMAP 0
336# endif
337#endif
338
339/*
dan2ee53412014-09-06 16:49:40 +0000340** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
341** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
342*/
343#ifdef __ANDROID__
344# define lseek lseek64
345#endif
346
drhd76dba72017-07-22 16:00:34 +0000347#ifdef __linux__
348/*
349** Linux-specific IOCTL magic numbers used for controlling F2FS
350*/
danefe16972017-07-20 19:49:14 +0000351#define F2FS_IOCTL_MAGIC 0xf5
352#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
353#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
354#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
355#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
dan9d709542017-07-21 21:06:24 +0000356#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
dan9d709542017-07-21 21:06:24 +0000357#define F2FS_FEATURE_ATOMIC_WRITE 0x0004
drhd76dba72017-07-22 16:00:34 +0000358#endif /* __linux__ */
danefe16972017-07-20 19:49:14 +0000359
360
dan2ee53412014-09-06 16:49:40 +0000361/*
drh9a3baf12011-04-25 18:01:27 +0000362** Different Unix systems declare open() in different ways. Same use
363** open(const char*,int,mode_t). Others use open(const char*,int,...).
364** The difference is important when using a pointer to the function.
365**
366** The safest way to deal with the problem is to always use this wrapper
367** which always has the same well-defined interface.
368*/
369static int posixOpen(const char *zFile, int flags, int mode){
370 return open(zFile, flags, mode);
371}
372
drh90315a22011-08-10 01:52:12 +0000373/* Forward reference */
374static int openDirectory(const char*, int*);
danbc760632014-03-20 09:42:09 +0000375static int unixGetpagesize(void);
drh90315a22011-08-10 01:52:12 +0000376
drh9a3baf12011-04-25 18:01:27 +0000377/*
drh99ab3b12011-03-02 15:09:07 +0000378** Many system calls are accessed through pointer-to-functions so that
379** they may be overridden at runtime to facilitate fault injection during
380** testing and sandboxing. The following array holds the names and pointers
381** to all overrideable system calls.
382*/
383static struct unix_syscall {
mistachkin48864df2013-03-21 21:20:32 +0000384 const char *zName; /* Name of the system call */
drh58ad5802011-03-23 22:02:23 +0000385 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
386 sqlite3_syscall_ptr pDefault; /* Default value */
drh99ab3b12011-03-02 15:09:07 +0000387} aSyscall[] = {
drh9a3baf12011-04-25 18:01:27 +0000388 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
389#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
drh99ab3b12011-03-02 15:09:07 +0000390
drh58ad5802011-03-23 22:02:23 +0000391 { "close", (sqlite3_syscall_ptr)close, 0 },
drh99ab3b12011-03-02 15:09:07 +0000392#define osClose ((int(*)(int))aSyscall[1].pCurrent)
393
drh58ad5802011-03-23 22:02:23 +0000394 { "access", (sqlite3_syscall_ptr)access, 0 },
drh99ab3b12011-03-02 15:09:07 +0000395#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
396
drh58ad5802011-03-23 22:02:23 +0000397 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
drh99ab3b12011-03-02 15:09:07 +0000398#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
399
drh58ad5802011-03-23 22:02:23 +0000400 { "stat", (sqlite3_syscall_ptr)stat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000401#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
402
403/*
404** The DJGPP compiler environment looks mostly like Unix, but it
405** lacks the fcntl() system call. So redefine fcntl() to be something
406** that always succeeds. This means that locking does not occur under
407** DJGPP. But it is DOS - what did you expect?
408*/
409#ifdef __DJGPP__
410 { "fstat", 0, 0 },
411#define osFstat(a,b,c) 0
412#else
drh58ad5802011-03-23 22:02:23 +0000413 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
drh99ab3b12011-03-02 15:09:07 +0000414#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
415#endif
416
drh58ad5802011-03-23 22:02:23 +0000417 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
drh99ab3b12011-03-02 15:09:07 +0000418#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
419
drh58ad5802011-03-23 22:02:23 +0000420 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
drh99ab3b12011-03-02 15:09:07 +0000421#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
drhe562be52011-03-02 18:01:10 +0000422
drh58ad5802011-03-23 22:02:23 +0000423 { "read", (sqlite3_syscall_ptr)read, 0 },
drhe562be52011-03-02 18:01:10 +0000424#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
425
drhe89b2912015-03-03 20:42:01 +0000426#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000427 { "pread", (sqlite3_syscall_ptr)pread, 0 },
drhe562be52011-03-02 18:01:10 +0000428#else
drh58ad5802011-03-23 22:02:23 +0000429 { "pread", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000430#endif
431#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
432
433#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000434 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
drhe562be52011-03-02 18:01:10 +0000435#else
drh58ad5802011-03-23 22:02:23 +0000436 { "pread64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000437#endif
drhf9986d92016-04-18 13:09:55 +0000438#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
drhe562be52011-03-02 18:01:10 +0000439
drh58ad5802011-03-23 22:02:23 +0000440 { "write", (sqlite3_syscall_ptr)write, 0 },
drhe562be52011-03-02 18:01:10 +0000441#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
442
drhe89b2912015-03-03 20:42:01 +0000443#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
drh58ad5802011-03-23 22:02:23 +0000444 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
drhe562be52011-03-02 18:01:10 +0000445#else
drh58ad5802011-03-23 22:02:23 +0000446 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000447#endif
448#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
449 aSyscall[12].pCurrent)
450
451#if defined(USE_PREAD64)
drh58ad5802011-03-23 22:02:23 +0000452 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
drhe562be52011-03-02 18:01:10 +0000453#else
drh58ad5802011-03-23 22:02:23 +0000454 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000455#endif
drhf9986d92016-04-18 13:09:55 +0000456#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
drhe562be52011-03-02 18:01:10 +0000457 aSyscall[13].pCurrent)
458
drh6226ca22015-11-24 15:06:28 +0000459 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
drh2aa5a002011-04-13 13:42:25 +0000460#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
drhe562be52011-03-02 18:01:10 +0000461
462#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
drh58ad5802011-03-23 22:02:23 +0000463 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
drhe562be52011-03-02 18:01:10 +0000464#else
drh58ad5802011-03-23 22:02:23 +0000465 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
drhe562be52011-03-02 18:01:10 +0000466#endif
dan0fd7d862011-03-29 10:04:23 +0000467#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
drhe562be52011-03-02 18:01:10 +0000468
drh036ac7f2011-08-08 23:18:05 +0000469 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
470#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
471
drh90315a22011-08-10 01:52:12 +0000472 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
473#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
474
drh9ef6bc42011-11-04 02:24:02 +0000475 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
476#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
477
478 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
479#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
480
drhe2258a22016-01-12 00:37:55 +0000481#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000482 { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
drhe2258a22016-01-12 00:37:55 +0000483#else
484 { "fchown", (sqlite3_syscall_ptr)0, 0 },
485#endif
dand3eaebd2012-02-13 08:50:23 +0000486#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
drh23c4b972012-02-11 23:55:15 +0000487
drh26f625f2018-02-19 16:34:31 +0000488#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000489 { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
drh26f625f2018-02-19 16:34:31 +0000490#else
491 { "geteuid", (sqlite3_syscall_ptr)0, 0 },
492#endif
drh6226ca22015-11-24 15:06:28 +0000493#define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
494
dan4dd51442013-08-26 14:30:25 +0000495#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhe4a08f92016-01-08 19:17:30 +0000496 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
497#else
498 { "mmap", (sqlite3_syscall_ptr)0, 0 },
499#endif
drh6226ca22015-11-24 15:06:28 +0000500#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
dan893c0ff2013-03-25 19:05:07 +0000501
drhe4a08f92016-01-08 19:17:30 +0000502#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd1ab8062013-03-25 20:50:25 +0000503 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
drhe4a08f92016-01-08 19:17:30 +0000504#else
drha8299922016-01-08 22:31:00 +0000505 { "munmap", (sqlite3_syscall_ptr)0, 0 },
drhe4a08f92016-01-08 19:17:30 +0000506#endif
drh62be1fa2017-12-09 01:02:33 +0000507#define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
drhd1ab8062013-03-25 20:50:25 +0000508
drhe4a08f92016-01-08 19:17:30 +0000509#if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
drhd1ab8062013-03-25 20:50:25 +0000510 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
511#else
512 { "mremap", (sqlite3_syscall_ptr)0, 0 },
513#endif
drh6226ca22015-11-24 15:06:28 +0000514#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
515
drh24dbeae2016-01-08 22:18:00 +0000516#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
danbc760632014-03-20 09:42:09 +0000517 { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
drh24dbeae2016-01-08 22:18:00 +0000518#else
519 { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
520#endif
drh6226ca22015-11-24 15:06:28 +0000521#define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
danbc760632014-03-20 09:42:09 +0000522
drhe2258a22016-01-12 00:37:55 +0000523#if defined(HAVE_READLINK)
dan245fdc62015-10-31 17:58:33 +0000524 { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
drhe2258a22016-01-12 00:37:55 +0000525#else
526 { "readlink", (sqlite3_syscall_ptr)0, 0 },
527#endif
drh6226ca22015-11-24 15:06:28 +0000528#define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
dan245fdc62015-10-31 17:58:33 +0000529
danaf1b36b2016-01-25 18:43:05 +0000530#if defined(HAVE_LSTAT)
531 { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
532#else
533 { "lstat", (sqlite3_syscall_ptr)0, 0 },
534#endif
dancaf6b152016-01-25 18:05:49 +0000535#define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
dan702eec12014-06-23 10:04:58 +0000536
drhb5d013e2017-10-25 16:14:12 +0000537#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
dan16f39b62018-09-18 19:40:18 +0000538# ifdef __ANDROID__
539 { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
danec9b2a12019-07-15 07:58:28 +0000540#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
dan16f39b62018-09-18 19:40:18 +0000541# else
danefe16972017-07-20 19:49:14 +0000542 { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
danec9b2a12019-07-15 07:58:28 +0000543#define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
dan16f39b62018-09-18 19:40:18 +0000544# endif
drhb5d013e2017-10-25 16:14:12 +0000545#else
546 { "ioctl", (sqlite3_syscall_ptr)0, 0 },
547#endif
danefe16972017-07-20 19:49:14 +0000548
drhe562be52011-03-02 18:01:10 +0000549}; /* End of the overrideable system calls */
drh99ab3b12011-03-02 15:09:07 +0000550
drh6226ca22015-11-24 15:06:28 +0000551
552/*
553** On some systems, calls to fchown() will trigger a message in a security
554** log if they come from non-root processes. So avoid calling fchown() if
555** we are not running as root.
556*/
557static int robustFchown(int fd, uid_t uid, gid_t gid){
drhe2258a22016-01-12 00:37:55 +0000558#if defined(HAVE_FCHOWN)
drh6226ca22015-11-24 15:06:28 +0000559 return osGeteuid() ? 0 : osFchown(fd,uid,gid);
drhe2258a22016-01-12 00:37:55 +0000560#else
561 return 0;
drh6226ca22015-11-24 15:06:28 +0000562#endif
563}
564
drh99ab3b12011-03-02 15:09:07 +0000565/*
566** This is the xSetSystemCall() method of sqlite3_vfs for all of the
drh1df30962011-03-02 19:06:42 +0000567** "unix" VFSes. Return SQLITE_OK opon successfully updating the
568** system call pointer, or SQLITE_NOTFOUND if there is no configurable
569** system call named zName.
drh99ab3b12011-03-02 15:09:07 +0000570*/
571static int unixSetSystemCall(
drh58ad5802011-03-23 22:02:23 +0000572 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
573 const char *zName, /* Name of system call to override */
574 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
drh99ab3b12011-03-02 15:09:07 +0000575){
drh58ad5802011-03-23 22:02:23 +0000576 unsigned int i;
drh1df30962011-03-02 19:06:42 +0000577 int rc = SQLITE_NOTFOUND;
drh58ad5802011-03-23 22:02:23 +0000578
579 UNUSED_PARAMETER(pNotUsed);
drh99ab3b12011-03-02 15:09:07 +0000580 if( zName==0 ){
581 /* If no zName is given, restore all system calls to their default
582 ** settings and return NULL
583 */
dan51438a72011-04-02 17:00:47 +0000584 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000585 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
586 if( aSyscall[i].pDefault ){
587 aSyscall[i].pCurrent = aSyscall[i].pDefault;
drh99ab3b12011-03-02 15:09:07 +0000588 }
589 }
590 }else{
591 /* If zName is specified, operate on only the one system call
592 ** specified.
593 */
594 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
595 if( strcmp(zName, aSyscall[i].zName)==0 ){
596 if( aSyscall[i].pDefault==0 ){
597 aSyscall[i].pDefault = aSyscall[i].pCurrent;
598 }
drh1df30962011-03-02 19:06:42 +0000599 rc = SQLITE_OK;
drh99ab3b12011-03-02 15:09:07 +0000600 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
601 aSyscall[i].pCurrent = pNewFunc;
602 break;
603 }
604 }
605 }
606 return rc;
607}
608
drh1df30962011-03-02 19:06:42 +0000609/*
610** Return the value of a system call. Return NULL if zName is not a
611** recognized system call name. NULL is also returned if the system call
612** is currently undefined.
613*/
drh58ad5802011-03-23 22:02:23 +0000614static sqlite3_syscall_ptr unixGetSystemCall(
615 sqlite3_vfs *pNotUsed,
616 const char *zName
617){
618 unsigned int i;
619
620 UNUSED_PARAMETER(pNotUsed);
drh1df30962011-03-02 19:06:42 +0000621 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
622 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
623 }
624 return 0;
625}
626
627/*
628** Return the name of the first system call after zName. If zName==NULL
629** then return the name of the first system call. Return NULL if zName
630** is the last system call or if zName is not the name of a valid
631** system call.
632*/
633static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
dan0fd7d862011-03-29 10:04:23 +0000634 int i = -1;
drh58ad5802011-03-23 22:02:23 +0000635
636 UNUSED_PARAMETER(p);
dan0fd7d862011-03-29 10:04:23 +0000637 if( zName ){
638 for(i=0; i<ArraySize(aSyscall)-1; i++){
639 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
drh1df30962011-03-02 19:06:42 +0000640 }
641 }
dan0fd7d862011-03-29 10:04:23 +0000642 for(i++; i<ArraySize(aSyscall); i++){
643 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
drh1df30962011-03-02 19:06:42 +0000644 }
645 return 0;
646}
647
drhad4f1e52011-03-04 15:43:57 +0000648/*
drh77a3fdc2013-08-30 14:24:12 +0000649** Do not accept any file descriptor less than this value, in order to avoid
650** opening database file using file descriptors that are commonly used for
651** standard input, output, and error.
652*/
653#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
654# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
655#endif
656
657/*
drh8c815d12012-02-13 20:16:37 +0000658** Invoke open(). Do so multiple times, until it either succeeds or
drh5adc60b2012-04-14 13:25:11 +0000659** fails for some reason other than EINTR.
drh8c815d12012-02-13 20:16:37 +0000660**
661** If the file creation mode "m" is 0 then set it to the default for
662** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
663** 0644) as modified by the system umask. If m is not 0, then
664** make the file creation mode be exactly m ignoring the umask.
665**
666** The m parameter will be non-zero only when creating -wal, -journal,
667** and -shm files. We want those files to have *exactly* the same
668** permissions as their original database, unadulterated by the umask.
669** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
670** transaction crashes and leaves behind hot journals, then any
671** process that is able to write to the database will also be able to
672** recover the hot journals.
drhad4f1e52011-03-04 15:43:57 +0000673*/
drh8c815d12012-02-13 20:16:37 +0000674static int robust_open(const char *z, int f, mode_t m){
drh5adc60b2012-04-14 13:25:11 +0000675 int fd;
drhe1186ab2013-01-04 20:45:13 +0000676 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
drh5128d002013-08-30 06:20:23 +0000677 while(1){
drh5adc60b2012-04-14 13:25:11 +0000678#if defined(O_CLOEXEC)
679 fd = osOpen(z,f|O_CLOEXEC,m2);
680#else
681 fd = osOpen(z,f,m2);
682#endif
drh5128d002013-08-30 06:20:23 +0000683 if( fd<0 ){
684 if( errno==EINTR ) continue;
685 break;
686 }
drh77a3fdc2013-08-30 14:24:12 +0000687 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
drh5128d002013-08-30 06:20:23 +0000688 osClose(fd);
689 sqlite3_log(SQLITE_WARNING,
690 "attempt to open \"%s\" as file descriptor %d", z, fd);
691 fd = -1;
drh0ba36212020-02-13 13:45:04 +0000692 if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
drh5128d002013-08-30 06:20:23 +0000693 }
drhe1186ab2013-01-04 20:45:13 +0000694 if( fd>=0 ){
695 if( m!=0 ){
696 struct stat statbuf;
danb83c21e2013-03-05 15:27:34 +0000697 if( osFstat(fd, &statbuf)==0
698 && statbuf.st_size==0
drhcfc17692013-03-06 01:41:53 +0000699 && (statbuf.st_mode&0777)!=m
danb83c21e2013-03-05 15:27:34 +0000700 ){
drhe1186ab2013-01-04 20:45:13 +0000701 osFchmod(fd, m);
702 }
703 }
drh5adc60b2012-04-14 13:25:11 +0000704#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
drhe1186ab2013-01-04 20:45:13 +0000705 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
drh5adc60b2012-04-14 13:25:11 +0000706#endif
drhe1186ab2013-01-04 20:45:13 +0000707 }
drh5adc60b2012-04-14 13:25:11 +0000708 return fd;
drhad4f1e52011-03-04 15:43:57 +0000709}
danielk197713adf8a2004-06-03 16:08:41 +0000710
drh107886a2008-11-21 22:21:50 +0000711/*
dan9359c7b2009-08-21 08:29:10 +0000712** Helper functions to obtain and relinquish the global mutex. The
drh8af6c222010-05-14 12:43:01 +0000713** global mutex is used to protect the unixInodeInfo and
dan9359c7b2009-08-21 08:29:10 +0000714** vxworksFileId objects used by this file, all of which may be
715** shared by multiple threads.
716**
717** Function unixMutexHeld() is used to assert() that the global mutex
718** is held when required. This function is only used as part of assert()
719** statements. e.g.
720**
721** unixEnterMutex()
722** assert( unixMutexHeld() );
723** unixEnterLeave()
drh095908e2018-08-13 20:46:18 +0000724**
725** To prevent deadlock, the global unixBigLock must must be acquired
726** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
727** OK to get the pLockMutex without holding unixBigLock first, but if
728** that happens, the unixBigLock mutex must not be acquired until after
729** pLockMutex is released.
730**
731** OK: enter(unixBigLock), enter(pLockInfo)
732** OK: enter(unixBigLock)
733** OK: enter(pLockInfo)
734** ERROR: enter(pLockInfo), enter(unixBigLock)
drh107886a2008-11-21 22:21:50 +0000735*/
drh56115892018-02-05 16:39:12 +0000736static sqlite3_mutex *unixBigLock = 0;
drh107886a2008-11-21 22:21:50 +0000737static void unixEnterMutex(void){
drh095908e2018-08-13 20:46:18 +0000738 assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
drh56115892018-02-05 16:39:12 +0000739 sqlite3_mutex_enter(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000740}
741static void unixLeaveMutex(void){
drh095908e2018-08-13 20:46:18 +0000742 assert( sqlite3_mutex_held(unixBigLock) );
drh56115892018-02-05 16:39:12 +0000743 sqlite3_mutex_leave(unixBigLock);
drh107886a2008-11-21 22:21:50 +0000744}
dan9359c7b2009-08-21 08:29:10 +0000745#ifdef SQLITE_DEBUG
746static int unixMutexHeld(void) {
drh56115892018-02-05 16:39:12 +0000747 return sqlite3_mutex_held(unixBigLock);
dan9359c7b2009-08-21 08:29:10 +0000748}
749#endif
drh107886a2008-11-21 22:21:50 +0000750
drh734c9862008-11-28 15:37:20 +0000751
mistachkinfb383e92015-04-16 03:24:38 +0000752#ifdef SQLITE_HAVE_OS_TRACE
drh734c9862008-11-28 15:37:20 +0000753/*
754** Helper function for printing out trace information from debugging
peter.d.reid60ec9142014-09-06 16:39:46 +0000755** binaries. This returns the string representation of the supplied
drh734c9862008-11-28 15:37:20 +0000756** integer lock-type.
757*/
drh308c2a52010-05-14 11:30:18 +0000758static const char *azFileLock(int eFileLock){
759 switch( eFileLock ){
dan9359c7b2009-08-21 08:29:10 +0000760 case NO_LOCK: return "NONE";
761 case SHARED_LOCK: return "SHARED";
762 case RESERVED_LOCK: return "RESERVED";
763 case PENDING_LOCK: return "PENDING";
764 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
drh734c9862008-11-28 15:37:20 +0000765 }
766 return "ERROR";
767}
768#endif
769
770#ifdef SQLITE_LOCK_TRACE
771/*
772** Print out information about all locking operations.
drh6c7d5c52008-11-21 20:32:33 +0000773**
drh734c9862008-11-28 15:37:20 +0000774** This routine is used for troubleshooting locks on multithreaded
775** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
776** command-line option on the compiler. This code is normally
777** turned off.
778*/
779static int lockTrace(int fd, int op, struct flock *p){
780 char *zOpName, *zType;
781 int s;
782 int savedErrno;
783 if( op==F_GETLK ){
784 zOpName = "GETLK";
785 }else if( op==F_SETLK ){
786 zOpName = "SETLK";
787 }else{
drh99ab3b12011-03-02 15:09:07 +0000788 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000789 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
790 return s;
791 }
792 if( p->l_type==F_RDLCK ){
793 zType = "RDLCK";
794 }else if( p->l_type==F_WRLCK ){
795 zType = "WRLCK";
796 }else if( p->l_type==F_UNLCK ){
797 zType = "UNLCK";
798 }else{
799 assert( 0 );
800 }
801 assert( p->l_whence==SEEK_SET );
drh99ab3b12011-03-02 15:09:07 +0000802 s = osFcntl(fd, op, p);
drh734c9862008-11-28 15:37:20 +0000803 savedErrno = errno;
804 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
805 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
806 (int)p->l_pid, s);
807 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
808 struct flock l2;
809 l2 = *p;
drh99ab3b12011-03-02 15:09:07 +0000810 osFcntl(fd, F_GETLK, &l2);
drh734c9862008-11-28 15:37:20 +0000811 if( l2.l_type==F_RDLCK ){
812 zType = "RDLCK";
813 }else if( l2.l_type==F_WRLCK ){
814 zType = "WRLCK";
815 }else if( l2.l_type==F_UNLCK ){
816 zType = "UNLCK";
817 }else{
818 assert( 0 );
819 }
820 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
821 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
822 }
823 errno = savedErrno;
824 return s;
825}
drh99ab3b12011-03-02 15:09:07 +0000826#undef osFcntl
827#define osFcntl lockTrace
drh734c9862008-11-28 15:37:20 +0000828#endif /* SQLITE_LOCK_TRACE */
829
drhff812312011-02-23 13:33:46 +0000830/*
831** Retry ftruncate() calls that fail due to EINTR
dan2ee53412014-09-06 16:49:40 +0000832**
drhe6d41732015-02-21 00:49:00 +0000833** All calls to ftruncate() within this file should be made through
834** this wrapper. On the Android platform, bypassing the logic below
835** could lead to a corrupt database.
drhff812312011-02-23 13:33:46 +0000836*/
drhff812312011-02-23 13:33:46 +0000837static int robust_ftruncate(int h, sqlite3_int64 sz){
838 int rc;
dan2ee53412014-09-06 16:49:40 +0000839#ifdef __ANDROID__
840 /* On Android, ftruncate() always uses 32-bit offsets, even if
841 ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
dan524a7332014-09-06 17:06:13 +0000842 ** truncate a file to any size larger than 2GiB. Silently ignore any
dan2ee53412014-09-06 16:49:40 +0000843 ** such attempts. */
844 if( sz>(sqlite3_int64)0x7FFFFFFF ){
845 rc = SQLITE_OK;
846 }else
847#endif
drh99ab3b12011-03-02 15:09:07 +0000848 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
drhff812312011-02-23 13:33:46 +0000849 return rc;
850}
drh734c9862008-11-28 15:37:20 +0000851
852/*
853** This routine translates a standard POSIX errno code into something
854** useful to the clients of the sqlite3 functions. Specifically, it is
855** intended to translate a variety of "try again" errors into SQLITE_BUSY
856** and a variety of "please close the file descriptor NOW" errors into
857** SQLITE_IOERR
858**
859** Errors during initialization of locks, or file system support for locks,
860** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
861*/
862static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
drh91c4def2015-11-25 14:00:07 +0000863 assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
864 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
865 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
866 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
drh734c9862008-11-28 15:37:20 +0000867 switch (posixError) {
drh91c4def2015-11-25 14:00:07 +0000868 case EACCES:
drh734c9862008-11-28 15:37:20 +0000869 case EAGAIN:
870 case ETIMEDOUT:
871 case EBUSY:
872 case EINTR:
873 case ENOLCK:
874 /* random NFS retry error, unless during file system support
875 * introspection, in which it actually means what it says */
876 return SQLITE_BUSY;
877
drh734c9862008-11-28 15:37:20 +0000878 case EPERM:
879 return SQLITE_PERM;
880
drh734c9862008-11-28 15:37:20 +0000881 default:
882 return sqliteIOErr;
883 }
884}
885
886
drh734c9862008-11-28 15:37:20 +0000887/******************************************************************************
888****************** Begin Unique File ID Utility Used By VxWorks ***************
889**
890** On most versions of unix, we can get a unique ID for a file by concatenating
891** the device number and the inode number. But this does not work on VxWorks.
892** On VxWorks, a unique file id must be based on the canonical filename.
893**
894** A pointer to an instance of the following structure can be used as a
895** unique file ID in VxWorks. Each instance of this structure contains
896** a copy of the canonical filename. There is also a reference count.
897** The structure is reclaimed when the number of pointers to it drops to
898** zero.
899**
900** There are never very many files open at one time and lookups are not
901** a performance-critical path, so it is sufficient to put these
902** structures on a linked list.
903*/
904struct vxworksFileId {
905 struct vxworksFileId *pNext; /* Next in a list of them all */
906 int nRef; /* Number of references to this one */
907 int nName; /* Length of the zCanonicalName[] string */
908 char *zCanonicalName; /* Canonical filename */
909};
910
911#if OS_VXWORKS
912/*
drh9b35ea62008-11-29 02:20:26 +0000913** All unique filenames are held on a linked list headed by this
drh734c9862008-11-28 15:37:20 +0000914** variable:
915*/
916static struct vxworksFileId *vxworksFileList = 0;
917
918/*
919** Simplify a filename into its canonical form
920** by making the following changes:
921**
922** * removing any trailing and duplicate /
drh9b35ea62008-11-29 02:20:26 +0000923** * convert /./ into just /
924** * convert /A/../ where A is any simple name into just /
drh734c9862008-11-28 15:37:20 +0000925**
926** Changes are made in-place. Return the new name length.
927**
928** The original filename is in z[0..n-1]. Return the number of
929** characters in the simplified name.
930*/
931static int vxworksSimplifyName(char *z, int n){
932 int i, j;
933 while( n>1 && z[n-1]=='/' ){ n--; }
934 for(i=j=0; i<n; i++){
935 if( z[i]=='/' ){
936 if( z[i+1]=='/' ) continue;
937 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
938 i += 1;
939 continue;
940 }
941 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
942 while( j>0 && z[j-1]!='/' ){ j--; }
943 if( j>0 ){ j--; }
944 i += 2;
945 continue;
946 }
947 }
948 z[j++] = z[i];
949 }
950 z[j] = 0;
951 return j;
952}
953
954/*
955** Find a unique file ID for the given absolute pathname. Return
956** a pointer to the vxworksFileId object. This pointer is the unique
957** file ID.
958**
959** The nRef field of the vxworksFileId object is incremented before
960** the object is returned. A new vxworksFileId object is created
961** and added to the global list if necessary.
962**
963** If a memory allocation error occurs, return NULL.
964*/
965static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
966 struct vxworksFileId *pNew; /* search key and new file ID */
967 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
968 int n; /* Length of zAbsoluteName string */
969
970 assert( zAbsoluteName[0]=='/' );
drhea678832008-12-10 19:26:22 +0000971 n = (int)strlen(zAbsoluteName);
drhf3cdcdc2015-04-29 16:50:28 +0000972 pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
drh734c9862008-11-28 15:37:20 +0000973 if( pNew==0 ) return 0;
974 pNew->zCanonicalName = (char*)&pNew[1];
975 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
976 n = vxworksSimplifyName(pNew->zCanonicalName, n);
977
978 /* Search for an existing entry that matching the canonical name.
979 ** If found, increment the reference count and return a pointer to
980 ** the existing file ID.
981 */
982 unixEnterMutex();
983 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
984 if( pCandidate->nName==n
985 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
986 ){
987 sqlite3_free(pNew);
988 pCandidate->nRef++;
989 unixLeaveMutex();
990 return pCandidate;
991 }
992 }
993
994 /* No match was found. We will make a new file ID */
995 pNew->nRef = 1;
996 pNew->nName = n;
997 pNew->pNext = vxworksFileList;
998 vxworksFileList = pNew;
999 unixLeaveMutex();
1000 return pNew;
1001}
1002
1003/*
1004** Decrement the reference count on a vxworksFileId object. Free
1005** the object when the reference count reaches zero.
1006*/
1007static void vxworksReleaseFileId(struct vxworksFileId *pId){
1008 unixEnterMutex();
1009 assert( pId->nRef>0 );
1010 pId->nRef--;
1011 if( pId->nRef==0 ){
1012 struct vxworksFileId **pp;
1013 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
1014 assert( *pp==pId );
1015 *pp = pId->pNext;
1016 sqlite3_free(pId);
1017 }
1018 unixLeaveMutex();
1019}
1020#endif /* OS_VXWORKS */
1021/*************** End of Unique File ID Utility Used By VxWorks ****************
1022******************************************************************************/
1023
1024
1025/******************************************************************************
1026*************************** Posix Advisory Locking ****************************
1027**
drh9b35ea62008-11-29 02:20:26 +00001028** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
drhbbd42a62004-05-22 17:41:58 +00001029** section 6.5.2.2 lines 483 through 490 specify that when a process
1030** sets or clears a lock, that operation overrides any prior locks set
1031** by the same process. It does not explicitly say so, but this implies
1032** that it overrides locks set by the same process using a different
1033** file descriptor. Consider this test case:
drh6c7d5c52008-11-21 20:32:33 +00001034**
1035** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
drhbbd42a62004-05-22 17:41:58 +00001036** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
1037**
1038** Suppose ./file1 and ./file2 are really the same file (because
1039** one is a hard or symbolic link to the other) then if you set
1040** an exclusive lock on fd1, then try to get an exclusive lock
1041** on fd2, it works. I would have expected the second lock to
1042** fail since there was already a lock on the file due to fd1.
1043** But not so. Since both locks came from the same process, the
1044** second overrides the first, even though they were on different
1045** file descriptors opened on different file names.
1046**
drh734c9862008-11-28 15:37:20 +00001047** This means that we cannot use POSIX locks to synchronize file access
1048** among competing threads of the same process. POSIX locks will work fine
drhbbd42a62004-05-22 17:41:58 +00001049** to synchronize access for threads in separate processes, but not
1050** threads within the same process.
1051**
1052** To work around the problem, SQLite has to manage file locks internally
1053** on its own. Whenever a new database is opened, we have to find the
1054** specific inode of the database file (the inode is determined by the
1055** st_dev and st_ino fields of the stat structure that fstat() fills in)
1056** and check for locks already existing on that inode. When locks are
1057** created or removed, we have to look at our own internal record of the
1058** locks to see if another thread has previously set a lock on that same
1059** inode.
1060**
drh9b35ea62008-11-29 02:20:26 +00001061** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
1062** For VxWorks, we have to use the alternative unique ID system based on
1063** canonical filename and implemented in the previous division.)
1064**
danielk1977ad94b582007-08-20 06:44:22 +00001065** The sqlite3_file structure for POSIX is no longer just an integer file
drhbbd42a62004-05-22 17:41:58 +00001066** descriptor. It is now a structure that holds the integer file
1067** descriptor and a pointer to a structure that describes the internal
1068** locks on the corresponding inode. There is one locking structure
danielk1977ad94b582007-08-20 06:44:22 +00001069** per inode, so if the same inode is opened twice, both unixFile structures
drhbbd42a62004-05-22 17:41:58 +00001070** point to the same locking structure. The locking structure keeps
1071** a reference count (so we will know when to delete it) and a "cnt"
1072** field that tells us its internal lock status. cnt==0 means the
1073** file is unlocked. cnt==-1 means the file has an exclusive lock.
1074** cnt>0 means there are cnt shared locks on the file.
1075**
1076** Any attempt to lock or unlock a file first checks the locking
1077** structure. The fcntl() system call is only invoked to set a
1078** POSIX lock if the internal lock structure transitions between
1079** a locked and an unlocked state.
1080**
drh734c9862008-11-28 15:37:20 +00001081** But wait: there are yet more problems with POSIX advisory locks.
drhbbd42a62004-05-22 17:41:58 +00001082**
1083** If you close a file descriptor that points to a file that has locks,
1084** all locks on that file that are owned by the current process are
drh8af6c222010-05-14 12:43:01 +00001085** released. To work around this problem, each unixInodeInfo object
1086** maintains a count of the number of pending locks on tha inode.
1087** When an attempt is made to close an unixFile, if there are
danielk1977ad94b582007-08-20 06:44:22 +00001088** other unixFile open on the same inode that are holding locks, the call
drhbbd42a62004-05-22 17:41:58 +00001089** to close() the file descriptor is deferred until all of the locks clear.
drh8af6c222010-05-14 12:43:01 +00001090** The unixInodeInfo structure keeps a list of file descriptors that need to
drhbbd42a62004-05-22 17:41:58 +00001091** be closed and that list is walked (and cleared) when the last lock
1092** clears.
1093**
drh9b35ea62008-11-29 02:20:26 +00001094** Yet another problem: LinuxThreads do not play well with posix locks.
drh5fdae772004-06-29 03:29:00 +00001095**
drh9b35ea62008-11-29 02:20:26 +00001096** Many older versions of linux use the LinuxThreads library which is
1097** not posix compliant. Under LinuxThreads, a lock created by thread
drh734c9862008-11-28 15:37:20 +00001098** A cannot be modified or overridden by a different thread B.
1099** Only thread A can modify the lock. Locking behavior is correct
1100** if the appliation uses the newer Native Posix Thread Library (NPTL)
1101** on linux - with NPTL a lock created by thread A can override locks
1102** in thread B. But there is no way to know at compile-time which
1103** threading library is being used. So there is no way to know at
1104** compile-time whether or not thread A can override locks on thread B.
drh8af6c222010-05-14 12:43:01 +00001105** One has to do a run-time check to discover the behavior of the
drh734c9862008-11-28 15:37:20 +00001106** current process.
drh5fdae772004-06-29 03:29:00 +00001107**
drh8af6c222010-05-14 12:43:01 +00001108** SQLite used to support LinuxThreads. But support for LinuxThreads
1109** was dropped beginning with version 3.7.0. SQLite will still work with
1110** LinuxThreads provided that (1) there is no more than one connection
1111** per database file in the same process and (2) database connections
1112** do not move across threads.
drhbbd42a62004-05-22 17:41:58 +00001113*/
1114
1115/*
1116** An instance of the following structure serves as the key used
drh8af6c222010-05-14 12:43:01 +00001117** to locate a particular unixInodeInfo object.
drh6c7d5c52008-11-21 20:32:33 +00001118*/
1119struct unixFileId {
drh107886a2008-11-21 22:21:50 +00001120 dev_t dev; /* Device number */
drh6c7d5c52008-11-21 20:32:33 +00001121#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00001122 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
drh6c7d5c52008-11-21 20:32:33 +00001123#else
drh25ef7f52016-12-05 20:06:45 +00001124 /* We are told that some versions of Android contain a bug that
1125 ** sizes ino_t at only 32-bits instead of 64-bits. (See
1126 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
1127 ** To work around this, always allocate 64-bits for the inode number.
1128 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
1129 ** but that should not be a big deal. */
1130 /* WAS: ino_t ino; */
1131 u64 ino; /* Inode number */
drh6c7d5c52008-11-21 20:32:33 +00001132#endif
1133};
1134
1135/*
drhbbd42a62004-05-22 17:41:58 +00001136** An instance of the following structure is allocated for each open
drh24efa542018-10-02 19:36:40 +00001137** inode.
drhbbd42a62004-05-22 17:41:58 +00001138**
danielk1977ad94b582007-08-20 06:44:22 +00001139** A single inode can have multiple file descriptors, so each unixFile
drhbbd42a62004-05-22 17:41:58 +00001140** structure contains a pointer to an instance of this object and this
danielk1977ad94b582007-08-20 06:44:22 +00001141** object keeps a count of the number of unixFile pointing to it.
drhda6dc242018-07-23 21:10:37 +00001142**
1143** Mutex rules:
1144**
drh095908e2018-08-13 20:46:18 +00001145** (1) Only the pLockMutex mutex must be held in order to read or write
drhda6dc242018-07-23 21:10:37 +00001146** any of the locking fields:
drhef52b362018-08-13 22:50:34 +00001147** nShared, nLock, eFileLock, bProcessLock, pUnused
drhda6dc242018-07-23 21:10:37 +00001148**
1149** (2) When nRef>0, then the following fields are unchanging and can
1150** be read (but not written) without holding any mutex:
1151** fileId, pLockMutex
1152**
drhef52b362018-08-13 22:50:34 +00001153** (3) With the exceptions above, all the fields may only be read
drhda6dc242018-07-23 21:10:37 +00001154** or written while holding the global unixBigLock mutex.
drh095908e2018-08-13 20:46:18 +00001155**
1156** Deadlock prevention: The global unixBigLock mutex may not
1157** be acquired while holding the pLockMutex mutex. If both unixBigLock
1158** and pLockMutex are needed, then unixBigLock must be acquired first.
drhbbd42a62004-05-22 17:41:58 +00001159*/
drh8af6c222010-05-14 12:43:01 +00001160struct unixInodeInfo {
1161 struct unixFileId fileId; /* The lookup key */
drhda6dc242018-07-23 21:10:37 +00001162 sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
1163 int nShared; /* Number of SHARED locks held */
1164 int nLock; /* Number of outstanding file locks */
1165 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
1166 unsigned char bProcessLock; /* An exclusive process lock is held */
drhef52b362018-08-13 22:50:34 +00001167 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
drh734c9862008-11-28 15:37:20 +00001168 int nRef; /* Number of pointers to this structure */
drhd91c68f2010-05-14 14:52:25 +00001169 unixShmNode *pShmNode; /* Shared memory associated with this inode */
drhd91c68f2010-05-14 14:52:25 +00001170 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
1171 unixInodeInfo *pPrev; /* .... doubly linked */
drhd4a80312011-04-15 14:33:20 +00001172#if SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001173 unsigned long long sharedByte; /* for AFP simulated shared lock */
1174#endif
drh6c7d5c52008-11-21 20:32:33 +00001175#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001176 sem_t *pSem; /* Named POSIX semaphore */
1177 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
chw97185482008-11-17 08:05:31 +00001178#endif
drhbbd42a62004-05-22 17:41:58 +00001179};
1180
drhda0e7682008-07-30 15:27:54 +00001181/*
drh8af6c222010-05-14 12:43:01 +00001182** A lists of all unixInodeInfo objects.
drh24efa542018-10-02 19:36:40 +00001183**
1184** Must hold unixBigLock in order to read or write this variable.
drhbbd42a62004-05-22 17:41:58 +00001185*/
drhc68886b2017-08-18 16:09:52 +00001186static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
drh095908e2018-08-13 20:46:18 +00001187
1188#ifdef SQLITE_DEBUG
1189/*
drh24efa542018-10-02 19:36:40 +00001190** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
1191** This routine is used only within assert() to help verify correct mutex
1192** usage.
drh095908e2018-08-13 20:46:18 +00001193*/
1194int unixFileMutexHeld(unixFile *pFile){
1195 assert( pFile->pInode );
1196 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
1197}
1198int unixFileMutexNotheld(unixFile *pFile){
1199 assert( pFile->pInode );
1200 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
1201}
1202#endif
drh5fdae772004-06-29 03:29:00 +00001203
drh5fdae772004-06-29 03:29:00 +00001204/*
dane18d4952011-02-21 11:46:24 +00001205**
drhaaeaa182015-11-24 15:12:47 +00001206** This function - unixLogErrorAtLine(), is only ever called via the macro
dane18d4952011-02-21 11:46:24 +00001207** unixLogError().
1208**
1209** It is invoked after an error occurs in an OS function and errno has been
1210** set. It logs a message using sqlite3_log() containing the current value of
1211** errno and, if possible, the human-readable equivalent from strerror() or
1212** strerror_r().
1213**
1214** The first argument passed to the macro should be the error code that
1215** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
1216** The two subsequent arguments should be the name of the OS function that
mistachkind5578432012-08-25 10:01:29 +00001217** failed (e.g. "unlink", "open") and the associated file-system path,
dane18d4952011-02-21 11:46:24 +00001218** if any.
1219*/
drh0e9365c2011-03-02 02:08:13 +00001220#define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
1221static int unixLogErrorAtLine(
dane18d4952011-02-21 11:46:24 +00001222 int errcode, /* SQLite error code */
1223 const char *zFunc, /* Name of OS function that failed */
1224 const char *zPath, /* File path associated with error */
1225 int iLine /* Source line number where error occurred */
1226){
1227 char *zErr; /* Message from strerror() or equivalent */
drh0e9365c2011-03-02 02:08:13 +00001228 int iErrno = errno; /* Saved syscall error number */
dane18d4952011-02-21 11:46:24 +00001229
1230 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
1231 ** the strerror() function to obtain the human-readable error message
1232 ** equivalent to errno. Otherwise, use strerror_r().
1233 */
1234#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
1235 char aErr[80];
1236 memset(aErr, 0, sizeof(aErr));
1237 zErr = aErr;
1238
1239 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
mistachkind5578432012-08-25 10:01:29 +00001240 ** assume that the system provides the GNU version of strerror_r() that
dane18d4952011-02-21 11:46:24 +00001241 ** returns a pointer to a buffer containing the error message. That pointer
1242 ** may point to aErr[], or it may point to some static storage somewhere.
1243 ** Otherwise, assume that the system provides the POSIX version of
1244 ** strerror_r(), which always writes an error message into aErr[].
1245 **
1246 ** If the code incorrectly assumes that it is the POSIX version that is
1247 ** available, the error message will often be an empty string. Not a
1248 ** huge problem. Incorrectly concluding that the GNU version is available
1249 ** could lead to a segfault though.
1250 */
1251#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
1252 zErr =
1253# endif
drh0e9365c2011-03-02 02:08:13 +00001254 strerror_r(iErrno, aErr, sizeof(aErr)-1);
dane18d4952011-02-21 11:46:24 +00001255
1256#elif SQLITE_THREADSAFE
1257 /* This is a threadsafe build, but strerror_r() is not available. */
1258 zErr = "";
1259#else
1260 /* Non-threadsafe build, use strerror(). */
drh0e9365c2011-03-02 02:08:13 +00001261 zErr = strerror(iErrno);
dane18d4952011-02-21 11:46:24 +00001262#endif
1263
drh0e9365c2011-03-02 02:08:13 +00001264 if( zPath==0 ) zPath = "";
dane18d4952011-02-21 11:46:24 +00001265 sqlite3_log(errcode,
drh0e9365c2011-03-02 02:08:13 +00001266 "os_unix.c:%d: (%d) %s(%s) - %s",
1267 iLine, iErrno, zFunc, zPath, zErr
dane18d4952011-02-21 11:46:24 +00001268 );
1269
1270 return errcode;
1271}
1272
drh0e9365c2011-03-02 02:08:13 +00001273/*
1274** Close a file descriptor.
1275**
1276** We assume that close() almost always works, since it is only in a
1277** very sick application or on a very sick platform that it might fail.
1278** If it does fail, simply leak the file descriptor, but do log the
1279** error.
1280**
1281** Note that it is not safe to retry close() after EINTR since the
1282** file descriptor might have already been reused by another thread.
1283** So we don't even try to recover from an EINTR. Just log the error
1284** and move on.
1285*/
1286static void robust_close(unixFile *pFile, int h, int lineno){
drh99ab3b12011-03-02 15:09:07 +00001287 if( osClose(h) ){
drh0e9365c2011-03-02 02:08:13 +00001288 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
1289 pFile ? pFile->zPath : 0, lineno);
1290 }
1291}
dane18d4952011-02-21 11:46:24 +00001292
1293/*
drhe6d41732015-02-21 00:49:00 +00001294** Set the pFile->lastErrno. Do this in a subroutine as that provides
1295** a convenient place to set a breakpoint.
drh4bf66fd2015-02-19 02:43:02 +00001296*/
1297static void storeLastErrno(unixFile *pFile, int error){
1298 pFile->lastErrno = error;
1299}
1300
1301/*
danb0ac3e32010-06-16 10:55:42 +00001302** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
danb0ac3e32010-06-16 10:55:42 +00001303*/
drh0e9365c2011-03-02 02:08:13 +00001304static void closePendingFds(unixFile *pFile){
danb0ac3e32010-06-16 10:55:42 +00001305 unixInodeInfo *pInode = pFile->pInode;
danb0ac3e32010-06-16 10:55:42 +00001306 UnixUnusedFd *p;
1307 UnixUnusedFd *pNext;
drhef52b362018-08-13 22:50:34 +00001308 assert( unixFileMutexHeld(pFile) );
danb0ac3e32010-06-16 10:55:42 +00001309 for(p=pInode->pUnused; p; p=pNext){
1310 pNext = p->pNext;
drh0e9365c2011-03-02 02:08:13 +00001311 robust_close(pFile, p->fd, __LINE__);
1312 sqlite3_free(p);
danb0ac3e32010-06-16 10:55:42 +00001313 }
drh0e9365c2011-03-02 02:08:13 +00001314 pInode->pUnused = 0;
danb0ac3e32010-06-16 10:55:42 +00001315}
1316
1317/*
drh8af6c222010-05-14 12:43:01 +00001318** Release a unixInodeInfo structure previously allocated by findInodeInfo().
dan9359c7b2009-08-21 08:29:10 +00001319**
drh24efa542018-10-02 19:36:40 +00001320** The global mutex must be held when this routine is called, but the mutex
1321** on the inode being deleted must NOT be held.
drh6c7d5c52008-11-21 20:32:33 +00001322*/
danb0ac3e32010-06-16 10:55:42 +00001323static void releaseInodeInfo(unixFile *pFile){
1324 unixInodeInfo *pInode = pFile->pInode;
dan9359c7b2009-08-21 08:29:10 +00001325 assert( unixMutexHeld() );
drh095908e2018-08-13 20:46:18 +00001326 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00001327 if( ALWAYS(pInode) ){
drh8af6c222010-05-14 12:43:01 +00001328 pInode->nRef--;
1329 if( pInode->nRef==0 ){
drhd91c68f2010-05-14 14:52:25 +00001330 assert( pInode->pShmNode==0 );
drhef52b362018-08-13 22:50:34 +00001331 sqlite3_mutex_enter(pInode->pLockMutex);
danb0ac3e32010-06-16 10:55:42 +00001332 closePendingFds(pFile);
drhef52b362018-08-13 22:50:34 +00001333 sqlite3_mutex_leave(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001334 if( pInode->pPrev ){
1335 assert( pInode->pPrev->pNext==pInode );
1336 pInode->pPrev->pNext = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001337 }else{
drh8af6c222010-05-14 12:43:01 +00001338 assert( inodeList==pInode );
1339 inodeList = pInode->pNext;
drhda0e7682008-07-30 15:27:54 +00001340 }
drh8af6c222010-05-14 12:43:01 +00001341 if( pInode->pNext ){
1342 assert( pInode->pNext->pPrev==pInode );
1343 pInode->pNext->pPrev = pInode->pPrev;
drhda0e7682008-07-30 15:27:54 +00001344 }
drhda6dc242018-07-23 21:10:37 +00001345 sqlite3_mutex_free(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001346 sqlite3_free(pInode);
danielk1977e339d652008-06-28 11:23:00 +00001347 }
drhbbd42a62004-05-22 17:41:58 +00001348 }
1349}
1350
1351/*
drh8af6c222010-05-14 12:43:01 +00001352** Given a file descriptor, locate the unixInodeInfo object that
1353** describes that file descriptor. Create a new one if necessary. The
1354** return value might be uninitialized if an error occurs.
drh6c7d5c52008-11-21 20:32:33 +00001355**
drh24efa542018-10-02 19:36:40 +00001356** The global mutex must held when calling this routine.
dan9359c7b2009-08-21 08:29:10 +00001357**
drh6c7d5c52008-11-21 20:32:33 +00001358** Return an appropriate error code.
1359*/
drh8af6c222010-05-14 12:43:01 +00001360static int findInodeInfo(
drh6c7d5c52008-11-21 20:32:33 +00001361 unixFile *pFile, /* Unix file with file desc used in the key */
drhd91c68f2010-05-14 14:52:25 +00001362 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
drh6c7d5c52008-11-21 20:32:33 +00001363){
1364 int rc; /* System call return code */
1365 int fd; /* The file descriptor for pFile */
drhd91c68f2010-05-14 14:52:25 +00001366 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
1367 struct stat statbuf; /* Low-level file information */
1368 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
drh6c7d5c52008-11-21 20:32:33 +00001369
dan9359c7b2009-08-21 08:29:10 +00001370 assert( unixMutexHeld() );
1371
drh6c7d5c52008-11-21 20:32:33 +00001372 /* Get low-level information about the file that we can used to
1373 ** create a unique name for the file.
1374 */
1375 fd = pFile->h;
drh99ab3b12011-03-02 15:09:07 +00001376 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001377 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001378 storeLastErrno(pFile, errno);
drh40fe8d32015-11-30 20:36:26 +00001379#if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
drh6c7d5c52008-11-21 20:32:33 +00001380 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
1381#endif
1382 return SQLITE_IOERR;
1383 }
1384
drheb0d74f2009-02-03 15:27:02 +00001385#ifdef __APPLE__
drh6c7d5c52008-11-21 20:32:33 +00001386 /* On OS X on an msdos filesystem, the inode number is reported
1387 ** incorrectly for zero-size files. See ticket #3260. To work
1388 ** around this problem (we consider it a bug in OS X, not SQLite)
1389 ** we always increase the file size to 1 by writing a single byte
1390 ** prior to accessing the inode number. The one byte written is
1391 ** an ASCII 'S' character which also happens to be the first byte
1392 ** in the header of every SQLite database. In this way, if there
1393 ** is a race condition such that another thread has already populated
1394 ** the first page of the database, no damage is done.
1395 */
drh7ed97b92010-01-20 13:07:21 +00001396 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
drhe562be52011-03-02 18:01:10 +00001397 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
drheb0d74f2009-02-03 15:27:02 +00001398 if( rc!=1 ){
drh4bf66fd2015-02-19 02:43:02 +00001399 storeLastErrno(pFile, errno);
drheb0d74f2009-02-03 15:27:02 +00001400 return SQLITE_IOERR;
1401 }
drh99ab3b12011-03-02 15:09:07 +00001402 rc = osFstat(fd, &statbuf);
drh6c7d5c52008-11-21 20:32:33 +00001403 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00001404 storeLastErrno(pFile, errno);
drh6c7d5c52008-11-21 20:32:33 +00001405 return SQLITE_IOERR;
1406 }
1407 }
drheb0d74f2009-02-03 15:27:02 +00001408#endif
drh6c7d5c52008-11-21 20:32:33 +00001409
drh8af6c222010-05-14 12:43:01 +00001410 memset(&fileId, 0, sizeof(fileId));
1411 fileId.dev = statbuf.st_dev;
drh6c7d5c52008-11-21 20:32:33 +00001412#if OS_VXWORKS
drh8af6c222010-05-14 12:43:01 +00001413 fileId.pId = pFile->pId;
drh6c7d5c52008-11-21 20:32:33 +00001414#else
drh25ef7f52016-12-05 20:06:45 +00001415 fileId.ino = (u64)statbuf.st_ino;
drh6c7d5c52008-11-21 20:32:33 +00001416#endif
drh24efa542018-10-02 19:36:40 +00001417 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001418 pInode = inodeList;
1419 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1420 pInode = pInode->pNext;
drh6c7d5c52008-11-21 20:32:33 +00001421 }
drh8af6c222010-05-14 12:43:01 +00001422 if( pInode==0 ){
drhf3cdcdc2015-04-29 16:50:28 +00001423 pInode = sqlite3_malloc64( sizeof(*pInode) );
drh8af6c222010-05-14 12:43:01 +00001424 if( pInode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00001425 return SQLITE_NOMEM_BKPT;
drh6c7d5c52008-11-21 20:32:33 +00001426 }
drh8af6c222010-05-14 12:43:01 +00001427 memset(pInode, 0, sizeof(*pInode));
1428 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
drh6886d6d2018-07-23 22:55:10 +00001429 if( sqlite3GlobalConfig.bCoreMutex ){
1430 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1431 if( pInode->pLockMutex==0 ){
1432 sqlite3_free(pInode);
1433 return SQLITE_NOMEM_BKPT;
1434 }
1435 }
drh8af6c222010-05-14 12:43:01 +00001436 pInode->nRef = 1;
drh24efa542018-10-02 19:36:40 +00001437 assert( unixMutexHeld() );
drh8af6c222010-05-14 12:43:01 +00001438 pInode->pNext = inodeList;
1439 pInode->pPrev = 0;
1440 if( inodeList ) inodeList->pPrev = pInode;
1441 inodeList = pInode;
1442 }else{
1443 pInode->nRef++;
drh6c7d5c52008-11-21 20:32:33 +00001444 }
drh8af6c222010-05-14 12:43:01 +00001445 *ppInode = pInode;
1446 return SQLITE_OK;
drh6c7d5c52008-11-21 20:32:33 +00001447}
drh6c7d5c52008-11-21 20:32:33 +00001448
drhb959a012013-12-07 12:29:22 +00001449/*
1450** Return TRUE if pFile has been renamed or unlinked since it was first opened.
1451*/
1452static int fileHasMoved(unixFile *pFile){
drh61ffea52014-08-12 12:19:25 +00001453#if OS_VXWORKS
1454 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
1455#else
drhb959a012013-12-07 12:29:22 +00001456 struct stat buf;
1457 return pFile->pInode!=0 &&
drh25ef7f52016-12-05 20:06:45 +00001458 (osStat(pFile->zPath, &buf)!=0
1459 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
drh91be7dc2014-08-11 13:53:30 +00001460#endif
drhb959a012013-12-07 12:29:22 +00001461}
1462
aswift5b1a2562008-08-22 00:22:35 +00001463
1464/*
drhfbc7e882013-04-11 01:16:15 +00001465** Check a unixFile that is a database. Verify the following:
1466**
1467** (1) There is exactly one hard link on the file
1468** (2) The file is not a symbolic link
1469** (3) The file has not been renamed or unlinked
1470**
1471** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
1472*/
1473static void verifyDbFile(unixFile *pFile){
1474 struct stat buf;
1475 int rc;
drh86151e82015-12-08 14:37:16 +00001476
1477 /* These verifications occurs for the main database only */
1478 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
1479
drhfbc7e882013-04-11 01:16:15 +00001480 rc = osFstat(pFile->h, &buf);
1481 if( rc!=0 ){
1482 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001483 return;
1484 }
drh6369bc32016-03-21 16:06:42 +00001485 if( buf.st_nlink==0 ){
drhfbc7e882013-04-11 01:16:15 +00001486 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001487 return;
1488 }
1489 if( buf.st_nlink>1 ){
1490 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001491 return;
1492 }
drhb959a012013-12-07 12:29:22 +00001493 if( fileHasMoved(pFile) ){
drhfbc7e882013-04-11 01:16:15 +00001494 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
drhfbc7e882013-04-11 01:16:15 +00001495 return;
1496 }
1497}
1498
1499
1500/*
danielk197713adf8a2004-06-03 16:08:41 +00001501** This routine checks if there is a RESERVED lock held on the specified
aswift5b1a2562008-08-22 00:22:35 +00001502** file by this or any other process. If such a lock is held, set *pResOut
1503** to a non-zero value otherwise *pResOut is set to zero. The return value
1504** is set to SQLITE_OK unless an I/O error occurs during lock checking.
danielk197713adf8a2004-06-03 16:08:41 +00001505*/
danielk1977861f7452008-06-05 11:39:11 +00001506static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00001507 int rc = SQLITE_OK;
1508 int reserved = 0;
drh054889e2005-11-30 03:20:31 +00001509 unixFile *pFile = (unixFile*)id;
danielk197713adf8a2004-06-03 16:08:41 +00001510
danielk1977861f7452008-06-05 11:39:11 +00001511 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1512
drh054889e2005-11-30 03:20:31 +00001513 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00001514 assert( pFile->eFileLock<=SHARED_LOCK );
drhda6dc242018-07-23 21:10:37 +00001515 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
danielk197713adf8a2004-06-03 16:08:41 +00001516
1517 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00001518 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00001519 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001520 }
1521
drh2ac3ee92004-06-07 16:27:46 +00001522 /* Otherwise see if some other process holds it.
danielk197713adf8a2004-06-03 16:08:41 +00001523 */
danielk197709480a92009-02-09 05:32:32 +00001524#ifndef __DJGPP__
drha7e61d82011-03-12 17:02:57 +00001525 if( !reserved && !pFile->pInode->bProcessLock ){
danielk197713adf8a2004-06-03 16:08:41 +00001526 struct flock lock;
1527 lock.l_whence = SEEK_SET;
drh2ac3ee92004-06-07 16:27:46 +00001528 lock.l_start = RESERVED_BYTE;
1529 lock.l_len = 1;
1530 lock.l_type = F_WRLCK;
danea83bc62011-04-01 11:56:32 +00001531 if( osFcntl(pFile->h, F_GETLK, &lock) ){
1532 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00001533 storeLastErrno(pFile, errno);
aswift5b1a2562008-08-22 00:22:35 +00001534 } else if( lock.l_type!=F_UNLCK ){
1535 reserved = 1;
danielk197713adf8a2004-06-03 16:08:41 +00001536 }
1537 }
danielk197709480a92009-02-09 05:32:32 +00001538#endif
danielk197713adf8a2004-06-03 16:08:41 +00001539
drhda6dc242018-07-23 21:10:37 +00001540 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001541 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
danielk197713adf8a2004-06-03 16:08:41 +00001542
aswift5b1a2562008-08-22 00:22:35 +00001543 *pResOut = reserved;
1544 return rc;
danielk197713adf8a2004-06-03 16:08:41 +00001545}
1546
1547/*
drhf0119b22018-03-26 17:40:53 +00001548** Set a posix-advisory-lock.
1549**
1550** There are two versions of this routine. If compiled with
1551** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
1552** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
1553** value is set, then it is the number of milliseconds to wait before
1554** failing the lock. The iBusyTimeout value is always reset back to
1555** zero on each call.
1556**
1557** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
1558** attempt to set the lock.
1559*/
1560#ifndef SQLITE_ENABLE_SETLK_TIMEOUT
1561# define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
1562#else
1563static int osSetPosixAdvisoryLock(
1564 int h, /* The file descriptor on which to take the lock */
1565 struct flock *pLock, /* The description of the lock */
1566 unixFile *pFile /* Structure holding timeout value */
1567){
dan7bb8b8a2020-05-06 20:27:18 +00001568 int tm = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00001569 int rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001570 while( rc<0 && tm>0 ){
drhf0119b22018-03-26 17:40:53 +00001571 /* On systems that support some kind of blocking file lock with a timeout,
1572 ** make appropriate changes here to invoke that blocking file lock. On
1573 ** generic posix, however, there is no such API. So we simply try the
1574 ** lock once every millisecond until either the timeout expires, or until
1575 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001576 usleep(1000);
1577 rc = osFcntl(h,F_SETLK,pLock);
dan7bb8b8a2020-05-06 20:27:18 +00001578 tm--;
drhf0119b22018-03-26 17:40:53 +00001579 }
1580 return rc;
1581}
1582#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1583
1584
1585/*
drha7e61d82011-03-12 17:02:57 +00001586** Attempt to set a system-lock on the file pFile. The lock is
1587** described by pLock.
1588**
drh77197112011-03-15 19:08:48 +00001589** If the pFile was opened read/write from unix-excl, then the only lock
1590** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001591** the first time any lock is attempted. All subsequent system locking
1592** operations become no-ops. Locking operations still happen internally,
1593** in order to coordinate access between separate database connections
1594** within this process, but all of that is handled in memory and the
1595** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001596**
1597** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1598** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1599** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001600**
1601** Zero is returned if the call completes successfully, or -1 if a call
1602** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001603*/
1604static int unixFileLock(unixFile *pFile, struct flock *pLock){
1605 int rc;
drh3cb93392011-03-12 18:10:44 +00001606 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001607 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001608 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001609 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001610 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001611 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001612 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001613 lock.l_whence = SEEK_SET;
1614 lock.l_start = SHARED_FIRST;
1615 lock.l_len = SHARED_SIZE;
1616 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001617 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001618 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001619 pInode->bProcessLock = 1;
1620 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001621 }else{
1622 rc = 0;
1623 }
1624 }else{
drhf0119b22018-03-26 17:40:53 +00001625 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001626 }
1627 return rc;
1628}
1629
1630/*
drh308c2a52010-05-14 11:30:18 +00001631** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001632** of the following:
1633**
drh2ac3ee92004-06-07 16:27:46 +00001634** (1) SHARED_LOCK
1635** (2) RESERVED_LOCK
1636** (3) PENDING_LOCK
1637** (4) EXCLUSIVE_LOCK
1638**
drhb3e04342004-06-08 00:47:47 +00001639** Sometimes when requesting one lock state, additional lock states
1640** are inserted in between. The locking might fail on one of the later
1641** transitions leaving the lock state different from what it started but
1642** still short of its goal. The following chart shows the allowed
1643** transitions and the inserted intermediate states:
1644**
1645** UNLOCKED -> SHARED
1646** SHARED -> RESERVED
1647** SHARED -> (PENDING) -> EXCLUSIVE
1648** RESERVED -> (PENDING) -> EXCLUSIVE
1649** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001650**
drha6abd042004-06-09 17:37:22 +00001651** This routine will only increase a lock. Use the sqlite3OsUnlock()
1652** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001653*/
drh308c2a52010-05-14 11:30:18 +00001654static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001655 /* The following describes the implementation of the various locks and
1656 ** lock transitions in terms of the POSIX advisory shared and exclusive
1657 ** lock primitives (called read-locks and write-locks below, to avoid
1658 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001659 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001660 ** accessing the same database file, in case that is ever required.
1661 **
1662 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1663 ** byte', each single bytes at well known offsets, and the 'shared byte
1664 ** range', a range of 510 bytes at a well known offset.
1665 **
1666 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001667 ** byte'. If this is successful, 'shared byte range' is read-locked
1668 ** and the lock on the 'pending byte' released. (Legacy note: When
1669 ** SQLite was first developed, Windows95 systems were still very common,
1670 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1671 ** single randomly selected by from the 'shared byte range' is locked.
1672 ** Windows95 is now pretty much extinct, but this work-around for the
1673 ** lack of shared-locks on Windows95 lives on, for backwards
1674 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001675 **
danielk197790ba3bd2004-06-25 08:32:25 +00001676 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1677 ** A RESERVED lock is implemented by grabbing a write-lock on the
1678 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001679 **
1680 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001681 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1682 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1683 ** obtained, but existing SHARED locks are allowed to persist. A process
1684 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1685 ** This property is used by the algorithm for rolling back a journal file
1686 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001687 **
danielk197790ba3bd2004-06-25 08:32:25 +00001688 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1689 ** implemented by obtaining a write-lock on the entire 'shared byte
1690 ** range'. Since all other locks require a read-lock on one of the bytes
1691 ** within this range, this ensures that no other locks are held on the
1692 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001693 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001694 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001695 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001696 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001697 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001698 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001699
drh054889e2005-11-30 03:20:31 +00001700 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001701 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1702 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001703 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001704 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001705
1706 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001707 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001708 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001709 */
drh308c2a52010-05-14 11:30:18 +00001710 if( pFile->eFileLock>=eFileLock ){
1711 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1712 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001713 return SQLITE_OK;
1714 }
1715
drh0c2694b2009-09-03 16:23:44 +00001716 /* Make sure the locking sequence is correct.
1717 ** (1) We never move from unlocked to anything higher than shared lock.
1718 ** (2) SQLite never explicitly requests a pendig lock.
1719 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001720 */
drh308c2a52010-05-14 11:30:18 +00001721 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1722 assert( eFileLock!=PENDING_LOCK );
1723 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001724
drh8af6c222010-05-14 12:43:01 +00001725 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001726 */
drh8af6c222010-05-14 12:43:01 +00001727 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001728 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001729
danielk1977ad94b582007-08-20 06:44:22 +00001730 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001731 ** handle that precludes the requested lock, return BUSY.
1732 */
drh8af6c222010-05-14 12:43:01 +00001733 if( (pFile->eFileLock!=pInode->eFileLock &&
1734 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001735 ){
1736 rc = SQLITE_BUSY;
1737 goto end_lock;
1738 }
1739
1740 /* If a SHARED lock is requested, and some thread using this PID already
1741 ** has a SHARED or RESERVED lock, then increment reference counts and
1742 ** return SQLITE_OK.
1743 */
drh308c2a52010-05-14 11:30:18 +00001744 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001745 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001746 assert( eFileLock==SHARED_LOCK );
1747 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001748 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001749 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001750 pInode->nShared++;
1751 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001752 goto end_lock;
1753 }
1754
danielk19779a1d0ab2004-06-01 14:09:28 +00001755
drh3cde3bb2004-06-12 02:17:14 +00001756 /* A PENDING lock is needed before acquiring a SHARED lock and before
1757 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1758 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001759 */
drh0c2694b2009-09-03 16:23:44 +00001760 lock.l_len = 1L;
1761 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001762 if( eFileLock==SHARED_LOCK
1763 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001764 ){
drh308c2a52010-05-14 11:30:18 +00001765 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001766 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001767 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001768 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001769 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001770 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001771 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001772 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001773 goto end_lock;
1774 }
drh3cde3bb2004-06-12 02:17:14 +00001775 }
1776
1777
1778 /* If control gets to this point, then actually go ahead and make
1779 ** operating system calls for the specified lock.
1780 */
drh308c2a52010-05-14 11:30:18 +00001781 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001782 assert( pInode->nShared==0 );
1783 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001784 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001785
drh2ac3ee92004-06-07 16:27:46 +00001786 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001787 lock.l_start = SHARED_FIRST;
1788 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001789 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001790 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001791 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001792 }
dan661d71a2011-03-30 19:08:03 +00001793
drh2ac3ee92004-06-07 16:27:46 +00001794 /* Drop the temporary PENDING lock */
1795 lock.l_start = PENDING_BYTE;
1796 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001797 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001798 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1799 /* This could happen with a network mount */
1800 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001801 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001802 }
dan661d71a2011-03-30 19:08:03 +00001803
1804 if( rc ){
1805 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001806 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001807 }
dan661d71a2011-03-30 19:08:03 +00001808 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001809 }else{
drh308c2a52010-05-14 11:30:18 +00001810 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001811 pInode->nLock++;
1812 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001813 }
drh8af6c222010-05-14 12:43:01 +00001814 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001815 /* We are trying for an exclusive lock but another thread in this
1816 ** same process is still holding a shared lock. */
1817 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001818 }else{
drh3cde3bb2004-06-12 02:17:14 +00001819 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001820 ** assumed that there is a SHARED or greater lock on the file
1821 ** already.
1822 */
drh308c2a52010-05-14 11:30:18 +00001823 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001824 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001825
1826 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1827 if( eFileLock==RESERVED_LOCK ){
1828 lock.l_start = RESERVED_BYTE;
1829 lock.l_len = 1L;
1830 }else{
1831 lock.l_start = SHARED_FIRST;
1832 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001833 }
dan661d71a2011-03-30 19:08:03 +00001834
1835 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001836 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001837 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001838 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001839 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001840 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001841 }
drhbbd42a62004-05-22 17:41:58 +00001842 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001843
drh8f941bc2009-01-14 23:03:40 +00001844
drhd3d8c042012-05-29 17:02:40 +00001845#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001846 /* Set up the transaction-counter change checking flags when
1847 ** transitioning from a SHARED to a RESERVED lock. The change
1848 ** from SHARED to RESERVED marks the beginning of a normal
1849 ** write operation (not a hot journal rollback).
1850 */
1851 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001852 && pFile->eFileLock<=SHARED_LOCK
1853 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001854 ){
1855 pFile->transCntrChng = 0;
1856 pFile->dbUpdate = 0;
1857 pFile->inNormalWrite = 1;
1858 }
1859#endif
1860
1861
danielk1977ecb2a962004-06-02 06:30:16 +00001862 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001863 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001864 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001865 }else if( eFileLock==EXCLUSIVE_LOCK ){
1866 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001867 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001868 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001869
1870end_lock:
drhda6dc242018-07-23 21:10:37 +00001871 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001872 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1873 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001874 return rc;
1875}
1876
1877/*
dan08da86a2009-08-21 17:18:03 +00001878** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001879** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001880*/
1881static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001882 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001883 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001884 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001885 p->pNext = pInode->pUnused;
1886 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001887 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001888 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001889}
1890
1891/*
drh308c2a52010-05-14 11:30:18 +00001892** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001893** must be either NO_LOCK or SHARED_LOCK.
1894**
1895** If the locking level of the file descriptor is already at or below
1896** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001897**
1898** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1899** the byte range is divided into 2 parts and the first part is unlocked then
1900** set to a read lock, then the other part is simply unlocked. This works
1901** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1902** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001903*/
drha7e61d82011-03-12 17:02:57 +00001904static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001905 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001906 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001907 struct flock lock;
1908 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001909
drh054889e2005-11-30 03:20:31 +00001910 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001911 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001912 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001913 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001914
drh308c2a52010-05-14 11:30:18 +00001915 assert( eFileLock<=SHARED_LOCK );
1916 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001917 return SQLITE_OK;
1918 }
drh8af6c222010-05-14 12:43:01 +00001919 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001920 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001921 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001922 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001923 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001924
drhd3d8c042012-05-29 17:02:40 +00001925#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001926 /* When reducing a lock such that other processes can start
1927 ** reading the database file again, make sure that the
1928 ** transaction counter was updated if any part of the database
1929 ** file changed. If the transaction counter is not updated,
1930 ** other connections to the same file might not realize that
1931 ** the file has changed and hence might not know to flush their
1932 ** cache. The use of a stale cache can lead to database corruption.
1933 */
drh8f941bc2009-01-14 23:03:40 +00001934 pFile->inNormalWrite = 0;
1935#endif
1936
drh7ed97b92010-01-20 13:07:21 +00001937 /* downgrading to a shared lock on NFS involves clearing the write lock
1938 ** before establishing the readlock - to avoid a race condition we downgrade
1939 ** the lock in 2 blocks, so that part of the range will be covered by a
1940 ** write lock until the rest is covered by a read lock:
1941 ** 1: [WWWWW]
1942 ** 2: [....W]
1943 ** 3: [RRRRW]
1944 ** 4: [RRRR.]
1945 */
drh308c2a52010-05-14 11:30:18 +00001946 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001947#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001948 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001949 assert( handleNFSUnlock==0 );
1950#endif
1951#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001952 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001953 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001954 off_t divSize = SHARED_SIZE - 1;
1955
1956 lock.l_type = F_UNLCK;
1957 lock.l_whence = SEEK_SET;
1958 lock.l_start = SHARED_FIRST;
1959 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001960 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001961 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001962 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001963 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001964 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001965 }
drh7ed97b92010-01-20 13:07:21 +00001966 lock.l_type = F_RDLCK;
1967 lock.l_whence = SEEK_SET;
1968 lock.l_start = SHARED_FIRST;
1969 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001970 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001971 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001972 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1973 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001974 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001975 }
1976 goto end_unlock;
1977 }
1978 lock.l_type = F_UNLCK;
1979 lock.l_whence = SEEK_SET;
1980 lock.l_start = SHARED_FIRST+divSize;
1981 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001982 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001983 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001984 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001985 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001986 goto end_unlock;
1987 }
drh30f776f2011-02-25 03:25:07 +00001988 }else
1989#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1990 {
drh7ed97b92010-01-20 13:07:21 +00001991 lock.l_type = F_RDLCK;
1992 lock.l_whence = SEEK_SET;
1993 lock.l_start = SHARED_FIRST;
1994 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001995 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001996 /* In theory, the call to unixFileLock() cannot fail because another
1997 ** process is holding an incompatible lock. If it does, this
1998 ** indicates that the other process is not following the locking
1999 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
2000 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2001 ** an assert to fail). */
2002 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002003 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00002004 goto end_unlock;
2005 }
drh9c105bb2004-10-02 20:38:28 +00002006 }
2007 }
drhbbd42a62004-05-22 17:41:58 +00002008 lock.l_type = F_UNLCK;
2009 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00002010 lock.l_start = PENDING_BYTE;
2011 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00002012 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002013 pInode->eFileLock = SHARED_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);
drhcd731cf2009-03-28 23:23:02 +00002017 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00002018 }
drhbbd42a62004-05-22 17:41:58 +00002019 }
drh308c2a52010-05-14 11:30:18 +00002020 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002021 /* Decrement the shared lock counter. Release the lock using an
2022 ** OS call only when all threads in this same process have released
2023 ** the lock.
2024 */
drh8af6c222010-05-14 12:43:01 +00002025 pInode->nShared--;
2026 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002027 lock.l_type = F_UNLCK;
2028 lock.l_whence = SEEK_SET;
2029 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002030 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002031 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002032 }else{
danea83bc62011-04-01 11:56:32 +00002033 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002034 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002035 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002036 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002037 }
drha6abd042004-06-09 17:37:22 +00002038 }
2039
drhbbd42a62004-05-22 17:41:58 +00002040 /* Decrement the count of locks against this same file. When the
2041 ** count reaches zero, close any other file descriptors whose close
2042 ** was deferred because of outstanding locks.
2043 */
drh8af6c222010-05-14 12:43:01 +00002044 pInode->nLock--;
2045 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002046 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002047 }
drhf2f105d2012-08-20 15:53:54 +00002048
aswift5b1a2562008-08-22 00:22:35 +00002049end_unlock:
drhda6dc242018-07-23 21:10:37 +00002050 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002051 if( rc==SQLITE_OK ){
2052 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002053 }
drh9c105bb2004-10-02 20:38:28 +00002054 return rc;
drhbbd42a62004-05-22 17:41:58 +00002055}
2056
2057/*
drh308c2a52010-05-14 11:30:18 +00002058** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002059** must be either NO_LOCK or SHARED_LOCK.
2060**
2061** If the locking level of the file descriptor is already at or below
2062** the requested locking level, this routine is a no-op.
2063*/
drh308c2a52010-05-14 11:30:18 +00002064static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002065#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002066 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002067#endif
drha7e61d82011-03-12 17:02:57 +00002068 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002069}
2070
mistachkine98844f2013-08-24 00:59:24 +00002071#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002072static int unixMapfile(unixFile *pFd, i64 nByte);
2073static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002074#endif
danf23da962013-03-23 21:00:41 +00002075
drh7ed97b92010-01-20 13:07:21 +00002076/*
danielk1977e339d652008-06-28 11:23:00 +00002077** This function performs the parts of the "close file" operation
2078** common to all locking schemes. It closes the directory and file
2079** handles, if they are valid, and sets all fields of the unixFile
2080** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002081**
2082** It is *not* necessary to hold the mutex when this routine is called,
2083** even on VxWorks. A mutex will be acquired on VxWorks by the
2084** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002085*/
2086static int closeUnixFile(sqlite3_file *id){
2087 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002088#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002089 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002090#endif
dan661d71a2011-03-30 19:08:03 +00002091 if( pFile->h>=0 ){
2092 robust_close(pFile, pFile->h, __LINE__);
2093 pFile->h = -1;
2094 }
2095#if OS_VXWORKS
2096 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002097 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002098 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002099 }
2100 vxworksReleaseFileId(pFile->pId);
2101 pFile->pId = 0;
2102 }
2103#endif
drh0bdbc902014-06-16 18:35:06 +00002104#ifdef SQLITE_UNLINK_AFTER_CLOSE
2105 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2106 osUnlink(pFile->zPath);
2107 sqlite3_free(*(char**)&pFile->zPath);
2108 pFile->zPath = 0;
2109 }
2110#endif
dan661d71a2011-03-30 19:08:03 +00002111 OSTRACE(("CLOSE %-3d\n", pFile->h));
2112 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002113 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002114 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002115 return SQLITE_OK;
2116}
2117
2118/*
danielk1977e3026632004-06-22 11:29:02 +00002119** Close a file.
2120*/
danielk197762079062007-08-15 17:08:46 +00002121static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002122 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002123 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002124 unixInodeInfo *pInode = pFile->pInode;
2125
2126 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002127 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002128 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002129 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002130 unixEnterMutex();
2131
2132 /* unixFile.pInode is always valid here. Otherwise, a different close
2133 ** routine (e.g. nolockClose()) would be called instead.
2134 */
2135 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002136 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002137 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002138 /* If there are outstanding locks, do not actually close the file just
2139 ** yet because that would clear those locks. Instead, add the file
2140 ** descriptor to pInode->pUnused list. It will be automatically closed
2141 ** when the last lock is cleared.
2142 */
2143 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002144 }
drhef52b362018-08-13 22:50:34 +00002145 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002146 releaseInodeInfo(pFile);
2147 rc = closeUnixFile(id);
2148 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002149 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002150}
2151
drh734c9862008-11-28 15:37:20 +00002152/************** End of the posix advisory lock implementation *****************
2153******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002154
drh734c9862008-11-28 15:37:20 +00002155/******************************************************************************
2156****************************** No-op Locking **********************************
2157**
2158** Of the various locking implementations available, this is by far the
2159** simplest: locking is ignored. No attempt is made to lock the database
2160** file for reading or writing.
2161**
2162** This locking mode is appropriate for use on read-only databases
2163** (ex: databases that are burned into CD-ROM, for example.) It can
2164** also be used if the application employs some external mechanism to
2165** prevent simultaneous access of the same database by two or more
2166** database connections. But there is a serious risk of database
2167** corruption if this locking mode is used in situations where multiple
2168** database connections are accessing the same database file at the same
2169** time and one or more of those connections are writing.
2170*/
drhbfe66312006-10-03 17:40:40 +00002171
drh734c9862008-11-28 15:37:20 +00002172static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2173 UNUSED_PARAMETER(NotUsed);
2174 *pResOut = 0;
2175 return SQLITE_OK;
2176}
drh734c9862008-11-28 15:37:20 +00002177static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2178 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2179 return SQLITE_OK;
2180}
drh734c9862008-11-28 15:37:20 +00002181static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2182 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2183 return SQLITE_OK;
2184}
2185
2186/*
drh9b35ea62008-11-29 02:20:26 +00002187** Close the file.
drh734c9862008-11-28 15:37:20 +00002188*/
2189static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002190 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002191}
2192
2193/******************* End of the no-op lock implementation *********************
2194******************************************************************************/
2195
2196/******************************************************************************
2197************************* Begin dot-file Locking ******************************
2198**
mistachkin48864df2013-03-21 21:20:32 +00002199** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002200** files (really a directory) to control access to the database. This works
2201** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002202**
2203** (1) There is zero concurrency. A single reader blocks all other
2204** connections from reading or writing the database.
2205**
2206** (2) An application crash or power loss can leave stale lock files
2207** sitting around that need to be cleared manually.
2208**
2209** Nevertheless, a dotlock is an appropriate locking mode for use if no
2210** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002211**
drh9ef6bc42011-11-04 02:24:02 +00002212** Dotfile locking works by creating a subdirectory in the same directory as
2213** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002214** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002215** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002216*/
2217
2218/*
2219** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002220** lock directory.
drh734c9862008-11-28 15:37:20 +00002221*/
2222#define DOTLOCK_SUFFIX ".lock"
2223
drh7708e972008-11-29 00:56:52 +00002224/*
2225** This routine checks if there is a RESERVED lock held on the specified
2226** file by this or any other process. If such a lock is held, set *pResOut
2227** to a non-zero value otherwise *pResOut is set to zero. The return value
2228** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2229**
2230** In dotfile locking, either a lock exists or it does not. So in this
2231** variation of CheckReservedLock(), *pResOut is set to true if any lock
2232** is held on the file and false if the file is unlocked.
2233*/
drh734c9862008-11-28 15:37:20 +00002234static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2235 int rc = SQLITE_OK;
2236 int reserved = 0;
2237 unixFile *pFile = (unixFile*)id;
2238
2239 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2240
2241 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002242 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002243 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002244 *pResOut = reserved;
2245 return rc;
2246}
2247
drh7708e972008-11-29 00:56:52 +00002248/*
drh308c2a52010-05-14 11:30:18 +00002249** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002250** of the following:
2251**
2252** (1) SHARED_LOCK
2253** (2) RESERVED_LOCK
2254** (3) PENDING_LOCK
2255** (4) EXCLUSIVE_LOCK
2256**
2257** Sometimes when requesting one lock state, additional lock states
2258** are inserted in between. The locking might fail on one of the later
2259** transitions leaving the lock state different from what it started but
2260** still short of its goal. The following chart shows the allowed
2261** transitions and the inserted intermediate states:
2262**
2263** UNLOCKED -> SHARED
2264** SHARED -> RESERVED
2265** SHARED -> (PENDING) -> EXCLUSIVE
2266** RESERVED -> (PENDING) -> EXCLUSIVE
2267** PENDING -> EXCLUSIVE
2268**
2269** This routine will only increase a lock. Use the sqlite3OsUnlock()
2270** routine to lower a locking level.
2271**
2272** With dotfile locking, we really only support state (4): EXCLUSIVE.
2273** But we track the other locking levels internally.
2274*/
drh308c2a52010-05-14 11:30:18 +00002275static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002276 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002277 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002278 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002279
drh7708e972008-11-29 00:56:52 +00002280
2281 /* If we have any lock, then the lock file already exists. All we have
2282 ** to do is adjust our internal record of the lock level.
2283 */
drh308c2a52010-05-14 11:30:18 +00002284 if( pFile->eFileLock > NO_LOCK ){
2285 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002286 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002287#ifdef HAVE_UTIME
2288 utime(zLockFile, NULL);
2289#else
drh734c9862008-11-28 15:37:20 +00002290 utimes(zLockFile, NULL);
2291#endif
drh7708e972008-11-29 00:56:52 +00002292 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002293 }
2294
2295 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002296 rc = osMkdir(zLockFile, 0777);
2297 if( rc<0 ){
2298 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002299 int tErrno = errno;
2300 if( EEXIST == tErrno ){
2301 rc = SQLITE_BUSY;
2302 } else {
2303 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002304 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002305 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002306 }
2307 }
drh7708e972008-11-29 00:56:52 +00002308 return rc;
drh734c9862008-11-28 15:37:20 +00002309 }
drh734c9862008-11-28 15:37:20 +00002310
2311 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002312 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002313 return rc;
2314}
2315
drh7708e972008-11-29 00:56:52 +00002316/*
drh308c2a52010-05-14 11:30:18 +00002317** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002318** must be either NO_LOCK or SHARED_LOCK.
2319**
2320** If the locking level of the file descriptor is already at or below
2321** the requested locking level, this routine is a no-op.
2322**
2323** When the locking level reaches NO_LOCK, delete the lock file.
2324*/
drh308c2a52010-05-14 11:30:18 +00002325static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002326 unixFile *pFile = (unixFile*)id;
2327 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002328 int rc;
drh734c9862008-11-28 15:37:20 +00002329
2330 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002331 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002332 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002333 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002334
2335 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002336 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002337 return SQLITE_OK;
2338 }
drh7708e972008-11-29 00:56:52 +00002339
2340 /* To downgrade to shared, simply update our internal notion of the
2341 ** lock state. No need to mess with the file on disk.
2342 */
drh308c2a52010-05-14 11:30:18 +00002343 if( eFileLock==SHARED_LOCK ){
2344 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002345 return SQLITE_OK;
2346 }
2347
drh7708e972008-11-29 00:56:52 +00002348 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002349 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002350 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002351 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002352 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002353 if( tErrno==ENOENT ){
2354 rc = SQLITE_OK;
2355 }else{
danea83bc62011-04-01 11:56:32 +00002356 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002357 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002358 }
2359 return rc;
2360 }
drh308c2a52010-05-14 11:30:18 +00002361 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002362 return SQLITE_OK;
2363}
2364
2365/*
drh9b35ea62008-11-29 02:20:26 +00002366** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002367*/
2368static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002369 unixFile *pFile = (unixFile*)id;
2370 assert( id!=0 );
2371 dotlockUnlock(id, NO_LOCK);
2372 sqlite3_free(pFile->lockingContext);
2373 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002374}
2375/****************** End of the dot-file lock implementation *******************
2376******************************************************************************/
2377
2378/******************************************************************************
2379************************** Begin flock Locking ********************************
2380**
2381** Use the flock() system call to do file locking.
2382**
drh6b9d6dd2008-12-03 19:34:47 +00002383** flock() locking is like dot-file locking in that the various
2384** fine-grain locking levels supported by SQLite are collapsed into
2385** a single exclusive lock. In other words, SHARED, RESERVED, and
2386** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2387** still works when you do this, but concurrency is reduced since
2388** only a single process can be reading the database at a time.
2389**
drhe89b2912015-03-03 20:42:01 +00002390** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002391*/
drhe89b2912015-03-03 20:42:01 +00002392#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002393
drh6b9d6dd2008-12-03 19:34:47 +00002394/*
drhff812312011-02-23 13:33:46 +00002395** Retry flock() calls that fail with EINTR
2396*/
2397#ifdef EINTR
2398static int robust_flock(int fd, int op){
2399 int rc;
2400 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2401 return rc;
2402}
2403#else
drh5c819272011-02-23 14:00:12 +00002404# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002405#endif
2406
2407
2408/*
drh6b9d6dd2008-12-03 19:34:47 +00002409** This routine checks if there is a RESERVED lock held on the specified
2410** file by this or any other process. If such a lock is held, set *pResOut
2411** to a non-zero value otherwise *pResOut is set to zero. The return value
2412** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2413*/
drh734c9862008-11-28 15:37:20 +00002414static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2415 int rc = SQLITE_OK;
2416 int reserved = 0;
2417 unixFile *pFile = (unixFile*)id;
2418
2419 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2420
2421 assert( pFile );
2422
2423 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002424 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002425 reserved = 1;
2426 }
2427
2428 /* Otherwise see if some other process holds it. */
2429 if( !reserved ){
2430 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002431 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002432 if( !lrc ){
2433 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002434 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002435 if ( lrc ) {
2436 int tErrno = errno;
2437 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002438 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002439 storeLastErrno(pFile, tErrno);
2440 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002441 }
2442 } else {
2443 int tErrno = errno;
2444 reserved = 1;
2445 /* someone else might have it reserved */
2446 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2447 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002448 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002449 rc = lrc;
2450 }
2451 }
2452 }
drh308c2a52010-05-14 11:30:18 +00002453 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002454
2455#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002456 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002457 rc = SQLITE_OK;
2458 reserved=1;
2459 }
2460#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2461 *pResOut = reserved;
2462 return rc;
2463}
2464
drh6b9d6dd2008-12-03 19:34:47 +00002465/*
drh308c2a52010-05-14 11:30:18 +00002466** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002467** of the following:
2468**
2469** (1) SHARED_LOCK
2470** (2) RESERVED_LOCK
2471** (3) PENDING_LOCK
2472** (4) EXCLUSIVE_LOCK
2473**
2474** Sometimes when requesting one lock state, additional lock states
2475** are inserted in between. The locking might fail on one of the later
2476** transitions leaving the lock state different from what it started but
2477** still short of its goal. The following chart shows the allowed
2478** transitions and the inserted intermediate states:
2479**
2480** UNLOCKED -> SHARED
2481** SHARED -> RESERVED
2482** SHARED -> (PENDING) -> EXCLUSIVE
2483** RESERVED -> (PENDING) -> EXCLUSIVE
2484** PENDING -> EXCLUSIVE
2485**
2486** flock() only really support EXCLUSIVE locks. We track intermediate
2487** lock states in the sqlite3_file structure, but all locks SHARED or
2488** above are really EXCLUSIVE locks and exclude all other processes from
2489** access the file.
2490**
2491** This routine will only increase a lock. Use the sqlite3OsUnlock()
2492** routine to lower a locking level.
2493*/
drh308c2a52010-05-14 11:30:18 +00002494static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002495 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002496 unixFile *pFile = (unixFile*)id;
2497
2498 assert( pFile );
2499
2500 /* if we already have a lock, it is exclusive.
2501 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002502 if (pFile->eFileLock > NO_LOCK) {
2503 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002504 return SQLITE_OK;
2505 }
2506
2507 /* grab an exclusive lock */
2508
drhff812312011-02-23 13:33:46 +00002509 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002510 int tErrno = errno;
2511 /* didn't get, must be busy */
2512 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2513 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002514 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002515 }
2516 } else {
2517 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002518 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002519 }
drh308c2a52010-05-14 11:30:18 +00002520 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2521 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002522#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002523 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002524 rc = SQLITE_BUSY;
2525 }
2526#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2527 return rc;
2528}
2529
drh6b9d6dd2008-12-03 19:34:47 +00002530
2531/*
drh308c2a52010-05-14 11:30:18 +00002532** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002533** must be either NO_LOCK or SHARED_LOCK.
2534**
2535** If the locking level of the file descriptor is already at or below
2536** the requested locking level, this routine is a no-op.
2537*/
drh308c2a52010-05-14 11:30:18 +00002538static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002539 unixFile *pFile = (unixFile*)id;
2540
2541 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002542 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002543 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002544 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002545
2546 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002547 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002548 return SQLITE_OK;
2549 }
2550
2551 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002552 if (eFileLock==SHARED_LOCK) {
2553 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002554 return SQLITE_OK;
2555 }
2556
2557 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002558 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002559#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002560 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002561#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002562 return SQLITE_IOERR_UNLOCK;
2563 }else{
drh308c2a52010-05-14 11:30:18 +00002564 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002565 return SQLITE_OK;
2566 }
2567}
2568
2569/*
2570** Close a file.
2571*/
2572static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002573 assert( id!=0 );
2574 flockUnlock(id, NO_LOCK);
2575 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002576}
2577
2578#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2579
2580/******************* End of the flock lock implementation *********************
2581******************************************************************************/
2582
2583/******************************************************************************
2584************************ Begin Named Semaphore Locking ************************
2585**
2586** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002587**
2588** Semaphore locking is like dot-lock and flock in that it really only
2589** supports EXCLUSIVE locking. Only a single process can read or write
2590** the database file at a time. This reduces potential concurrency, but
2591** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002592*/
2593#if OS_VXWORKS
2594
drh6b9d6dd2008-12-03 19:34:47 +00002595/*
2596** This routine checks if there is a RESERVED lock held on the specified
2597** file by this or any other process. If such a lock is held, set *pResOut
2598** to a non-zero value otherwise *pResOut is set to zero. The return value
2599** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2600*/
drh8cd5b252015-03-02 22:06:43 +00002601static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002602 int rc = SQLITE_OK;
2603 int reserved = 0;
2604 unixFile *pFile = (unixFile*)id;
2605
2606 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2607
2608 assert( pFile );
2609
2610 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002611 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002612 reserved = 1;
2613 }
2614
2615 /* Otherwise see if some other process holds it. */
2616 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002617 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002618
2619 if( sem_trywait(pSem)==-1 ){
2620 int tErrno = errno;
2621 if( EAGAIN != tErrno ){
2622 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002623 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002624 } else {
2625 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002626 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002627 }
2628 }else{
2629 /* we could have it if we want it */
2630 sem_post(pSem);
2631 }
2632 }
drh308c2a52010-05-14 11:30:18 +00002633 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002634
2635 *pResOut = reserved;
2636 return rc;
2637}
2638
drh6b9d6dd2008-12-03 19:34:47 +00002639/*
drh308c2a52010-05-14 11:30:18 +00002640** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002641** of the following:
2642**
2643** (1) SHARED_LOCK
2644** (2) RESERVED_LOCK
2645** (3) PENDING_LOCK
2646** (4) EXCLUSIVE_LOCK
2647**
2648** Sometimes when requesting one lock state, additional lock states
2649** are inserted in between. The locking might fail on one of the later
2650** transitions leaving the lock state different from what it started but
2651** still short of its goal. The following chart shows the allowed
2652** transitions and the inserted intermediate states:
2653**
2654** UNLOCKED -> SHARED
2655** SHARED -> RESERVED
2656** SHARED -> (PENDING) -> EXCLUSIVE
2657** RESERVED -> (PENDING) -> EXCLUSIVE
2658** PENDING -> EXCLUSIVE
2659**
2660** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2661** lock states in the sqlite3_file structure, but all locks SHARED or
2662** above are really EXCLUSIVE locks and exclude all other processes from
2663** access the file.
2664**
2665** This routine will only increase a lock. Use the sqlite3OsUnlock()
2666** routine to lower a locking level.
2667*/
drh8cd5b252015-03-02 22:06:43 +00002668static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002669 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002670 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002671 int rc = SQLITE_OK;
2672
2673 /* if we already have a lock, it is exclusive.
2674 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002675 if (pFile->eFileLock > NO_LOCK) {
2676 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002677 rc = SQLITE_OK;
2678 goto sem_end_lock;
2679 }
2680
2681 /* lock semaphore now but bail out when already locked. */
2682 if( sem_trywait(pSem)==-1 ){
2683 rc = SQLITE_BUSY;
2684 goto sem_end_lock;
2685 }
2686
2687 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002688 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002689
2690 sem_end_lock:
2691 return rc;
2692}
2693
drh6b9d6dd2008-12-03 19:34:47 +00002694/*
drh308c2a52010-05-14 11:30:18 +00002695** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002696** must be either NO_LOCK or SHARED_LOCK.
2697**
2698** If the locking level of the file descriptor is already at or below
2699** the requested locking level, this routine is a no-op.
2700*/
drh8cd5b252015-03-02 22:06:43 +00002701static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002702 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002703 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002704
2705 assert( pFile );
2706 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002707 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002708 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002709 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002710
2711 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002712 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002713 return SQLITE_OK;
2714 }
2715
2716 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002717 if (eFileLock==SHARED_LOCK) {
2718 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002719 return SQLITE_OK;
2720 }
2721
2722 /* no, really unlock. */
2723 if ( sem_post(pSem)==-1 ) {
2724 int rc, tErrno = errno;
2725 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2726 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002727 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002728 }
2729 return rc;
2730 }
drh308c2a52010-05-14 11:30:18 +00002731 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002732 return SQLITE_OK;
2733}
2734
2735/*
2736 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002737 */
drh8cd5b252015-03-02 22:06:43 +00002738static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002739 if( id ){
2740 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002741 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002742 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002743 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002744 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002745 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002746 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002747 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002748 }
2749 return SQLITE_OK;
2750}
2751
2752#endif /* OS_VXWORKS */
2753/*
2754** Named semaphore locking is only available on VxWorks.
2755**
2756*************** End of the named semaphore lock implementation ****************
2757******************************************************************************/
2758
2759
2760/******************************************************************************
2761*************************** Begin AFP Locking *********************************
2762**
2763** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2764** on Apple Macintosh computers - both OS9 and OSX.
2765**
2766** Third-party implementations of AFP are available. But this code here
2767** only works on OSX.
2768*/
2769
drhd2cb50b2009-01-09 21:41:17 +00002770#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002771/*
2772** The afpLockingContext structure contains all afp lock specific state
2773*/
drhbfe66312006-10-03 17:40:40 +00002774typedef struct afpLockingContext afpLockingContext;
2775struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002776 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002777 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002778};
2779
2780struct ByteRangeLockPB2
2781{
2782 unsigned long long offset; /* offset to first byte to lock */
2783 unsigned long long length; /* nbr of bytes to lock */
2784 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2785 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2786 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2787 int fd; /* file desc to assoc this lock with */
2788};
2789
drhfd131da2007-08-07 17:13:03 +00002790#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002791
drh6b9d6dd2008-12-03 19:34:47 +00002792/*
2793** This is a utility for setting or clearing a bit-range lock on an
2794** AFP filesystem.
2795**
2796** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2797*/
2798static int afpSetLock(
2799 const char *path, /* Name of the file to be locked or unlocked */
2800 unixFile *pFile, /* Open file descriptor on path */
2801 unsigned long long offset, /* First byte to be locked */
2802 unsigned long long length, /* Number of bytes to lock */
2803 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002804){
drh6b9d6dd2008-12-03 19:34:47 +00002805 struct ByteRangeLockPB2 pb;
2806 int err;
drhbfe66312006-10-03 17:40:40 +00002807
2808 pb.unLockFlag = setLockFlag ? 0 : 1;
2809 pb.startEndFlag = 0;
2810 pb.offset = offset;
2811 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002812 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002813
drh308c2a52010-05-14 11:30:18 +00002814 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002815 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002816 offset, length));
drhbfe66312006-10-03 17:40:40 +00002817 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2818 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002819 int rc;
2820 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002821 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2822 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002823#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2824 rc = SQLITE_BUSY;
2825#else
drh734c9862008-11-28 15:37:20 +00002826 rc = sqliteErrorFromPosixError(tErrno,
2827 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002828#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002829 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002830 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002831 }
2832 return rc;
drhbfe66312006-10-03 17:40:40 +00002833 } else {
aswift5b1a2562008-08-22 00:22:35 +00002834 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002835 }
2836}
2837
drh6b9d6dd2008-12-03 19:34:47 +00002838/*
2839** This routine checks if there is a RESERVED lock held on the specified
2840** file by this or any other process. If such a lock is held, set *pResOut
2841** to a non-zero value otherwise *pResOut is set to zero. The return value
2842** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2843*/
danielk1977e339d652008-06-28 11:23:00 +00002844static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002845 int rc = SQLITE_OK;
2846 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002847 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002848 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002849
aswift5b1a2562008-08-22 00:22:35 +00002850 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2851
2852 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002853 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002854 if( context->reserved ){
2855 *pResOut = 1;
2856 return SQLITE_OK;
2857 }
drhda6dc242018-07-23 21:10:37 +00002858 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002859 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002860 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002861 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002862 }
2863
2864 /* Otherwise see if some other process holds it.
2865 */
aswift5b1a2562008-08-22 00:22:35 +00002866 if( !reserved ){
2867 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002868 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002869 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002870 /* if we succeeded in taking the reserved lock, unlock it to restore
2871 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002872 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002873 } else {
2874 /* if we failed to get the lock then someone else must have it */
2875 reserved = 1;
2876 }
2877 if( IS_LOCK_ERROR(lrc) ){
2878 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002879 }
2880 }
drhbfe66312006-10-03 17:40:40 +00002881
drhda6dc242018-07-23 21:10:37 +00002882 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002883 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002884
2885 *pResOut = reserved;
2886 return rc;
drhbfe66312006-10-03 17:40:40 +00002887}
2888
drh6b9d6dd2008-12-03 19:34:47 +00002889/*
drh308c2a52010-05-14 11:30:18 +00002890** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002891** of the following:
2892**
2893** (1) SHARED_LOCK
2894** (2) RESERVED_LOCK
2895** (3) PENDING_LOCK
2896** (4) EXCLUSIVE_LOCK
2897**
2898** Sometimes when requesting one lock state, additional lock states
2899** are inserted in between. The locking might fail on one of the later
2900** transitions leaving the lock state different from what it started but
2901** still short of its goal. The following chart shows the allowed
2902** transitions and the inserted intermediate states:
2903**
2904** UNLOCKED -> SHARED
2905** SHARED -> RESERVED
2906** SHARED -> (PENDING) -> EXCLUSIVE
2907** RESERVED -> (PENDING) -> EXCLUSIVE
2908** PENDING -> EXCLUSIVE
2909**
2910** This routine will only increase a lock. Use the sqlite3OsUnlock()
2911** routine to lower a locking level.
2912*/
drh308c2a52010-05-14 11:30:18 +00002913static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002914 int rc = SQLITE_OK;
2915 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002916 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002917 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002918
2919 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002920 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2921 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002922 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002923
drhbfe66312006-10-03 17:40:40 +00002924 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002925 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002926 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002927 */
drh308c2a52010-05-14 11:30:18 +00002928 if( pFile->eFileLock>=eFileLock ){
2929 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2930 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002931 return SQLITE_OK;
2932 }
2933
2934 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002935 ** (1) We never move from unlocked to anything higher than shared lock.
2936 ** (2) SQLite never explicitly requests a pendig lock.
2937 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002938 */
drh308c2a52010-05-14 11:30:18 +00002939 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2940 assert( eFileLock!=PENDING_LOCK );
2941 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002942
drh8af6c222010-05-14 12:43:01 +00002943 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002944 */
drh8af6c222010-05-14 12:43:01 +00002945 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002946 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002947
2948 /* If some thread using this PID has a lock via a different unixFile*
2949 ** handle that precludes the requested lock, return BUSY.
2950 */
drh8af6c222010-05-14 12:43:01 +00002951 if( (pFile->eFileLock!=pInode->eFileLock &&
2952 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002953 ){
2954 rc = SQLITE_BUSY;
2955 goto afp_end_lock;
2956 }
2957
2958 /* If a SHARED lock is requested, and some thread using this PID already
2959 ** has a SHARED or RESERVED lock, then increment reference counts and
2960 ** return SQLITE_OK.
2961 */
drh308c2a52010-05-14 11:30:18 +00002962 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002963 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002964 assert( eFileLock==SHARED_LOCK );
2965 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002966 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002967 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002968 pInode->nShared++;
2969 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002970 goto afp_end_lock;
2971 }
drhbfe66312006-10-03 17:40:40 +00002972
2973 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002974 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2975 ** be released.
2976 */
drh308c2a52010-05-14 11:30:18 +00002977 if( eFileLock==SHARED_LOCK
2978 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002979 ){
2980 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002981 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002982 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002983 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002984 goto afp_end_lock;
2985 }
2986 }
2987
2988 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002989 ** operating system calls for the specified lock.
2990 */
drh308c2a52010-05-14 11:30:18 +00002991 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002992 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002993 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002994
drh8af6c222010-05-14 12:43:01 +00002995 assert( pInode->nShared==0 );
2996 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002997
2998 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002999 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00003000 /* note that the quality of the randomness doesn't matter that much */
3001 lk = random();
drh8af6c222010-05-14 12:43:01 +00003002 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00003003 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003004 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00003005 if( IS_LOCK_ERROR(lrc1) ){
3006 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00003007 }
aswift5b1a2562008-08-22 00:22:35 +00003008 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00003009 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00003010
aswift5b1a2562008-08-22 00:22:35 +00003011 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00003012 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00003013 rc = lrc1;
3014 goto afp_end_lock;
3015 } else if( IS_LOCK_ERROR(lrc2) ){
3016 rc = lrc2;
3017 goto afp_end_lock;
3018 } else if( lrc1 != SQLITE_OK ) {
3019 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003020 } else {
drh308c2a52010-05-14 11:30:18 +00003021 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003022 pInode->nLock++;
3023 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003024 }
drh8af6c222010-05-14 12:43:01 +00003025 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003026 /* We are trying for an exclusive lock but another thread in this
3027 ** same process is still holding a shared lock. */
3028 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003029 }else{
3030 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3031 ** assumed that there is a SHARED or greater lock on the file
3032 ** already.
3033 */
3034 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003035 assert( 0!=pFile->eFileLock );
3036 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003037 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003038 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003039 if( !failed ){
3040 context->reserved = 1;
3041 }
drhbfe66312006-10-03 17:40:40 +00003042 }
drh308c2a52010-05-14 11:30:18 +00003043 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003044 /* Acquire an EXCLUSIVE lock */
3045
3046 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003047 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003048 */
drh6b9d6dd2008-12-03 19:34:47 +00003049 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003050 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003051 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003052 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003053 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003054 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003055 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003056 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003057 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3058 ** a critical I/O error
3059 */
drh2e233812017-08-22 15:21:54 +00003060 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003061 SQLITE_IOERR_LOCK;
3062 goto afp_end_lock;
3063 }
3064 }else{
aswift5b1a2562008-08-22 00:22:35 +00003065 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003066 }
3067 }
aswift5b1a2562008-08-22 00:22:35 +00003068 if( failed ){
3069 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003070 }
3071 }
3072
3073 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003074 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003075 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003076 }else if( eFileLock==EXCLUSIVE_LOCK ){
3077 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003078 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003079 }
3080
3081afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003082 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003083 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3084 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003085 return rc;
3086}
3087
3088/*
drh308c2a52010-05-14 11:30:18 +00003089** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003090** must be either NO_LOCK or SHARED_LOCK.
3091**
3092** If the locking level of the file descriptor is already at or below
3093** the requested locking level, this routine is a no-op.
3094*/
drh308c2a52010-05-14 11:30:18 +00003095static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003096 int rc = SQLITE_OK;
3097 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003098 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003099 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3100 int skipShared = 0;
3101#ifdef SQLITE_TEST
3102 int h = pFile->h;
3103#endif
drhbfe66312006-10-03 17:40:40 +00003104
3105 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003106 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003107 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003108 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003109
drh308c2a52010-05-14 11:30:18 +00003110 assert( eFileLock<=SHARED_LOCK );
3111 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003112 return SQLITE_OK;
3113 }
drh8af6c222010-05-14 12:43:01 +00003114 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003115 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003116 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003117 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003118 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003119 SimulateIOErrorBenign(1);
3120 SimulateIOError( h=(-1) )
3121 SimulateIOErrorBenign(0);
3122
drhd3d8c042012-05-29 17:02:40 +00003123#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003124 /* When reducing a lock such that other processes can start
3125 ** reading the database file again, make sure that the
3126 ** transaction counter was updated if any part of the database
3127 ** file changed. If the transaction counter is not updated,
3128 ** other connections to the same file might not realize that
3129 ** the file has changed and hence might not know to flush their
3130 ** cache. The use of a stale cache can lead to database corruption.
3131 */
3132 assert( pFile->inNormalWrite==0
3133 || pFile->dbUpdate==0
3134 || pFile->transCntrChng==1 );
3135 pFile->inNormalWrite = 0;
3136#endif
aswiftaebf4132008-11-21 00:10:35 +00003137
drh308c2a52010-05-14 11:30:18 +00003138 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003139 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003140 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003141 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003142 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003143 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3144 } else {
3145 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003146 }
3147 }
drh308c2a52010-05-14 11:30:18 +00003148 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003149 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003150 }
drh308c2a52010-05-14 11:30:18 +00003151 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003152 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3153 if( !rc ){
3154 context->reserved = 0;
3155 }
aswiftaebf4132008-11-21 00:10:35 +00003156 }
drh8af6c222010-05-14 12:43:01 +00003157 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3158 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003159 }
aswiftaebf4132008-11-21 00:10:35 +00003160 }
drh308c2a52010-05-14 11:30:18 +00003161 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003162
drh7ed97b92010-01-20 13:07:21 +00003163 /* Decrement the shared lock counter. Release the lock using an
3164 ** OS call only when all threads in this same process have released
3165 ** the lock.
3166 */
drh8af6c222010-05-14 12:43:01 +00003167 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3168 pInode->nShared--;
3169 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003170 SimulateIOErrorBenign(1);
3171 SimulateIOError( h=(-1) )
3172 SimulateIOErrorBenign(0);
3173 if( !skipShared ){
3174 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3175 }
3176 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003177 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003178 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003179 }
3180 }
3181 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003182 pInode->nLock--;
3183 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003184 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003185 }
drhbfe66312006-10-03 17:40:40 +00003186 }
drh7ed97b92010-01-20 13:07:21 +00003187
drhda6dc242018-07-23 21:10:37 +00003188 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003189 if( rc==SQLITE_OK ){
3190 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003191 }
drhbfe66312006-10-03 17:40:40 +00003192 return rc;
3193}
3194
3195/*
drh339eb0b2008-03-07 15:34:11 +00003196** Close a file & cleanup AFP specific locking context
3197*/
danielk1977e339d652008-06-28 11:23:00 +00003198static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003199 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003200 unixFile *pFile = (unixFile*)id;
3201 assert( id!=0 );
3202 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003203 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003204 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003205 if( pFile->pInode ){
3206 unixInodeInfo *pInode = pFile->pInode;
3207 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003208 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003209 /* If there are outstanding locks, do not actually close the file just
3210 ** yet because that would clear those locks. Instead, add the file
3211 ** descriptor to pInode->aPending. It will be automatically closed when
3212 ** the last lock is cleared.
3213 */
3214 setPendingFd(pFile);
3215 }
3216 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003217 }
drha8de1e12015-11-30 00:05:39 +00003218 releaseInodeInfo(pFile);
3219 sqlite3_free(pFile->lockingContext);
3220 rc = closeUnixFile(id);
3221 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003222 return rc;
drhbfe66312006-10-03 17:40:40 +00003223}
3224
drhd2cb50b2009-01-09 21:41:17 +00003225#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003226/*
3227** The code above is the AFP lock implementation. The code is specific
3228** to MacOSX and does not work on other unix platforms. No alternative
3229** is available. If you don't compile for a mac, then the "unix-afp"
3230** VFS is not available.
3231**
3232********************* End of the AFP lock implementation **********************
3233******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003234
drh7ed97b92010-01-20 13:07:21 +00003235/******************************************************************************
3236*************************** Begin NFS Locking ********************************/
3237
3238#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3239/*
drh308c2a52010-05-14 11:30:18 +00003240 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003241 ** must be either NO_LOCK or SHARED_LOCK.
3242 **
3243 ** If the locking level of the file descriptor is already at or below
3244 ** the requested locking level, this routine is a no-op.
3245 */
drh308c2a52010-05-14 11:30:18 +00003246static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003247 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003248}
3249
3250#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3251/*
3252** The code above is the NFS lock implementation. The code is specific
3253** to MacOSX and does not work on other unix platforms. No alternative
3254** is available.
3255**
3256********************* End of the NFS lock implementation **********************
3257******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003258
3259/******************************************************************************
3260**************** Non-locking sqlite3_file methods *****************************
3261**
3262** The next division contains implementations for all methods of the
3263** sqlite3_file object other than the locking methods. The locking
3264** methods were defined in divisions above (one locking method per
3265** division). Those methods that are common to all locking modes
3266** are gather together into this division.
3267*/
drhbfe66312006-10-03 17:40:40 +00003268
3269/*
drh734c9862008-11-28 15:37:20 +00003270** Seek to the offset passed as the second argument, then read cnt
3271** bytes into pBuf. Return the number of bytes actually read.
3272**
3273** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3274** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3275** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003276** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003277** See tickets #2741 and #2681.
3278**
3279** To avoid stomping the errno value on a failed read the lastErrno value
3280** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003281*/
drh734c9862008-11-28 15:37:20 +00003282static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3283 int got;
drh58024642011-11-07 18:16:00 +00003284 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003285#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3286 i64 newOffset;
3287#endif
drh734c9862008-11-28 15:37:20 +00003288 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003289 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003290 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003291 do{
drh734c9862008-11-28 15:37:20 +00003292#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003293 got = osPread(id->h, pBuf, cnt, offset);
3294 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003295#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003296 got = osPread64(id->h, pBuf, cnt, offset);
3297 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003298#else
drha46cadc2016-03-04 03:02:06 +00003299 newOffset = lseek(id->h, offset, SEEK_SET);
3300 SimulateIOError( newOffset = -1 );
3301 if( newOffset<0 ){
3302 storeLastErrno((unixFile*)id, errno);
3303 return -1;
3304 }
3305 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003306#endif
drh58024642011-11-07 18:16:00 +00003307 if( got==cnt ) break;
3308 if( got<0 ){
3309 if( errno==EINTR ){ got = 1; continue; }
3310 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003311 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003312 break;
3313 }else if( got>0 ){
3314 cnt -= got;
3315 offset += got;
3316 prior += got;
3317 pBuf = (void*)(got + (char*)pBuf);
3318 }
3319 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003320 TIMER_END;
drh58024642011-11-07 18:16:00 +00003321 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3322 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3323 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003324}
3325
3326/*
drh734c9862008-11-28 15:37:20 +00003327** Read data from a file into a buffer. Return SQLITE_OK if all
3328** bytes were read successfully and SQLITE_IOERR if anything goes
3329** wrong.
drh339eb0b2008-03-07 15:34:11 +00003330*/
drh734c9862008-11-28 15:37:20 +00003331static int unixRead(
3332 sqlite3_file *id,
3333 void *pBuf,
3334 int amt,
3335 sqlite3_int64 offset
3336){
dan08da86a2009-08-21 17:18:03 +00003337 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003338 int got;
3339 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003340 assert( offset>=0 );
3341 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003342
dan08da86a2009-08-21 17:18:03 +00003343 /* If this is a database file (not a journal, master-journal or temp
3344 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003345#if 0
drhc68886b2017-08-18 16:09:52 +00003346 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003347 || offset>=PENDING_BYTE+512
3348 || offset+amt<=PENDING_BYTE
3349 );
dan7c246102010-04-12 19:00:29 +00003350#endif
drh08c6d442009-02-09 17:34:07 +00003351
drh9b4c59f2013-04-15 17:03:42 +00003352#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003353 /* Deal with as much of this read request as possible by transfering
3354 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003355 if( offset<pFile->mmapSize ){
3356 if( offset+amt <= pFile->mmapSize ){
3357 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3358 return SQLITE_OK;
3359 }else{
3360 int nCopy = pFile->mmapSize - offset;
3361 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3362 pBuf = &((u8 *)pBuf)[nCopy];
3363 amt -= nCopy;
3364 offset += nCopy;
3365 }
3366 }
drh6e0b6d52013-04-09 16:19:20 +00003367#endif
danf23da962013-03-23 21:00:41 +00003368
dan08da86a2009-08-21 17:18:03 +00003369 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003370 if( got==amt ){
3371 return SQLITE_OK;
3372 }else if( got<0 ){
3373 /* lastErrno set by seekAndRead */
3374 return SQLITE_IOERR_READ;
3375 }else{
drh4bf66fd2015-02-19 02:43:02 +00003376 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003377 /* Unread parts of the buffer must be zero-filled */
3378 memset(&((char*)pBuf)[got], 0, amt-got);
3379 return SQLITE_IOERR_SHORT_READ;
3380 }
3381}
3382
3383/*
dan47a2b4a2013-04-26 16:09:29 +00003384** Attempt to seek the file-descriptor passed as the first argument to
3385** absolute offset iOff, then attempt to write nBuf bytes of data from
3386** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3387** return the actual number of bytes written (which may be less than
3388** nBuf).
3389*/
3390static int seekAndWriteFd(
3391 int fd, /* File descriptor to write to */
3392 i64 iOff, /* File offset to begin writing at */
3393 const void *pBuf, /* Copy data from this buffer to the file */
3394 int nBuf, /* Size of buffer pBuf in bytes */
3395 int *piErrno /* OUT: Error number if error occurs */
3396){
3397 int rc = 0; /* Value returned by system call */
3398
3399 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003400 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003401 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003402 nBuf &= 0x1ffff;
3403 TIMER_START;
3404
3405#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003406 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003407#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003408 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003409#else
3410 do{
3411 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003412 SimulateIOError( iSeek = -1 );
3413 if( iSeek<0 ){
3414 rc = -1;
3415 break;
dan47a2b4a2013-04-26 16:09:29 +00003416 }
3417 rc = osWrite(fd, pBuf, nBuf);
3418 }while( rc<0 && errno==EINTR );
3419#endif
3420
3421 TIMER_END;
3422 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3423
drhe1818ec2015-12-01 16:21:35 +00003424 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003425 return rc;
3426}
3427
3428
3429/*
drh734c9862008-11-28 15:37:20 +00003430** Seek to the offset in id->offset then read cnt bytes into pBuf.
3431** Return the number of bytes actually read. Update the offset.
3432**
3433** To avoid stomping the errno value on a failed write the lastErrno value
3434** is set before returning.
3435*/
3436static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003437 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003438}
3439
3440
3441/*
3442** Write data from a buffer into a file. Return SQLITE_OK on success
3443** or some other error code on failure.
3444*/
3445static int unixWrite(
3446 sqlite3_file *id,
3447 const void *pBuf,
3448 int amt,
3449 sqlite3_int64 offset
3450){
dan08da86a2009-08-21 17:18:03 +00003451 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003452 int wrote = 0;
3453 assert( id );
3454 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003455
dan08da86a2009-08-21 17:18:03 +00003456 /* If this is a database file (not a journal, master-journal or temp
3457 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003458#if 0
drhc68886b2017-08-18 16:09:52 +00003459 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003460 || offset>=PENDING_BYTE+512
3461 || offset+amt<=PENDING_BYTE
3462 );
dan7c246102010-04-12 19:00:29 +00003463#endif
drh08c6d442009-02-09 17:34:07 +00003464
drhd3d8c042012-05-29 17:02:40 +00003465#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003466 /* If we are doing a normal write to a database file (as opposed to
3467 ** doing a hot-journal rollback or a write to some file other than a
3468 ** normal database file) then record the fact that the database
3469 ** has changed. If the transaction counter is modified, record that
3470 ** fact too.
3471 */
dan08da86a2009-08-21 17:18:03 +00003472 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003473 pFile->dbUpdate = 1; /* The database has been modified */
3474 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003475 int rc;
drh8f941bc2009-01-14 23:03:40 +00003476 char oldCntr[4];
3477 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003478 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003479 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003480 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003481 pFile->transCntrChng = 1; /* The transaction counter has changed */
3482 }
3483 }
3484 }
3485#endif
3486
danfe33e392015-11-17 20:56:06 +00003487#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003488 /* Deal with as much of this write request as possible by transfering
3489 ** data from the memory mapping using memcpy(). */
3490 if( offset<pFile->mmapSize ){
3491 if( offset+amt <= pFile->mmapSize ){
3492 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3493 return SQLITE_OK;
3494 }else{
3495 int nCopy = pFile->mmapSize - offset;
3496 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3497 pBuf = &((u8 *)pBuf)[nCopy];
3498 amt -= nCopy;
3499 offset += nCopy;
3500 }
3501 }
drh6e0b6d52013-04-09 16:19:20 +00003502#endif
drh02bf8b42015-09-01 23:51:53 +00003503
3504 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003505 amt -= wrote;
3506 offset += wrote;
3507 pBuf = &((char*)pBuf)[wrote];
3508 }
3509 SimulateIOError(( wrote=(-1), amt=1 ));
3510 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003511
drh02bf8b42015-09-01 23:51:53 +00003512 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003513 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003514 /* lastErrno set by seekAndWrite */
3515 return SQLITE_IOERR_WRITE;
3516 }else{
drh4bf66fd2015-02-19 02:43:02 +00003517 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003518 return SQLITE_FULL;
3519 }
3520 }
dan6e09d692010-07-27 18:34:15 +00003521
drh734c9862008-11-28 15:37:20 +00003522 return SQLITE_OK;
3523}
3524
3525#ifdef SQLITE_TEST
3526/*
3527** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003528** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003529*/
3530int sqlite3_sync_count = 0;
3531int sqlite3_fullsync_count = 0;
3532#endif
3533
3534/*
drh89240432009-03-25 01:06:01 +00003535** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003536** Others do no. To be safe, we will stick with the (slightly slower)
3537** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003538** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003539*/
drhf7a4a1b2015-01-10 18:02:45 +00003540#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003541# define fdatasync fsync
3542#endif
3543
3544/*
3545** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3546** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3547** only available on Mac OS X. But that could change.
3548*/
3549#ifdef F_FULLFSYNC
3550# define HAVE_FULLFSYNC 1
3551#else
3552# define HAVE_FULLFSYNC 0
3553#endif
3554
3555
3556/*
3557** The fsync() system call does not work as advertised on many
3558** unix systems. The following procedure is an attempt to make
3559** it work better.
3560**
3561** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3562** for testing when we want to run through the test suite quickly.
3563** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3564** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3565** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003566**
3567** SQLite sets the dataOnly flag if the size of the file is unchanged.
3568** The idea behind dataOnly is that it should only write the file content
3569** to disk, not the inode. We only set dataOnly if the file size is
3570** unchanged since the file size is part of the inode. However,
3571** Ted Ts'o tells us that fdatasync() will also write the inode if the
3572** file size has changed. The only real difference between fdatasync()
3573** and fsync(), Ted tells us, is that fdatasync() will not flush the
3574** inode if the mtime or owner or other inode attributes have changed.
3575** We only care about the file size, not the other file attributes, so
3576** as far as SQLite is concerned, an fdatasync() is always adequate.
3577** So, we always use fdatasync() if it is available, regardless of
3578** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003579*/
3580static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003581 int rc;
drh734c9862008-11-28 15:37:20 +00003582
3583 /* The following "ifdef/elif/else/" block has the same structure as
3584 ** the one below. It is replicated here solely to avoid cluttering
3585 ** up the real code with the UNUSED_PARAMETER() macros.
3586 */
3587#ifdef SQLITE_NO_SYNC
3588 UNUSED_PARAMETER(fd);
3589 UNUSED_PARAMETER(fullSync);
3590 UNUSED_PARAMETER(dataOnly);
3591#elif HAVE_FULLFSYNC
3592 UNUSED_PARAMETER(dataOnly);
3593#else
3594 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003595 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003596#endif
3597
3598 /* Record the number of times that we do a normal fsync() and
3599 ** FULLSYNC. This is used during testing to verify that this procedure
3600 ** gets called with the correct arguments.
3601 */
3602#ifdef SQLITE_TEST
3603 if( fullSync ) sqlite3_fullsync_count++;
3604 sqlite3_sync_count++;
3605#endif
3606
3607 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003608 ** no-op. But go ahead and call fstat() to validate the file
3609 ** descriptor as we need a method to provoke a failure during
3610 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003611 */
3612#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003613 {
3614 struct stat buf;
3615 rc = osFstat(fd, &buf);
3616 }
drh734c9862008-11-28 15:37:20 +00003617#elif HAVE_FULLFSYNC
3618 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003619 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003620 }else{
3621 rc = 1;
3622 }
3623 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003624 ** It shouldn't be possible for fullfsync to fail on the local
3625 ** file system (on OSX), so failure indicates that FULLFSYNC
3626 ** isn't supported for this file system. So, attempt an fsync
3627 ** and (for now) ignore the overhead of a superfluous fcntl call.
3628 ** It'd be better to detect fullfsync support once and avoid
3629 ** the fcntl call every time sync is called.
3630 */
drh734c9862008-11-28 15:37:20 +00003631 if( rc ) rc = fsync(fd);
3632
drh7ed97b92010-01-20 13:07:21 +00003633#elif defined(__APPLE__)
3634 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3635 ** so currently we default to the macro that redefines fdatasync to fsync
3636 */
3637 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003638#else
drh0b647ff2009-03-21 14:41:04 +00003639 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003640#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003641 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003642 rc = fsync(fd);
3643 }
drh0b647ff2009-03-21 14:41:04 +00003644#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003645#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3646
3647 if( OS_VXWORKS && rc!= -1 ){
3648 rc = 0;
3649 }
chw97185482008-11-17 08:05:31 +00003650 return rc;
drhbfe66312006-10-03 17:40:40 +00003651}
3652
drh734c9862008-11-28 15:37:20 +00003653/*
drh0059eae2011-08-08 23:48:40 +00003654** Open a file descriptor to the directory containing file zFilename.
3655** If successful, *pFd is set to the opened file descriptor and
3656** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3657** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3658** value.
3659**
drh90315a22011-08-10 01:52:12 +00003660** The directory file descriptor is used for only one thing - to
3661** fsync() a directory to make sure file creation and deletion events
3662** are flushed to disk. Such fsyncs are not needed on newer
3663** journaling filesystems, but are required on older filesystems.
3664**
3665** This routine can be overridden using the xSetSysCall interface.
3666** The ability to override this routine was added in support of the
3667** chromium sandbox. Opening a directory is a security risk (we are
3668** told) so making it overrideable allows the chromium sandbox to
3669** replace this routine with a harmless no-op. To make this routine
3670** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3671** *pFd set to a negative number.
3672**
drh0059eae2011-08-08 23:48:40 +00003673** If SQLITE_OK is returned, the caller is responsible for closing
3674** the file descriptor *pFd using close().
3675*/
3676static int openDirectory(const char *zFilename, int *pFd){
3677 int ii;
3678 int fd = -1;
3679 char zDirname[MAX_PATHNAME+1];
3680
3681 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003682 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3683 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003684 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003685 }else{
3686 if( zDirname[0]!='/' ) zDirname[0] = '.';
3687 zDirname[1] = 0;
3688 }
drh3b9f1542020-04-20 17:35:32 +00003689 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
drhdc278512015-12-07 18:18:33 +00003690 if( fd>=0 ){
3691 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003692 }
3693 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003694 if( fd>=0 ) return SQLITE_OK;
3695 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003696}
3697
3698/*
drh734c9862008-11-28 15:37:20 +00003699** Make sure all writes to a particular file are committed to disk.
3700**
3701** If dataOnly==0 then both the file itself and its metadata (file
3702** size, access time, etc) are synced. If dataOnly!=0 then only the
3703** file data is synced.
3704**
3705** Under Unix, also make sure that the directory entry for the file
3706** has been created by fsync-ing the directory that contains the file.
3707** If we do not do this and we encounter a power failure, the directory
3708** entry for the journal might not exist after we reboot. The next
3709** SQLite to access the file will not know that the journal exists (because
3710** the directory entry for the journal was never created) and the transaction
3711** will not roll back - possibly leading to database corruption.
3712*/
3713static int unixSync(sqlite3_file *id, int flags){
3714 int rc;
3715 unixFile *pFile = (unixFile*)id;
3716
3717 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3718 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3719
3720 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3721 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3722 || (flags&0x0F)==SQLITE_SYNC_FULL
3723 );
3724
3725 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3726 ** line is to test that doing so does not cause any problems.
3727 */
3728 SimulateDiskfullError( return SQLITE_FULL );
3729
3730 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003731 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003732 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3733 SimulateIOError( rc=1 );
3734 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003735 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003736 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003737 }
drh0059eae2011-08-08 23:48:40 +00003738
3739 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003740 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003741 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003742 */
3743 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3744 int dirfd;
3745 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003746 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003747 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003748 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003749 full_fsync(dirfd, 0, 0);
3750 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003751 }else{
3752 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003753 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003754 }
drh0059eae2011-08-08 23:48:40 +00003755 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003756 }
3757 return rc;
3758}
3759
3760/*
3761** Truncate an open file to a specified size
3762*/
3763static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003764 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003765 int rc;
dan6e09d692010-07-27 18:34:15 +00003766 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003767 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003768
3769 /* If the user has configured a chunk-size for this file, truncate the
3770 ** file so that it consists of an integer number of chunks (i.e. the
3771 ** actual file size after the operation may be larger than the requested
3772 ** size).
3773 */
drhb8af4b72012-04-05 20:04:39 +00003774 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003775 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3776 }
3777
dan2ee53412014-09-06 16:49:40 +00003778 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003779 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003780 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003781 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003782 }else{
drhd3d8c042012-05-29 17:02:40 +00003783#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003784 /* If we are doing a normal write to a database file (as opposed to
3785 ** doing a hot-journal rollback or a write to some file other than a
3786 ** normal database file) and we truncate the file to zero length,
3787 ** that effectively updates the change counter. This might happen
3788 ** when restoring a database using the backup API from a zero-length
3789 ** source.
3790 */
dan6e09d692010-07-27 18:34:15 +00003791 if( pFile->inNormalWrite && nByte==0 ){
3792 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003793 }
danf23da962013-03-23 21:00:41 +00003794#endif
danc0003312013-03-22 17:46:11 +00003795
mistachkine98844f2013-08-24 00:59:24 +00003796#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003797 /* If the file was just truncated to a size smaller than the currently
3798 ** mapped region, reduce the effective mapping size as well. SQLite will
3799 ** use read() and write() to access data beyond this point from now on.
3800 */
3801 if( nByte<pFile->mmapSize ){
3802 pFile->mmapSize = nByte;
3803 }
mistachkine98844f2013-08-24 00:59:24 +00003804#endif
drh3313b142009-11-06 04:13:18 +00003805
drh734c9862008-11-28 15:37:20 +00003806 return SQLITE_OK;
3807 }
3808}
3809
3810/*
3811** Determine the current size of a file in bytes
3812*/
3813static int unixFileSize(sqlite3_file *id, i64 *pSize){
3814 int rc;
3815 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003816 assert( id );
3817 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003818 SimulateIOError( rc=1 );
3819 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003820 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003821 return SQLITE_IOERR_FSTAT;
3822 }
3823 *pSize = buf.st_size;
3824
drh8af6c222010-05-14 12:43:01 +00003825 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003826 ** writes a single byte into that file in order to work around a bug
3827 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3828 ** layers, we need to report this file size as zero even though it is
3829 ** really 1. Ticket #3260.
3830 */
3831 if( *pSize==1 ) *pSize = 0;
3832
3833
3834 return SQLITE_OK;
3835}
3836
drhd2cb50b2009-01-09 21:41:17 +00003837#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003838/*
3839** Handler for proxy-locking file-control verbs. Defined below in the
3840** proxying locking division.
3841*/
3842static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003843#endif
drh715ff302008-12-03 22:32:44 +00003844
dan502019c2010-07-28 14:26:17 +00003845/*
3846** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003847** file-control operation. Enlarge the database to nBytes in size
3848** (rounded up to the next chunk-size). If the database is already
3849** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003850*/
3851static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003852 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003853 i64 nSize; /* Required file size */
3854 struct stat buf; /* Used to hold return values of fstat() */
3855
drh4bf66fd2015-02-19 02:43:02 +00003856 if( osFstat(pFile->h, &buf) ){
3857 return SQLITE_IOERR_FSTAT;
3858 }
dan502019c2010-07-28 14:26:17 +00003859
3860 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3861 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003862
dan502019c2010-07-28 14:26:17 +00003863#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003864 /* The code below is handling the return value of osFallocate()
3865 ** correctly. posix_fallocate() is defined to "returns zero on success,
3866 ** or an error number on failure". See the manpage for details. */
3867 int err;
drhff812312011-02-23 13:33:46 +00003868 do{
dan661d71a2011-03-30 19:08:03 +00003869 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3870 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003871 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003872#else
dan592bf7f2014-12-30 19:58:31 +00003873 /* If the OS does not have posix_fallocate(), fake it. Write a
3874 ** single byte to the last byte in each block that falls entirely
3875 ** within the extended region. Then, if required, a single byte
3876 ** at offset (nSize-1), to set the size of the file correctly.
3877 ** This is a similar technique to that used by glibc on systems
3878 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003879 */
3880 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003881 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003882 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003883
drh053378d2015-12-01 22:09:42 +00003884 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003885 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003886 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003887 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3888 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003889 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003890 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003891 }
dan502019c2010-07-28 14:26:17 +00003892#endif
3893 }
3894 }
3895
mistachkine98844f2013-08-24 00:59:24 +00003896#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003897 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003898 int rc;
3899 if( pFile->szChunk<=0 ){
3900 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003901 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003902 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3903 }
3904 }
3905
3906 rc = unixMapfile(pFile, nByte);
3907 return rc;
3908 }
mistachkine98844f2013-08-24 00:59:24 +00003909#endif
danf23da962013-03-23 21:00:41 +00003910
dan502019c2010-07-28 14:26:17 +00003911 return SQLITE_OK;
3912}
danielk1977ad94b582007-08-20 06:44:22 +00003913
danielk1977e3026632004-06-22 11:29:02 +00003914/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003915** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003916** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3917**
3918** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3919*/
3920static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3921 if( *pArg<0 ){
3922 *pArg = (pFile->ctrlFlags & mask)!=0;
3923 }else if( (*pArg)==0 ){
3924 pFile->ctrlFlags &= ~mask;
3925 }else{
3926 pFile->ctrlFlags |= mask;
3927 }
3928}
3929
drh696b33e2012-12-06 19:01:42 +00003930/* Forward declaration */
3931static int unixGetTempname(int nBuf, char *zBuf);
3932
drhf12b3f62011-12-21 14:42:29 +00003933/*
drh9e33c2c2007-08-31 18:34:59 +00003934** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003935*/
drhcc6bb3e2007-08-31 16:11:35 +00003936static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003937 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003938 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003939#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003940 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3941 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003942 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003943 }
3944 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3945 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003946 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003947 }
3948 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3949 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003950 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003951 }
drhd76dba72017-07-22 16:00:34 +00003952#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003953
drh9e33c2c2007-08-31 18:34:59 +00003954 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003955 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003956 return SQLITE_OK;
3957 }
drh4bf66fd2015-02-19 02:43:02 +00003958 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003959 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003960 return SQLITE_OK;
3961 }
dan6e09d692010-07-27 18:34:15 +00003962 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003963 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003964 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003965 }
drh9ff27ec2010-05-19 19:26:05 +00003966 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003967 int rc;
3968 SimulateIOErrorBenign(1);
3969 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3970 SimulateIOErrorBenign(0);
3971 return rc;
drhf0b190d2011-07-26 16:03:07 +00003972 }
3973 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003974 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3975 return SQLITE_OK;
3976 }
drhcb15f352011-12-23 01:04:17 +00003977 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3978 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003979 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003980 }
drhde60fc22011-12-14 17:53:36 +00003981 case SQLITE_FCNTL_VFSNAME: {
3982 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3983 return SQLITE_OK;
3984 }
drh696b33e2012-12-06 19:01:42 +00003985 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003986 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003987 if( zTFile ){
3988 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3989 *(char**)pArg = zTFile;
3990 }
3991 return SQLITE_OK;
3992 }
drhb959a012013-12-07 12:29:22 +00003993 case SQLITE_FCNTL_HAS_MOVED: {
3994 *(int*)pArg = fileHasMoved(pFile);
3995 return SQLITE_OK;
3996 }
drhf0119b22018-03-26 17:40:53 +00003997#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3998 case SQLITE_FCNTL_LOCK_TIMEOUT: {
dan97ccc1b2020-03-27 17:23:17 +00003999 int iOld = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00004000 pFile->iBusyTimeout = *(int*)pArg;
dan97ccc1b2020-03-27 17:23:17 +00004001 *(int*)pArg = iOld;
drhf0119b22018-03-26 17:40:53 +00004002 return SQLITE_OK;
4003 }
4004#endif
mistachkine98844f2013-08-24 00:59:24 +00004005#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00004006 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00004007 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00004008 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00004009 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4010 newLimit = sqlite3GlobalConfig.mxMmap;
4011 }
dan43c1e622017-08-07 18:13:28 +00004012
4013 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00004014 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4015 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00004016 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00004017 newLimit = (newLimit & 0x7FFFFFFF);
4018 }
4019
drh9b4c59f2013-04-15 17:03:42 +00004020 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004021 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004022 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004023 if( pFile->mmapSize>0 ){
4024 unixUnmapfile(pFile);
4025 rc = unixMapfile(pFile, -1);
4026 }
danbcb8a862013-04-08 15:30:41 +00004027 }
drh34e258c2013-05-23 01:40:53 +00004028 return rc;
danb2d3de32013-03-14 18:34:37 +00004029 }
mistachkine98844f2013-08-24 00:59:24 +00004030#endif
drhd3d8c042012-05-29 17:02:40 +00004031#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004032 /* The pager calls this method to signal that it has done
4033 ** a rollback and that the database is therefore unchanged and
4034 ** it hence it is OK for the transaction change counter to be
4035 ** unchanged.
4036 */
4037 case SQLITE_FCNTL_DB_UNCHANGED: {
4038 ((unixFile*)id)->dbUpdate = 0;
4039 return SQLITE_OK;
4040 }
4041#endif
drhd2cb50b2009-01-09 21:41:17 +00004042#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004043 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4044 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004045 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004046 }
drhd2cb50b2009-01-09 21:41:17 +00004047#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00004048 }
drh0b52b7d2011-01-26 19:46:22 +00004049 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004050}
4051
4052/*
danefe16972017-07-20 19:49:14 +00004053** If pFd->sectorSize is non-zero when this function is called, it is a
4054** no-op. Otherwise, the values of pFd->sectorSize and
4055** pFd->deviceCharacteristics are set according to the file-system
4056** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004057**
danefe16972017-07-20 19:49:14 +00004058** There are two versions of this function. One for QNX and one for all
4059** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004060*/
danefe16972017-07-20 19:49:14 +00004061#ifndef __QNXNTO__
4062static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004063 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004064 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004065#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004066 int res;
dan9d709542017-07-21 21:06:24 +00004067 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004068
danefe16972017-07-20 19:49:14 +00004069 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004070 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4071 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004072 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004073 }
drhd76dba72017-07-22 16:00:34 +00004074#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004075
4076 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4077 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4078 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4079 }
4080
4081 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4082 }
4083}
4084#else
drh537dddf2012-10-26 13:46:24 +00004085#include <sys/dcmd_blk.h>
4086#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004087static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004088 if( pFile->sectorSize == 0 ){
4089 struct statvfs fsInfo;
4090
4091 /* Set defaults for non-supported filesystems */
4092 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4093 pFile->deviceCharacteristics = 0;
4094 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004095 return;
drh537dddf2012-10-26 13:46:24 +00004096 }
4097
4098 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4099 pFile->sectorSize = fsInfo.f_bsize;
4100 pFile->deviceCharacteristics =
4101 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4102 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4103 ** the write succeeds */
4104 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4105 ** so it is ordered */
4106 0;
4107 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4108 pFile->sectorSize = fsInfo.f_bsize;
4109 pFile->deviceCharacteristics =
4110 /* etfs cluster size writes are atomic */
4111 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4112 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4113 ** the write succeeds */
4114 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4115 ** so it is ordered */
4116 0;
4117 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4118 pFile->sectorSize = fsInfo.f_bsize;
4119 pFile->deviceCharacteristics =
4120 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4121 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4122 ** the write succeeds */
4123 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4124 ** so it is ordered */
4125 0;
4126 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4127 pFile->sectorSize = fsInfo.f_bsize;
4128 pFile->deviceCharacteristics =
4129 /* full bitset of atomics from max sector size and smaller */
4130 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4131 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4132 ** so it is ordered */
4133 0;
4134 }else if( strstr(fsInfo.f_basetype, "dos") ){
4135 pFile->sectorSize = fsInfo.f_bsize;
4136 pFile->deviceCharacteristics =
4137 /* full bitset of atomics from max sector size and smaller */
4138 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4139 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4140 ** so it is ordered */
4141 0;
4142 }else{
4143 pFile->deviceCharacteristics =
4144 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4145 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4146 ** the write succeeds */
4147 0;
4148 }
4149 }
4150 /* Last chance verification. If the sector size isn't a multiple of 512
4151 ** then it isn't valid.*/
4152 if( pFile->sectorSize % 512 != 0 ){
4153 pFile->deviceCharacteristics = 0;
4154 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4155 }
drh537dddf2012-10-26 13:46:24 +00004156}
danefe16972017-07-20 19:49:14 +00004157#endif
4158
4159/*
4160** Return the sector size in bytes of the underlying block device for
4161** the specified file. This is almost always 512 bytes, but may be
4162** larger for some devices.
4163**
4164** SQLite code assumes this function cannot fail. It also assumes that
4165** if two files are created in the same file-system directory (i.e.
4166** a database and its journal file) that the sector size will be the
4167** same for both.
4168*/
4169static int unixSectorSize(sqlite3_file *id){
4170 unixFile *pFd = (unixFile*)id;
4171 setDeviceCharacteristics(pFd);
4172 return pFd->sectorSize;
4173}
danielk1977a3d4c882007-03-23 10:08:38 +00004174
danielk197790949c22007-08-17 16:50:38 +00004175/*
drhf12b3f62011-12-21 14:42:29 +00004176** Return the device characteristics for the file.
4177**
drhcb15f352011-12-23 01:04:17 +00004178** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004179** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004180** file system does not always provide powersafe overwrites. (In other
4181** words, after a power-loss event, parts of the file that were never
4182** written might end up being altered.) However, non-PSOW behavior is very,
4183** very rare. And asserting PSOW makes a large reduction in the amount
4184** of required I/O for journaling, since a lot of padding is eliminated.
4185** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4186** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004187*/
drhf12b3f62011-12-21 14:42:29 +00004188static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004189 unixFile *pFd = (unixFile*)id;
4190 setDeviceCharacteristics(pFd);
4191 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004192}
4193
dan702eec12014-06-23 10:04:58 +00004194#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004195
dan702eec12014-06-23 10:04:58 +00004196/*
4197** Return the system page size.
4198**
4199** This function should not be called directly by other code in this file.
4200** Instead, it should be called via macro osGetpagesize().
4201*/
4202static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004203#if OS_VXWORKS
4204 return 1024;
4205#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004206 return getpagesize();
4207#else
4208 return (int)sysconf(_SC_PAGESIZE);
4209#endif
4210}
4211
4212#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4213
4214#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004215
4216/*
drhd91c68f2010-05-14 14:52:25 +00004217** Object used to represent an shared memory buffer.
4218**
4219** When multiple threads all reference the same wal-index, each thread
4220** has its own unixShm object, but they all point to a single instance
4221** of this unixShmNode object. In other words, each wal-index is opened
4222** only once per process.
4223**
4224** Each unixShmNode object is connected to a single unixInodeInfo object.
4225** We could coalesce this object into unixInodeInfo, but that would mean
4226** every open file that does not use shared memory (in other words, most
4227** open files) would have to carry around this extra information. So
4228** the unixInodeInfo object contains a pointer to this unixShmNode object
4229** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004230**
4231** unixMutexHeld() must be true when creating or destroying
4232** this object or while reading or writing the following fields:
4233**
4234** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004235**
4236** The following fields are read-only after the object is created:
4237**
drh8820c8d2018-10-02 19:58:08 +00004238** hShm
drhd9e5c4f2010-05-12 18:01:39 +00004239** zFilename
4240**
drh8820c8d2018-10-02 19:58:08 +00004241** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004242** unixMutexHeld() is true when reading or writing any other field
4243** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004244*/
drhd91c68f2010-05-14 14:52:25 +00004245struct unixShmNode {
4246 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drh24efa542018-10-02 19:36:40 +00004247 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004248 char *zFilename; /* Name of the mmapped file */
drh8820c8d2018-10-02 19:58:08 +00004249 int hShm; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004250 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004251 u16 nRegion; /* Size of array apRegion */
4252 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004253 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004254 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004255 int nRef; /* Number of unixShm objects pointing to this */
4256 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004257#ifdef SQLITE_DEBUG
4258 u8 exclMask; /* Mask of exclusive locks held */
4259 u8 sharedMask; /* Mask of shared locks held */
4260 u8 nextShmId; /* Next available unixShm.id value */
4261#endif
4262};
4263
4264/*
drhd9e5c4f2010-05-12 18:01:39 +00004265** Structure used internally by this VFS to record the state of an
4266** open shared memory connection.
4267**
drhd91c68f2010-05-14 14:52:25 +00004268** The following fields are initialized when this object is created and
4269** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004270**
drh24efa542018-10-02 19:36:40 +00004271** unixShm.pShmNode
drhd91c68f2010-05-14 14:52:25 +00004272** unixShm.id
4273**
drh24efa542018-10-02 19:36:40 +00004274** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4275** be held while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004276*/
4277struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004278 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4279 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drh24efa542018-10-02 19:36:40 +00004280 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
drhfd532312011-08-31 18:35:34 +00004281 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004282 u16 sharedMask; /* Mask of shared locks held */
4283 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004284};
4285
4286/*
drhd9e5c4f2010-05-12 18:01:39 +00004287** Constants used for locking
4288*/
drhbd9676c2010-06-23 17:58:38 +00004289#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004290#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004291
drhd9e5c4f2010-05-12 18:01:39 +00004292/*
drh73b64e42010-05-30 19:55:15 +00004293** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004294**
4295** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4296** otherwise.
4297*/
4298static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004299 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004300 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004301 int ofst, /* First byte of the locking range */
4302 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004303){
drhbbf76ee2015-03-10 20:22:35 +00004304 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4305 struct flock f; /* The posix advisory locking structure */
4306 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004307
drhd91c68f2010-05-14 14:52:25 +00004308 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004309 pShmNode = pFile->pInode->pShmNode;
drh24efa542018-10-02 19:36:40 +00004310 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
drh9b7e8e12018-10-02 20:16:41 +00004311 assert( pShmNode->nRef>0 || unixMutexHeld() );
drhd9e5c4f2010-05-12 18:01:39 +00004312
dan9181ae92017-10-26 17:05:22 +00004313 /* Shared locks never span more than one byte */
4314 assert( n==1 || lockType!=F_RDLCK );
4315
4316 /* Locks are within range */
4317 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4318
drh8820c8d2018-10-02 19:58:08 +00004319 if( pShmNode->hShm>=0 ){
dan7bb8b8a2020-05-06 20:27:18 +00004320 int res;
drh3cb93392011-03-12 18:10:44 +00004321 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004322 f.l_type = lockType;
4323 f.l_whence = SEEK_SET;
4324 f.l_start = ofst;
4325 f.l_len = n;
dan7bb8b8a2020-05-06 20:27:18 +00004326 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
4327 if( res==-1 ){
dan7a623e12020-05-06 20:45:11 +00004328#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan7bb8b8a2020-05-06 20:27:18 +00004329 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
dan7a623e12020-05-06 20:45:11 +00004330#else
4331 rc = SQLITE_BUSY;
4332#endif
dan7bb8b8a2020-05-06 20:27:18 +00004333 }
drh3cb93392011-03-12 18:10:44 +00004334 }
drhd9e5c4f2010-05-12 18:01:39 +00004335
4336 /* Update the global lock state and do debug tracing */
4337#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004338 { u16 mask;
4339 OSTRACE(("SHM-LOCK "));
4340 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4341 if( rc==SQLITE_OK ){
4342 if( lockType==F_UNLCK ){
4343 OSTRACE(("unlock %d ok", ofst));
4344 pShmNode->exclMask &= ~mask;
4345 pShmNode->sharedMask &= ~mask;
4346 }else if( lockType==F_RDLCK ){
4347 OSTRACE(("read-lock %d ok", ofst));
4348 pShmNode->exclMask &= ~mask;
4349 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004350 }else{
dan9181ae92017-10-26 17:05:22 +00004351 assert( lockType==F_WRLCK );
4352 OSTRACE(("write-lock %d ok", ofst));
4353 pShmNode->exclMask |= mask;
4354 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004355 }
dan9181ae92017-10-26 17:05:22 +00004356 }else{
4357 if( lockType==F_UNLCK ){
4358 OSTRACE(("unlock %d failed", ofst));
4359 }else if( lockType==F_RDLCK ){
4360 OSTRACE(("read-lock failed"));
4361 }else{
4362 assert( lockType==F_WRLCK );
4363 OSTRACE(("write-lock %d failed", ofst));
4364 }
4365 }
4366 OSTRACE((" - afterwards %03x,%03x\n",
4367 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004368 }
drhd9e5c4f2010-05-12 18:01:39 +00004369#endif
4370
4371 return rc;
4372}
4373
dan781e34c2014-03-20 08:59:47 +00004374/*
dan781e34c2014-03-20 08:59:47 +00004375** Return the minimum number of 32KB shm regions that should be mapped at
4376** a time, assuming that each mapping must be an integer multiple of the
4377** current system page-size.
4378**
4379** Usually, this is 1. The exception seems to be systems that are configured
4380** to use 64KB pages - in this case each mapping must cover at least two
4381** shm regions.
4382*/
4383static int unixShmRegionPerMap(void){
4384 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004385 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004386 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4387 if( pgsz<shmsz ) return 1;
4388 return pgsz/shmsz;
4389}
drhd9e5c4f2010-05-12 18:01:39 +00004390
4391/*
drhd91c68f2010-05-14 14:52:25 +00004392** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004393**
4394** This is not a VFS shared-memory method; it is a utility function called
4395** by VFS shared-memory methods.
4396*/
drhd91c68f2010-05-14 14:52:25 +00004397static void unixShmPurge(unixFile *pFd){
4398 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004399 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004400 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004401 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004402 int i;
drhd91c68f2010-05-14 14:52:25 +00004403 assert( p->pInode==pFd->pInode );
drh24efa542018-10-02 19:36:40 +00004404 sqlite3_mutex_free(p->pShmMutex);
dan781e34c2014-03-20 08:59:47 +00004405 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh8820c8d2018-10-02 19:58:08 +00004406 if( p->hShm>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004407 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004408 }else{
4409 sqlite3_free(p->apRegion[i]);
4410 }
dan13a3cb82010-06-11 19:04:21 +00004411 }
dan18801912010-06-14 14:07:50 +00004412 sqlite3_free(p->apRegion);
drh8820c8d2018-10-02 19:58:08 +00004413 if( p->hShm>=0 ){
4414 robust_close(pFd, p->hShm, __LINE__);
4415 p->hShm = -1;
drh0e9365c2011-03-02 02:08:13 +00004416 }
drhd91c68f2010-05-14 14:52:25 +00004417 p->pInode->pShmNode = 0;
4418 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004419 }
4420}
4421
4422/*
dan92c02da2017-11-01 20:59:28 +00004423** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4424** take it now. Return SQLITE_OK if successful, or an SQLite error
4425** code otherwise.
4426**
4427** If the DMS cannot be locked because this is a readonly_shm=1
4428** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004429** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004430*/
4431static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4432 struct flock lock;
4433 int rc = SQLITE_OK;
4434
4435 /* Use F_GETLK to determine the locks other processes are holding
4436 ** on the DMS byte. If it indicates that another process is holding
4437 ** a SHARED lock, then this process may also take a SHARED lock
4438 ** and proceed with opening the *-shm file.
4439 **
4440 ** Or, if no other process is holding any lock, then this process
4441 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4442 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4443 ** downgrade to a SHARED lock on the DMS byte.
4444 **
4445 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4446 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4447 ** version of this code attempted the SHARED lock at this point. But
4448 ** this introduced a subtle race condition: if the process holding
4449 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4450 ** process might open and use the *-shm file without truncating it.
4451 ** And if the *-shm file has been corrupted by a power failure or
4452 ** system crash, the database itself may also become corrupt. */
4453 lock.l_whence = SEEK_SET;
4454 lock.l_start = UNIX_SHM_DMS;
4455 lock.l_len = 1;
4456 lock.l_type = F_WRLCK;
drh8820c8d2018-10-02 19:58:08 +00004457 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
dan92c02da2017-11-01 20:59:28 +00004458 rc = SQLITE_IOERR_LOCK;
4459 }else if( lock.l_type==F_UNLCK ){
4460 if( pShmNode->isReadonly ){
4461 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004462 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004463 }else{
4464 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
drhf7f2a822018-10-11 13:51:48 +00004465 /* The first connection to attach must truncate the -shm file. We
4466 ** truncate to 3 bytes (an arbitrary small number, less than the
4467 ** -shm header size) rather than 0 as a system debugging aid, to
4468 ** help detect if a -shm file truncation is legitimate or is the work
4469 ** or a rogue process. */
4470 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
dan92c02da2017-11-01 20:59:28 +00004471 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4472 }
4473 }
4474 }else if( lock.l_type==F_WRLCK ){
4475 rc = SQLITE_BUSY;
4476 }
4477
4478 if( rc==SQLITE_OK ){
4479 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4480 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4481 }
4482 return rc;
4483}
4484
4485/*
danda9fe0c2010-07-13 18:44:03 +00004486** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004487** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004488**
drh7234c6d2010-06-19 15:10:09 +00004489** The file used to implement shared-memory is in the same directory
4490** as the open database file and has the same name as the open database
4491** file with the "-shm" suffix added. For example, if the database file
4492** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004493** for shared memory will be called "/home/user1/config.db-shm".
4494**
4495** Another approach to is to use files in /dev/shm or /dev/tmp or an
4496** some other tmpfs mount. But if a file in a different directory
4497** from the database file is used, then differing access permissions
4498** or a chroot() might cause two different processes on the same
4499** database to end up using different files for shared memory -
4500** meaning that their memory would not really be shared - resulting
4501** in database corruption. Nevertheless, this tmpfs file usage
4502** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4503** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4504** option results in an incompatible build of SQLite; builds of SQLite
4505** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4506** same database file at the same time, database corruption will likely
4507** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4508** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004509**
4510** When opening a new shared-memory file, if no other instances of that
4511** file are currently open, in this process or in other processes, then
4512** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004513**
4514** If the original database file (pDbFd) is using the "unix-excl" VFS
4515** that means that an exclusive lock is held on the database file and
4516** that no other processes are able to read or write the database. In
4517** that case, we do not really need shared memory. No shared memory
4518** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004519*/
danda9fe0c2010-07-13 18:44:03 +00004520static int unixOpenSharedMemory(unixFile *pDbFd){
4521 struct unixShm *p = 0; /* The connection to be opened */
4522 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004523 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004524 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004525 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004526 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004527
danda9fe0c2010-07-13 18:44:03 +00004528 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004529 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004530 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004531 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004532 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004533
danda9fe0c2010-07-13 18:44:03 +00004534 /* Check to see if a unixShmNode object already exists. Reuse an existing
4535 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004536 */
drh095908e2018-08-13 20:46:18 +00004537 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004538 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004539 pInode = pDbFd->pInode;
4540 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004541 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004542 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004543#ifndef SQLITE_SHM_DIRECTORY
4544 const char *zBasePath = pDbFd->zPath;
4545#endif
danddb0ac42010-07-14 14:48:58 +00004546
4547 /* Call fstat() to figure out the permissions on the database file. If
4548 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004549 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004550 */
drhf3b1ed02015-12-02 13:11:03 +00004551 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004552 rc = SQLITE_IOERR_FSTAT;
4553 goto shm_open_err;
4554 }
4555
drha4ced192010-07-15 18:32:40 +00004556#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004557 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004558#else
drh4bf66fd2015-02-19 02:43:02 +00004559 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004560#endif
drhf3cdcdc2015-04-29 16:50:28 +00004561 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004562 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004563 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004564 goto shm_open_err;
4565 }
drh9cb5a0d2012-01-05 21:19:54 +00004566 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004567 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004568#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004569 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004570 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4571 (u32)sStat.st_ino, (u32)sStat.st_dev);
4572#else
danf12ba662017-11-07 15:43:52 +00004573 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4574 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004575#endif
drh8820c8d2018-10-02 19:58:08 +00004576 pShmNode->hShm = -1;
drhd91c68f2010-05-14 14:52:25 +00004577 pDbFd->pInode->pShmNode = pShmNode;
4578 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004579 if( sqlite3GlobalConfig.bCoreMutex ){
drh24efa542018-10-02 19:36:40 +00004580 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4581 if( pShmNode->pShmMutex==0 ){
drh97a7e5e2016-04-26 18:58:54 +00004582 rc = SQLITE_NOMEM_BKPT;
4583 goto shm_open_err;
4584 }
drhd91c68f2010-05-14 14:52:25 +00004585 }
drhd9e5c4f2010-05-12 18:01:39 +00004586
drh3cb93392011-03-12 18:10:44 +00004587 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004588 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drhc398c652019-11-22 00:42:01 +00004589 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4590 (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004591 }
drh8820c8d2018-10-02 19:58:08 +00004592 if( pShmNode->hShm<0 ){
drhc398c652019-11-22 00:42:01 +00004593 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4594 (sStat.st_mode&0777));
drh8820c8d2018-10-02 19:58:08 +00004595 if( pShmNode->hShm<0 ){
danf12ba662017-11-07 15:43:52 +00004596 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4597 goto shm_open_err;
4598 }
4599 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004600 }
drhac7c3ac2012-02-11 19:23:48 +00004601
4602 /* If this process is running as root, make sure that the SHM file
4603 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004604 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004605 */
drh8820c8d2018-10-02 19:58:08 +00004606 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004607
dan92c02da2017-11-01 20:59:28 +00004608 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004609 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004610 }
drhd9e5c4f2010-05-12 18:01:39 +00004611 }
4612
drhd91c68f2010-05-14 14:52:25 +00004613 /* Make the new connection a child of the unixShmNode */
4614 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004615#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004616 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004617#endif
drhd91c68f2010-05-14 14:52:25 +00004618 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004619 pDbFd->pShm = p;
4620 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004621
4622 /* The reference count on pShmNode has already been incremented under
4623 ** the cover of the unixEnterMutex() mutex and the pointer from the
4624 ** new (struct unixShm) object to the pShmNode has been set. All that is
4625 ** left to do is to link the new object into the linked list starting
drh24efa542018-10-02 19:36:40 +00004626 ** at pShmNode->pFirst. This must be done while holding the
4627 ** pShmNode->pShmMutex.
dan0668f592010-07-20 18:59:00 +00004628 */
drh24efa542018-10-02 19:36:40 +00004629 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan0668f592010-07-20 18:59:00 +00004630 p->pNext = pShmNode->pFirst;
4631 pShmNode->pFirst = p;
drh24efa542018-10-02 19:36:40 +00004632 sqlite3_mutex_leave(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004633 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004634
4635 /* Jump here on any error */
4636shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004637 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004638 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004639 unixLeaveMutex();
4640 return rc;
4641}
4642
4643/*
danda9fe0c2010-07-13 18:44:03 +00004644** This function is called to obtain a pointer to region iRegion of the
4645** shared-memory associated with the database file fd. Shared-memory regions
4646** are numbered starting from zero. Each shared-memory region is szRegion
4647** bytes in size.
4648**
4649** If an error occurs, an error code is returned and *pp is set to NULL.
4650**
4651** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4652** region has not been allocated (by any client, including one running in a
4653** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4654** bExtend is non-zero and the requested shared-memory region has not yet
4655** been allocated, it is allocated by this function.
4656**
4657** If the shared-memory region has already been allocated or is allocated by
4658** this call as described above, then it is mapped into this processes
4659** address space (if it is not already), *pp is set to point to the mapped
4660** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004661*/
danda9fe0c2010-07-13 18:44:03 +00004662static int unixShmMap(
4663 sqlite3_file *fd, /* Handle open on database file */
4664 int iRegion, /* Region to retrieve */
4665 int szRegion, /* Size of regions */
4666 int bExtend, /* True to extend file if necessary */
4667 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004668){
danda9fe0c2010-07-13 18:44:03 +00004669 unixFile *pDbFd = (unixFile*)fd;
4670 unixShm *p;
4671 unixShmNode *pShmNode;
4672 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004673 int nShmPerMap = unixShmRegionPerMap();
4674 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004675
danda9fe0c2010-07-13 18:44:03 +00004676 /* If the shared-memory file has not yet been opened, open it now. */
4677 if( pDbFd->pShm==0 ){
4678 rc = unixOpenSharedMemory(pDbFd);
4679 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004680 }
drhd9e5c4f2010-05-12 18:01:39 +00004681
danda9fe0c2010-07-13 18:44:03 +00004682 p = pDbFd->pShm;
4683 pShmNode = p->pShmNode;
drh24efa542018-10-02 19:36:40 +00004684 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004685 if( pShmNode->isUnlocked ){
4686 rc = unixLockSharedMemory(pDbFd, pShmNode);
4687 if( rc!=SQLITE_OK ) goto shmpage_out;
4688 pShmNode->isUnlocked = 0;
4689 }
danda9fe0c2010-07-13 18:44:03 +00004690 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004691 assert( pShmNode->pInode==pDbFd->pInode );
drh8820c8d2018-10-02 19:58:08 +00004692 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4693 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004694
dan781e34c2014-03-20 08:59:47 +00004695 /* Minimum number of regions required to be mapped. */
4696 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4697
4698 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004699 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004700 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004701 struct stat sStat; /* Used by fstat() */
4702
4703 pShmNode->szRegion = szRegion;
4704
drh8820c8d2018-10-02 19:58:08 +00004705 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004706 /* The requested region is not mapped into this processes address space.
4707 ** Check to see if it has been allocated (i.e. if the wal-index file is
4708 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004709 */
drh8820c8d2018-10-02 19:58:08 +00004710 if( osFstat(pShmNode->hShm, &sStat) ){
drh3cb93392011-03-12 18:10:44 +00004711 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004712 goto shmpage_out;
4713 }
drh3cb93392011-03-12 18:10:44 +00004714
4715 if( sStat.st_size<nByte ){
4716 /* The requested memory region does not exist. If bExtend is set to
4717 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004718 */
dan47a2b4a2013-04-26 16:09:29 +00004719 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004720 goto shmpage_out;
4721 }
dan47a2b4a2013-04-26 16:09:29 +00004722
4723 /* Alternatively, if bExtend is true, extend the file. Do this by
4724 ** writing a single byte to the end of each (OS) page being
4725 ** allocated or extended. Technically, we need only write to the
4726 ** last page in order to extend the file. But writing to all new
4727 ** pages forces the OS to allocate them immediately, which reduces
4728 ** the chances of SIGBUS while accessing the mapped region later on.
4729 */
4730 else{
4731 static const int pgsz = 4096;
4732 int iPg;
4733
4734 /* Write to the last byte of each newly allocated or extended page */
4735 assert( (nByte % pgsz)==0 );
4736 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004737 int x = 0;
drh8820c8d2018-10-02 19:58:08 +00004738 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004739 const char *zFile = pShmNode->zFilename;
4740 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4741 goto shmpage_out;
4742 }
4743 }
drh3cb93392011-03-12 18:10:44 +00004744 }
4745 }
danda9fe0c2010-07-13 18:44:03 +00004746 }
4747
4748 /* Map the requested memory region into this processes address space. */
4749 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004750 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004751 );
4752 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004753 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004754 goto shmpage_out;
4755 }
4756 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004757 while( pShmNode->nRegion<nReqRegion ){
4758 int nMap = szRegion*nShmPerMap;
4759 int i;
drh3cb93392011-03-12 18:10:44 +00004760 void *pMem;
drh8820c8d2018-10-02 19:58:08 +00004761 if( pShmNode->hShm>=0 ){
dan781e34c2014-03-20 08:59:47 +00004762 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004763 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh8820c8d2018-10-02 19:58:08 +00004764 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004765 );
4766 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004767 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004768 goto shmpage_out;
4769 }
4770 }else{
drhb6c4d592018-10-11 02:39:11 +00004771 pMem = sqlite3_malloc64(nMap);
drh3cb93392011-03-12 18:10:44 +00004772 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004773 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004774 goto shmpage_out;
4775 }
drhb6c4d592018-10-11 02:39:11 +00004776 memset(pMem, 0, nMap);
danda9fe0c2010-07-13 18:44:03 +00004777 }
dan781e34c2014-03-20 08:59:47 +00004778
4779 for(i=0; i<nShmPerMap; i++){
4780 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4781 }
4782 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004783 }
4784 }
4785
4786shmpage_out:
4787 if( pShmNode->nRegion>iRegion ){
4788 *pp = pShmNode->apRegion[iRegion];
4789 }else{
4790 *pp = 0;
4791 }
drh66dfec8b2011-06-01 20:01:49 +00004792 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
drh24efa542018-10-02 19:36:40 +00004793 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004794 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004795}
4796
4797/*
drhd9e5c4f2010-05-12 18:01:39 +00004798** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004799**
4800** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4801** different here than in posix. In xShmLock(), one can go from unlocked
4802** to shared and back or from unlocked to exclusive and back. But one may
4803** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004804*/
4805static int unixShmLock(
4806 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004807 int ofst, /* First lock to acquire or release */
4808 int n, /* Number of locks to acquire or release */
4809 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004810){
drh73b64e42010-05-30 19:55:15 +00004811 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4812 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4813 unixShm *pX; /* For looping over all siblings */
4814 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4815 int rc = SQLITE_OK; /* Result code */
4816 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004817
drhd91c68f2010-05-14 14:52:25 +00004818 assert( pShmNode==pDbFd->pInode->pShmNode );
4819 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004820 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004821 assert( n>=1 );
4822 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4823 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4824 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4825 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4826 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh8820c8d2018-10-02 19:58:08 +00004827 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4828 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004829
dan58021b22020-05-05 20:30:07 +00004830 /* Check that, if this to be a blocking lock, no locks that occur later
4831 ** in the following list than the lock being obtained are already held:
dan97ccc1b2020-03-27 17:23:17 +00004832 **
4833 ** 1. Checkpointer lock (ofst==1).
dan58021b22020-05-05 20:30:07 +00004834 ** 2. Write lock (ofst==0).
dan97ccc1b2020-03-27 17:23:17 +00004835 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
dan97ccc1b2020-03-27 17:23:17 +00004836 **
4837 ** In other words, if this is a blocking lock, none of the locks that
4838 ** occur later in the above list than the lock being obtained may be
dand31fcd42020-05-29 11:07:20 +00004839 ** held.
4840 **
4841 ** It is not permitted to block on the RECOVER lock.
4842 */
dan97ccc1b2020-03-27 17:23:17 +00004843#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
dan58021b22020-05-05 20:30:07 +00004844 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
4845 (ofst!=2) /* not RECOVER */
dan58021b22020-05-05 20:30:07 +00004846 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
4847 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
4848 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
4849 ));
dan97ccc1b2020-03-27 17:23:17 +00004850#endif
4851
drhc99597c2010-05-31 01:41:15 +00004852 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004853 assert( n>1 || mask==(1<<ofst) );
drh24efa542018-10-02 19:36:40 +00004854 sqlite3_mutex_enter(pShmNode->pShmMutex);
drh73b64e42010-05-30 19:55:15 +00004855 if( flags & SQLITE_SHM_UNLOCK ){
4856 u16 allMask = 0; /* Mask of locks held by siblings */
4857
4858 /* See if any siblings hold this same lock */
4859 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4860 if( pX==p ) continue;
4861 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4862 allMask |= pX->sharedMask;
4863 }
4864
4865 /* Unlock the system-level locks */
4866 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004867 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004868 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004869 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004870 }
drh73b64e42010-05-30 19:55:15 +00004871
4872 /* Undo the local locks */
4873 if( rc==SQLITE_OK ){
4874 p->exclMask &= ~mask;
4875 p->sharedMask &= ~mask;
4876 }
4877 }else if( flags & SQLITE_SHM_SHARED ){
4878 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4879
4880 /* Find out which shared locks are already held by sibling connections.
4881 ** If any sibling already holds an exclusive lock, go ahead and return
4882 ** SQLITE_BUSY.
4883 */
4884 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004885 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004886 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004887 break;
4888 }
4889 allShared |= pX->sharedMask;
4890 }
4891
4892 /* Get shared locks at the system level, if necessary */
4893 if( rc==SQLITE_OK ){
4894 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004895 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004896 }else{
drh73b64e42010-05-30 19:55:15 +00004897 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004898 }
drhd9e5c4f2010-05-12 18:01:39 +00004899 }
drh73b64e42010-05-30 19:55:15 +00004900
4901 /* Get the local shared locks */
4902 if( rc==SQLITE_OK ){
4903 p->sharedMask |= mask;
4904 }
4905 }else{
4906 /* Make sure no sibling connections hold locks that will block this
4907 ** lock. If any do, return SQLITE_BUSY right away.
4908 */
4909 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004910 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4911 rc = SQLITE_BUSY;
4912 break;
4913 }
4914 }
4915
4916 /* Get the exclusive locks at the system level. Then if successful
4917 ** also mark the local connection as being locked.
4918 */
4919 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004920 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004921 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004922 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004923 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004924 }
drhd9e5c4f2010-05-12 18:01:39 +00004925 }
4926 }
drh24efa542018-10-02 19:36:40 +00004927 sqlite3_mutex_leave(pShmNode->pShmMutex);
drh20e1f082010-05-31 16:10:12 +00004928 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004929 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004930 return rc;
4931}
4932
drh286a2882010-05-20 23:51:06 +00004933/*
4934** Implement a memory barrier or memory fence on shared memory.
4935**
4936** All loads and stores begun before the barrier must complete before
4937** any load or store begun after the barrier.
4938*/
4939static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004940 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004941){
drhff828942010-06-26 21:34:06 +00004942 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004943 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00004944 assert( fd->pMethods->xLock==nolockLock
4945 || unixFileMutexNotheld((unixFile*)fd)
4946 );
drh22c733d2015-09-24 12:40:43 +00004947 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004948 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004949}
4950
dan18801912010-06-14 14:07:50 +00004951/*
danda9fe0c2010-07-13 18:44:03 +00004952** Close a connection to shared-memory. Delete the underlying
4953** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004954**
4955** If there is no shared memory associated with the connection then this
4956** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004957*/
danda9fe0c2010-07-13 18:44:03 +00004958static int unixShmUnmap(
4959 sqlite3_file *fd, /* The underlying database file */
4960 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004961){
danda9fe0c2010-07-13 18:44:03 +00004962 unixShm *p; /* The connection to be closed */
4963 unixShmNode *pShmNode; /* The underlying shared-memory file */
4964 unixShm **pp; /* For looping over sibling connections */
4965 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004966
danda9fe0c2010-07-13 18:44:03 +00004967 pDbFd = (unixFile*)fd;
4968 p = pDbFd->pShm;
4969 if( p==0 ) return SQLITE_OK;
4970 pShmNode = p->pShmNode;
4971
4972 assert( pShmNode==pDbFd->pInode->pShmNode );
4973 assert( pShmNode->pInode==pDbFd->pInode );
4974
4975 /* Remove connection p from the set of connections associated
4976 ** with pShmNode */
drh24efa542018-10-02 19:36:40 +00004977 sqlite3_mutex_enter(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004978 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4979 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004980
danda9fe0c2010-07-13 18:44:03 +00004981 /* Free the connection p */
4982 sqlite3_free(p);
4983 pDbFd->pShm = 0;
drh24efa542018-10-02 19:36:40 +00004984 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004985
4986 /* If pShmNode->nRef has reached 0, then close the underlying
4987 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00004988 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00004989 unixEnterMutex();
4990 assert( pShmNode->nRef>0 );
4991 pShmNode->nRef--;
4992 if( pShmNode->nRef==0 ){
drh8820c8d2018-10-02 19:58:08 +00004993 if( deleteFlag && pShmNode->hShm>=0 ){
drh4bf66fd2015-02-19 02:43:02 +00004994 osUnlink(pShmNode->zFilename);
4995 }
danda9fe0c2010-07-13 18:44:03 +00004996 unixShmPurge(pDbFd);
4997 }
4998 unixLeaveMutex();
4999
5000 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00005001}
drh286a2882010-05-20 23:51:06 +00005002
danda9fe0c2010-07-13 18:44:03 +00005003
drhd9e5c4f2010-05-12 18:01:39 +00005004#else
drh6b017cc2010-06-14 18:01:46 +00005005# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00005006# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00005007# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00005008# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00005009#endif /* #ifndef SQLITE_OMIT_WAL */
5010
mistachkine98844f2013-08-24 00:59:24 +00005011#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00005012/*
danaef49d72013-03-25 16:28:54 +00005013** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00005014*/
danf23da962013-03-23 21:00:41 +00005015static void unixUnmapfile(unixFile *pFd){
5016 assert( pFd->nFetchOut==0 );
5017 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00005018 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00005019 pFd->pMapRegion = 0;
5020 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00005021 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00005022 }
5023}
dan5d8a1372013-03-19 19:28:06 +00005024
danaef49d72013-03-25 16:28:54 +00005025/*
dane6ecd662013-04-01 17:56:59 +00005026** Attempt to set the size of the memory mapping maintained by file
5027** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5028**
5029** If successful, this function sets the following variables:
5030**
5031** unixFile.pMapRegion
5032** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00005033** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00005034**
5035** If unsuccessful, an error message is logged via sqlite3_log() and
5036** the three variables above are zeroed. In this case SQLite should
5037** continue accessing the database using the xRead() and xWrite()
5038** methods.
5039*/
5040static void unixRemapfile(
5041 unixFile *pFd, /* File descriptor object */
5042 i64 nNew /* Required mapping size */
5043){
dan4ff7bc42013-04-02 12:04:09 +00005044 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00005045 int h = pFd->h; /* File descriptor open on db file */
5046 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00005047 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00005048 u8 *pNew = 0; /* Location of new mapping */
5049 int flags = PROT_READ; /* Flags to pass to mmap() */
5050
5051 assert( pFd->nFetchOut==0 );
5052 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00005053 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00005054 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00005055 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00005056 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00005057
danfe33e392015-11-17 20:56:06 +00005058#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005059 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005060#endif
dane6ecd662013-04-01 17:56:59 +00005061
5062 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005063#if HAVE_MREMAP
5064 i64 nReuse = pFd->mmapSize;
5065#else
danbc760632014-03-20 09:42:09 +00005066 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005067 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005068#endif
dane6ecd662013-04-01 17:56:59 +00005069 u8 *pReq = &pOrig[nReuse];
5070
5071 /* Unmap any pages of the existing mapping that cannot be reused. */
5072 if( nReuse!=nOrig ){
5073 osMunmap(pReq, nOrig-nReuse);
5074 }
5075
5076#if HAVE_MREMAP
5077 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005078 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005079#else
5080 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5081 if( pNew!=MAP_FAILED ){
5082 if( pNew!=pReq ){
5083 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005084 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005085 }else{
5086 pNew = pOrig;
5087 }
5088 }
5089#endif
5090
dan48ccef82013-04-02 20:55:01 +00005091 /* The attempt to extend the existing mapping failed. Free it. */
5092 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005093 osMunmap(pOrig, nReuse);
5094 }
5095 }
5096
5097 /* If pNew is still NULL, try to create an entirely new mapping. */
5098 if( pNew==0 ){
5099 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005100 }
5101
dan4ff7bc42013-04-02 12:04:09 +00005102 if( pNew==MAP_FAILED ){
5103 pNew = 0;
5104 nNew = 0;
5105 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5106
5107 /* If the mmap() above failed, assume that all subsequent mmap() calls
5108 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5109 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005110 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005111 }
dane6ecd662013-04-01 17:56:59 +00005112 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005113 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005114}
5115
5116/*
danaef49d72013-03-25 16:28:54 +00005117** Memory map or remap the file opened by file-descriptor pFd (if the file
5118** is already mapped, the existing mapping is replaced by the new). Or, if
5119** there already exists a mapping for this file, and there are still
5120** outstanding xFetch() references to it, this function is a no-op.
5121**
5122** If parameter nByte is non-negative, then it is the requested size of
5123** the mapping to create. Otherwise, if nByte is less than zero, then the
5124** requested size is the size of the file on disk. The actual size of the
5125** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005126** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005127**
5128** SQLITE_OK is returned if no error occurs (even if the mapping is not
5129** recreated as a result of outstanding references) or an SQLite error
5130** code otherwise.
5131*/
drhf3b1ed02015-12-02 13:11:03 +00005132static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005133 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005134 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005135 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5136
5137 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005138 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005139 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005140 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005141 }
drh3044b512014-06-16 16:41:52 +00005142 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005143 }
drh9b4c59f2013-04-15 17:03:42 +00005144 if( nMap>pFd->mmapSizeMax ){
5145 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005146 }
5147
drh333e6ca2015-12-02 15:44:39 +00005148 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005149 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005150 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005151 }
5152
danf23da962013-03-23 21:00:41 +00005153 return SQLITE_OK;
5154}
mistachkine98844f2013-08-24 00:59:24 +00005155#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005156
danaef49d72013-03-25 16:28:54 +00005157/*
5158** If possible, return a pointer to a mapping of file fd starting at offset
5159** iOff. The mapping must be valid for at least nAmt bytes.
5160**
5161** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5162** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5163** Finally, if an error does occur, return an SQLite error code. The final
5164** value of *pp is undefined in this case.
5165**
5166** If this function does return a pointer, the caller must eventually
5167** release the reference by calling unixUnfetch().
5168*/
danf23da962013-03-23 21:00:41 +00005169static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005170#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005171 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005172#endif
danf23da962013-03-23 21:00:41 +00005173 *pp = 0;
5174
drh9b4c59f2013-04-15 17:03:42 +00005175#if SQLITE_MAX_MMAP_SIZE>0
5176 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005177 if( pFd->pMapRegion==0 ){
5178 int rc = unixMapfile(pFd, -1);
5179 if( rc!=SQLITE_OK ) return rc;
5180 }
5181 if( pFd->mmapSize >= iOff+nAmt ){
5182 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5183 pFd->nFetchOut++;
5184 }
5185 }
drh6e0b6d52013-04-09 16:19:20 +00005186#endif
danf23da962013-03-23 21:00:41 +00005187 return SQLITE_OK;
5188}
5189
danaef49d72013-03-25 16:28:54 +00005190/*
dandf737fe2013-03-25 17:00:24 +00005191** If the third argument is non-NULL, then this function releases a
5192** reference obtained by an earlier call to unixFetch(). The second
5193** argument passed to this function must be the same as the corresponding
5194** argument that was passed to the unixFetch() invocation.
5195**
5196** Or, if the third argument is NULL, then this function is being called
5197** to inform the VFS layer that, according to POSIX, any existing mapping
5198** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005199*/
dandf737fe2013-03-25 17:00:24 +00005200static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005201#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005202 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005203 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005204
danaef49d72013-03-25 16:28:54 +00005205 /* If p==0 (unmap the entire file) then there must be no outstanding
5206 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5207 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005208 assert( (p==0)==(pFd->nFetchOut==0) );
5209
dandf737fe2013-03-25 17:00:24 +00005210 /* If p!=0, it must match the iOff value. */
5211 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5212
danf23da962013-03-23 21:00:41 +00005213 if( p ){
5214 pFd->nFetchOut--;
5215 }else{
5216 unixUnmapfile(pFd);
5217 }
5218
5219 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005220#else
5221 UNUSED_PARAMETER(fd);
5222 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005223 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005224#endif
danf23da962013-03-23 21:00:41 +00005225 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005226}
5227
5228/*
drh734c9862008-11-28 15:37:20 +00005229** Here ends the implementation of all sqlite3_file methods.
5230**
5231********************** End sqlite3_file Methods *******************************
5232******************************************************************************/
5233
5234/*
drh6b9d6dd2008-12-03 19:34:47 +00005235** This division contains definitions of sqlite3_io_methods objects that
5236** implement various file locking strategies. It also contains definitions
5237** of "finder" functions. A finder-function is used to locate the appropriate
5238** sqlite3_io_methods object for a particular database file. The pAppData
5239** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5240** the correct finder-function for that VFS.
5241**
5242** Most finder functions return a pointer to a fixed sqlite3_io_methods
5243** object. The only interesting finder-function is autolockIoFinder, which
5244** looks at the filesystem type and tries to guess the best locking
5245** strategy from that.
5246**
peter.d.reid60ec9142014-09-06 16:39:46 +00005247** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005248**
5249** (1) The real finder-function named "FImpt()".
5250**
dane946c392009-08-22 11:39:46 +00005251** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005252**
5253**
5254** A pointer to the F pointer is used as the pAppData value for VFS
5255** objects. We have to do this instead of letting pAppData point
5256** directly at the finder-function since C90 rules prevent a void*
5257** from be cast into a function pointer.
5258**
drh6b9d6dd2008-12-03 19:34:47 +00005259**
drh7708e972008-11-29 00:56:52 +00005260** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005261**
drh7708e972008-11-29 00:56:52 +00005262** * A constant sqlite3_io_methods object call METHOD that has locking
5263** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5264**
5265** * An I/O method finder function called FINDER that returns a pointer
5266** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005267*/
drhe6d41732015-02-21 00:49:00 +00005268#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005269static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005270 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005271 CLOSE, /* xClose */ \
5272 unixRead, /* xRead */ \
5273 unixWrite, /* xWrite */ \
5274 unixTruncate, /* xTruncate */ \
5275 unixSync, /* xSync */ \
5276 unixFileSize, /* xFileSize */ \
5277 LOCK, /* xLock */ \
5278 UNLOCK, /* xUnlock */ \
5279 CKLOCK, /* xCheckReservedLock */ \
5280 unixFileControl, /* xFileControl */ \
5281 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005282 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005283 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005284 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005285 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005286 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005287 unixFetch, /* xFetch */ \
5288 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005289}; \
drh0c2694b2009-09-03 16:23:44 +00005290static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5291 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005292 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005293} \
drh0c2694b2009-09-03 16:23:44 +00005294static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005295 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005296
5297/*
5298** Here are all of the sqlite3_io_methods objects for each of the
5299** locking strategies. Functions that return pointers to these methods
5300** are also created.
5301*/
5302IOMETHODS(
5303 posixIoFinder, /* Finder function name */
5304 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005305 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005306 unixClose, /* xClose method */
5307 unixLock, /* xLock method */
5308 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005309 unixCheckReservedLock, /* xCheckReservedLock method */
5310 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005311)
drh7708e972008-11-29 00:56:52 +00005312IOMETHODS(
5313 nolockIoFinder, /* Finder function name */
5314 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005315 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005316 nolockClose, /* xClose method */
5317 nolockLock, /* xLock method */
5318 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005319 nolockCheckReservedLock, /* xCheckReservedLock method */
5320 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005321)
drh7708e972008-11-29 00:56:52 +00005322IOMETHODS(
5323 dotlockIoFinder, /* Finder function name */
5324 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005325 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005326 dotlockClose, /* xClose method */
5327 dotlockLock, /* xLock method */
5328 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005329 dotlockCheckReservedLock, /* xCheckReservedLock method */
5330 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005331)
drh7708e972008-11-29 00:56:52 +00005332
drhe89b2912015-03-03 20:42:01 +00005333#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005334IOMETHODS(
5335 flockIoFinder, /* Finder function name */
5336 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005337 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005338 flockClose, /* xClose method */
5339 flockLock, /* xLock method */
5340 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005341 flockCheckReservedLock, /* xCheckReservedLock method */
5342 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005343)
drh7708e972008-11-29 00:56:52 +00005344#endif
5345
drh6c7d5c52008-11-21 20:32:33 +00005346#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005347IOMETHODS(
5348 semIoFinder, /* Finder function name */
5349 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005350 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005351 semXClose, /* xClose method */
5352 semXLock, /* xLock method */
5353 semXUnlock, /* xUnlock method */
5354 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005355 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005356)
aswiftaebf4132008-11-21 00:10:35 +00005357#endif
drh7708e972008-11-29 00:56:52 +00005358
drhd2cb50b2009-01-09 21:41:17 +00005359#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005360IOMETHODS(
5361 afpIoFinder, /* Finder function name */
5362 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005363 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005364 afpClose, /* xClose method */
5365 afpLock, /* xLock method */
5366 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005367 afpCheckReservedLock, /* xCheckReservedLock method */
5368 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005369)
drh715ff302008-12-03 22:32:44 +00005370#endif
5371
5372/*
5373** The proxy locking method is a "super-method" in the sense that it
5374** opens secondary file descriptors for the conch and lock files and
5375** it uses proxy, dot-file, AFP, and flock() locking methods on those
5376** secondary files. For this reason, the division that implements
5377** proxy locking is located much further down in the file. But we need
5378** to go ahead and define the sqlite3_io_methods and finder function
5379** for proxy locking here. So we forward declare the I/O methods.
5380*/
drhd2cb50b2009-01-09 21:41:17 +00005381#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005382static int proxyClose(sqlite3_file*);
5383static int proxyLock(sqlite3_file*, int);
5384static int proxyUnlock(sqlite3_file*, int);
5385static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005386IOMETHODS(
5387 proxyIoFinder, /* Finder function name */
5388 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005389 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005390 proxyClose, /* xClose method */
5391 proxyLock, /* xLock method */
5392 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005393 proxyCheckReservedLock, /* xCheckReservedLock method */
5394 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005395)
aswiftaebf4132008-11-21 00:10:35 +00005396#endif
drh7708e972008-11-29 00:56:52 +00005397
drh7ed97b92010-01-20 13:07:21 +00005398/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5399#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5400IOMETHODS(
5401 nfsIoFinder, /* Finder function name */
5402 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005403 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005404 unixClose, /* xClose method */
5405 unixLock, /* xLock method */
5406 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005407 unixCheckReservedLock, /* xCheckReservedLock method */
5408 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005409)
5410#endif
drh7708e972008-11-29 00:56:52 +00005411
drhd2cb50b2009-01-09 21:41:17 +00005412#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005413/*
drh6b9d6dd2008-12-03 19:34:47 +00005414** This "finder" function attempts to determine the best locking strategy
5415** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005416** object that implements that strategy.
5417**
5418** This is for MacOSX only.
5419*/
drh1875f7a2008-12-08 18:19:17 +00005420static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005421 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005422 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005423){
5424 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005425 const char *zFilesystem; /* Filesystem type name */
5426 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005427 } aMap[] = {
5428 { "hfs", &posixIoMethods },
5429 { "ufs", &posixIoMethods },
5430 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005431 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005432 { "webdav", &nolockIoMethods },
5433 { 0, 0 }
5434 };
5435 int i;
5436 struct statfs fsInfo;
5437 struct flock lockInfo;
5438
5439 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005440 /* If filePath==NULL that means we are dealing with a transient file
5441 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005442 return &nolockIoMethods;
5443 }
5444 if( statfs(filePath, &fsInfo) != -1 ){
5445 if( fsInfo.f_flags & MNT_RDONLY ){
5446 return &nolockIoMethods;
5447 }
5448 for(i=0; aMap[i].zFilesystem; i++){
5449 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5450 return aMap[i].pMethods;
5451 }
5452 }
5453 }
5454
5455 /* Default case. Handles, amongst others, "nfs".
5456 ** Test byte-range lock using fcntl(). If the call succeeds,
5457 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005458 */
drh7708e972008-11-29 00:56:52 +00005459 lockInfo.l_len = 1;
5460 lockInfo.l_start = 0;
5461 lockInfo.l_whence = SEEK_SET;
5462 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005463 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005464 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5465 return &nfsIoMethods;
5466 } else {
5467 return &posixIoMethods;
5468 }
drh7708e972008-11-29 00:56:52 +00005469 }else{
5470 return &dotlockIoMethods;
5471 }
5472}
drh0c2694b2009-09-03 16:23:44 +00005473static const sqlite3_io_methods
5474 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005475
drhd2cb50b2009-01-09 21:41:17 +00005476#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005477
drhe89b2912015-03-03 20:42:01 +00005478#if OS_VXWORKS
5479/*
5480** This "finder" function for VxWorks checks to see if posix advisory
5481** locking works. If it does, then that is what is used. If it does not
5482** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005483*/
drhe89b2912015-03-03 20:42:01 +00005484static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005485 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005486 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005487){
5488 struct flock lockInfo;
5489
5490 if( !filePath ){
5491 /* If filePath==NULL that means we are dealing with a transient file
5492 ** that does not need to be locked. */
5493 return &nolockIoMethods;
5494 }
5495
5496 /* Test if fcntl() is supported and use POSIX style locks.
5497 ** Otherwise fall back to the named semaphore method.
5498 */
5499 lockInfo.l_len = 1;
5500 lockInfo.l_start = 0;
5501 lockInfo.l_whence = SEEK_SET;
5502 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005503 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005504 return &posixIoMethods;
5505 }else{
5506 return &semIoMethods;
5507 }
5508}
drh0c2694b2009-09-03 16:23:44 +00005509static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005510 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005511
drhe89b2912015-03-03 20:42:01 +00005512#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005513
drh7708e972008-11-29 00:56:52 +00005514/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005515** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005516*/
drh0c2694b2009-09-03 16:23:44 +00005517typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005518
aswiftaebf4132008-11-21 00:10:35 +00005519
drh734c9862008-11-28 15:37:20 +00005520/****************************************************************************
5521**************************** sqlite3_vfs methods ****************************
5522**
5523** This division contains the implementation of methods on the
5524** sqlite3_vfs object.
5525*/
5526
danielk1977a3d4c882007-03-23 10:08:38 +00005527/*
danielk1977e339d652008-06-28 11:23:00 +00005528** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005529*/
5530static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005531 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005532 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005533 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005534 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005535 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005536){
drh7708e972008-11-29 00:56:52 +00005537 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005538 unixFile *pNew = (unixFile *)pId;
5539 int rc = SQLITE_OK;
5540
drh8af6c222010-05-14 12:43:01 +00005541 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005542
drhb07028f2011-10-14 21:49:18 +00005543 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005544 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005545
drh308c2a52010-05-14 11:30:18 +00005546 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005547 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005548 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005549 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005550 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005551#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005552 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005553#endif
drhc02a43a2012-01-10 23:18:38 +00005554 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5555 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005556 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005557 }
drh503a6862013-03-01 01:07:17 +00005558 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005559 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005560 }
drh339eb0b2008-03-07 15:34:11 +00005561
drh6c7d5c52008-11-21 20:32:33 +00005562#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005563 pNew->pId = vxworksFindFileId(zFilename);
5564 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005565 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005566 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005567 }
5568#endif
5569
drhc02a43a2012-01-10 23:18:38 +00005570 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005571 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005572 }else{
drh0c2694b2009-09-03 16:23:44 +00005573 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005574#if SQLITE_ENABLE_LOCKING_STYLE
5575 /* Cache zFilename in the locking context (AFP and dotlock override) for
5576 ** proxyLock activation is possible (remote proxy is based on db name)
5577 ** zFilename remains valid until file is closed, to support */
5578 pNew->lockingContext = (void*)zFilename;
5579#endif
drhda0e7682008-07-30 15:27:54 +00005580 }
danielk1977e339d652008-06-28 11:23:00 +00005581
drh7ed97b92010-01-20 13:07:21 +00005582 if( pLockingStyle == &posixIoMethods
5583#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5584 || pLockingStyle == &nfsIoMethods
5585#endif
5586 ){
drh7708e972008-11-29 00:56:52 +00005587 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005588 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005589 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005590 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005591 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005592 ** in two scenarios:
5593 **
5594 ** (a) A call to fstat() failed.
5595 ** (b) A malloc failed.
5596 **
5597 ** Scenario (b) may only occur if the process is holding no other
5598 ** file descriptors open on the same file. If there were other file
5599 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005600 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005601 ** handle h - as it is guaranteed that no posix locks will be released
5602 ** by doing so.
5603 **
5604 ** If scenario (a) caused the error then things are not so safe. The
5605 ** implicit assumption here is that if fstat() fails, things are in
5606 ** such bad shape that dropping a lock or two doesn't matter much.
5607 */
drh0e9365c2011-03-02 02:08:13 +00005608 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005609 h = -1;
5610 }
drh7708e972008-11-29 00:56:52 +00005611 unixLeaveMutex();
5612 }
danielk1977e339d652008-06-28 11:23:00 +00005613
drhd2cb50b2009-01-09 21:41:17 +00005614#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005615 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005616 /* AFP locking uses the file path so it needs to be included in
5617 ** the afpLockingContext.
5618 */
5619 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005620 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005621 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005622 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005623 }else{
5624 /* NB: zFilename exists and remains valid until the file is closed
5625 ** according to requirement F11141. So we do not need to make a
5626 ** copy of the filename. */
5627 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005628 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005629 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005630 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005631 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005632 if( rc!=SQLITE_OK ){
5633 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005634 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005635 h = -1;
5636 }
drh7708e972008-11-29 00:56:52 +00005637 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005638 }
drh7708e972008-11-29 00:56:52 +00005639 }
5640#endif
danielk1977e339d652008-06-28 11:23:00 +00005641
drh7708e972008-11-29 00:56:52 +00005642 else if( pLockingStyle == &dotlockIoMethods ){
5643 /* Dotfile locking uses the file path so it needs to be included in
5644 ** the dotlockLockingContext
5645 */
5646 char *zLockFile;
5647 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005648 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005649 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005650 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005651 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005652 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005653 }else{
5654 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005655 }
drh7708e972008-11-29 00:56:52 +00005656 pNew->lockingContext = zLockFile;
5657 }
danielk1977e339d652008-06-28 11:23:00 +00005658
drh6c7d5c52008-11-21 20:32:33 +00005659#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005660 else if( pLockingStyle == &semIoMethods ){
5661 /* Named semaphore locking uses the file path so it needs to be
5662 ** included in the semLockingContext
5663 */
5664 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005665 rc = findInodeInfo(pNew, &pNew->pInode);
5666 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5667 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005668 int n;
drh2238dcc2009-08-27 17:56:20 +00005669 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005670 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005671 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005672 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005673 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5674 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005675 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005676 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005677 }
chw97185482008-11-17 08:05:31 +00005678 }
drh7708e972008-11-29 00:56:52 +00005679 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005680 }
drh7708e972008-11-29 00:56:52 +00005681#endif
aswift5b1a2562008-08-22 00:22:35 +00005682
drh4bf66fd2015-02-19 02:43:02 +00005683 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005684#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005685 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005686 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005687 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005688 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005689 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005690 }
chw97185482008-11-17 08:05:31 +00005691#endif
danielk1977e339d652008-06-28 11:23:00 +00005692 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005693 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005694 }else{
drh7708e972008-11-29 00:56:52 +00005695 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005696 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005697 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005698 }
danielk1977e339d652008-06-28 11:23:00 +00005699 return rc;
drh054889e2005-11-30 03:20:31 +00005700}
drh9c06c952005-11-26 00:25:00 +00005701
danielk1977ad94b582007-08-20 06:44:22 +00005702/*
drh8b3cf822010-06-01 21:02:51 +00005703** Return the name of a directory in which to put temporary files.
5704** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005705*/
drh7234c6d2010-06-19 15:10:09 +00005706static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005707 static const char *azDirs[] = {
5708 0,
aswiftaebf4132008-11-21 00:10:35 +00005709 0,
danielk197717b90b52008-06-06 11:11:25 +00005710 "/var/tmp",
5711 "/usr/tmp",
5712 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005713 "."
danielk197717b90b52008-06-06 11:11:25 +00005714 };
drh2aab11f2016-04-29 20:30:56 +00005715 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005716 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005717 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005718
drhb7e50ad2015-11-28 21:49:53 +00005719 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5720 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005721 while(1){
5722 if( zDir!=0
5723 && osStat(zDir, &buf)==0
5724 && S_ISDIR(buf.st_mode)
5725 && osAccess(zDir, 03)==0
5726 ){
5727 return zDir;
5728 }
5729 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5730 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005731 }
drh7694e062016-04-21 23:37:24 +00005732 return 0;
drh8b3cf822010-06-01 21:02:51 +00005733}
5734
5735/*
5736** Create a temporary file name in zBuf. zBuf must be allocated
5737** by the calling process and must be big enough to hold at least
5738** pVfs->mxPathname bytes.
5739*/
5740static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005741 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005742 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005743
5744 /* It's odd to simulate an io-error here, but really this is just
5745 ** using the io-error infrastructure to test that SQLite handles this
5746 ** function failing.
5747 */
drh7694e062016-04-21 23:37:24 +00005748 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005749 SimulateIOError( return SQLITE_IOERR );
5750
drh7234c6d2010-06-19 15:10:09 +00005751 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005752 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005753 do{
drh970942e2015-11-25 23:13:14 +00005754 u64 r;
5755 sqlite3_randomness(sizeof(r), &r);
5756 assert( nBuf>2 );
5757 zBuf[nBuf-2] = 0;
5758 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5759 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005760 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005761 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005762 return SQLITE_OK;
5763}
5764
drhd2cb50b2009-01-09 21:41:17 +00005765#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005766/*
5767** Routine to transform a unixFile into a proxy-locking unixFile.
5768** Implementation in the proxy-lock division, but used by unixOpen()
5769** if SQLITE_PREFER_PROXY_LOCKING is defined.
5770*/
5771static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005772#endif
drhc66d5b62008-12-03 22:48:32 +00005773
dan08da86a2009-08-21 17:18:03 +00005774/*
5775** Search for an unused file descriptor that was opened on the database
5776** file (not a journal or master-journal file) identified by pathname
5777** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5778** argument to this function.
5779**
5780** Such a file descriptor may exist if a database connection was closed
5781** but the associated file descriptor could not be closed because some
5782** other file descriptor open on the same file is holding a file-lock.
5783** Refer to comments in the unixClose() function and the lengthy comment
5784** describing "Posix Advisory Locking" at the start of this file for
5785** further details. Also, ticket #4018.
5786**
5787** If a suitable file descriptor is found, then it is returned. If no
5788** such file descriptor is located, -1 is returned.
5789*/
dane946c392009-08-22 11:39:46 +00005790static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5791 UnixUnusedFd *pUnused = 0;
5792
5793 /* Do not search for an unused file descriptor on vxworks. Not because
5794 ** vxworks would not benefit from the change (it might, we're not sure),
5795 ** but because no way to test it is currently available. It is better
5796 ** not to risk breaking vxworks support for the sake of such an obscure
5797 ** feature. */
5798#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005799 struct stat sStat; /* Results of stat() call */
5800
drhc68886b2017-08-18 16:09:52 +00005801 unixEnterMutex();
5802
dan08da86a2009-08-21 17:18:03 +00005803 /* A stat() call may fail for various reasons. If this happens, it is
5804 ** almost certain that an open() call on the same path will also fail.
5805 ** For this reason, if an error occurs in the stat() call here, it is
5806 ** ignored and -1 is returned. The caller will try to open a new file
5807 ** descriptor on the same path, fail, and return an error to SQLite.
5808 **
5809 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005810 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005811 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005812 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005813
drh8af6c222010-05-14 12:43:01 +00005814 pInode = inodeList;
5815 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005816 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005817 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005818 }
drh8af6c222010-05-14 12:43:01 +00005819 if( pInode ){
dane946c392009-08-22 11:39:46 +00005820 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005821 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5822 sqlite3_mutex_enter(pInode->pLockMutex);
drh55220a62019-08-06 20:55:06 +00005823 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
drh8af6c222010-05-14 12:43:01 +00005824 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005825 pUnused = *pp;
5826 if( pUnused ){
5827 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005828 }
drh095908e2018-08-13 20:46:18 +00005829 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005830 }
dan08da86a2009-08-21 17:18:03 +00005831 }
drhc68886b2017-08-18 16:09:52 +00005832 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005833#endif /* if !OS_VXWORKS */
5834 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005835}
danielk197717b90b52008-06-06 11:11:25 +00005836
5837/*
dan1bf4ca72016-08-11 18:05:47 +00005838** Find the mode, uid and gid of file zFile.
5839*/
5840static int getFileMode(
5841 const char *zFile, /* File name */
5842 mode_t *pMode, /* OUT: Permissions of zFile */
5843 uid_t *pUid, /* OUT: uid of zFile. */
5844 gid_t *pGid /* OUT: gid of zFile. */
5845){
5846 struct stat sStat; /* Output of stat() on database file */
5847 int rc = SQLITE_OK;
5848 if( 0==osStat(zFile, &sStat) ){
5849 *pMode = sStat.st_mode & 0777;
5850 *pUid = sStat.st_uid;
5851 *pGid = sStat.st_gid;
5852 }else{
5853 rc = SQLITE_IOERR_FSTAT;
5854 }
5855 return rc;
5856}
5857
5858/*
danddb0ac42010-07-14 14:48:58 +00005859** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005860** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005861** and a value suitable for passing as the third argument to open(2) is
5862** written to *pMode. If an IO error occurs, an SQLite error code is
5863** returned and the value of *pMode is not modified.
5864**
peter.d.reid60ec9142014-09-06 16:39:46 +00005865** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005866** an indication to robust_open() to create the file using
5867** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5868** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005869** this function queries the file-system for the permissions on the
5870** corresponding database file and sets *pMode to this value. Whenever
5871** possible, WAL and journal files are created using the same permissions
5872** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005873**
5874** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5875** original filename is unavailable. But 8_3_NAMES is only used for
5876** FAT filesystems and permissions do not matter there, so just use
drh1116b172019-09-25 10:36:31 +00005877** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
danddb0ac42010-07-14 14:48:58 +00005878*/
5879static int findCreateFileMode(
5880 const char *zPath, /* Path of file (possibly) being created */
5881 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005882 mode_t *pMode, /* OUT: Permissions to open file with */
5883 uid_t *pUid, /* OUT: uid to set on the file */
5884 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005885){
5886 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005887 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005888 *pUid = 0;
5889 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005890 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005891 char zDb[MAX_PATHNAME+1]; /* Database file path */
5892 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005893
dana0c989d2010-11-05 18:07:37 +00005894 /* zPath is a path to a WAL or journal file. The following block derives
5895 ** the path to the associated database file from zPath. This block handles
5896 ** the following naming conventions:
5897 **
5898 ** "<path to db>-journal"
5899 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005900 ** "<path to db>-journalNN"
5901 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005902 **
drhd337c5b2011-10-20 18:23:35 +00005903 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005904 ** used by the test_multiplex.c module.
5905 */
5906 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005907 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005908 /* In normal operation, the journal file name will always contain
5909 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5910 ** rollback journal specifies a master journal with a goofy name, then
5911 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005912 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005913 nDb--;
5914 }
danddb0ac42010-07-14 14:48:58 +00005915 memcpy(zDb, zPath, nDb);
5916 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005917
dan1bf4ca72016-08-11 18:05:47 +00005918 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005919 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5920 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005921 }else if( flags & SQLITE_OPEN_URI ){
5922 /* If this is a main database file and the file was opened using a URI
5923 ** filename, check for the "modeof" parameter. If present, interpret
5924 ** its value as a filename and try to copy the mode, uid and gid from
5925 ** that file. */
5926 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5927 if( z ){
5928 rc = getFileMode(z, pMode, pUid, pGid);
5929 }
danddb0ac42010-07-14 14:48:58 +00005930 }
5931 return rc;
5932}
5933
5934/*
danielk1977ad94b582007-08-20 06:44:22 +00005935** Open the file zPath.
5936**
danielk1977b4b47412007-08-17 15:53:36 +00005937** Previously, the SQLite OS layer used three functions in place of this
5938** one:
5939**
5940** sqlite3OsOpenReadWrite();
5941** sqlite3OsOpenReadOnly();
5942** sqlite3OsOpenExclusive();
5943**
5944** These calls correspond to the following combinations of flags:
5945**
5946** ReadWrite() -> (READWRITE | CREATE)
5947** ReadOnly() -> (READONLY)
5948** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5949**
5950** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5951** true, the file was configured to be automatically deleted when the
5952** file handle closed. To achieve the same effect using this new
5953** interface, add the DELETEONCLOSE flag to those specified above for
5954** OpenExclusive().
5955*/
5956static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005957 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5958 const char *zPath, /* Pathname of file to be opened */
5959 sqlite3_file *pFile, /* The file descriptor to be filled in */
5960 int flags, /* Input flags to control the opening */
5961 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005962){
dan08da86a2009-08-21 17:18:03 +00005963 unixFile *p = (unixFile *)pFile;
5964 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005965 int openFlags = 0; /* Flags to pass to open() */
drhc398c652019-11-22 00:42:01 +00005966 int eType = flags&0x0FFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005967 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005968 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005969 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005970
5971 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5972 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5973 int isCreate = (flags & SQLITE_OPEN_CREATE);
5974 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5975 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005976#if SQLITE_ENABLE_LOCKING_STYLE
5977 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5978#endif
drh3d4435b2011-08-26 20:55:50 +00005979#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5980 struct statfs fsInfo;
5981#endif
danielk1977b4b47412007-08-17 15:53:36 +00005982
danielk1977fee2d252007-08-18 10:59:19 +00005983 /* If creating a master or main-file journal, this function will open
5984 ** a file-descriptor on the directory too. The first time unixSync()
5985 ** is called the directory file descriptor will be fsync()ed and close()d.
5986 */
drha803a2c2017-12-13 20:02:29 +00005987 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005988 eType==SQLITE_OPEN_MASTER_JOURNAL
5989 || eType==SQLITE_OPEN_MAIN_JOURNAL
5990 || eType==SQLITE_OPEN_WAL
5991 ));
danielk1977fee2d252007-08-18 10:59:19 +00005992
danielk197717b90b52008-06-06 11:11:25 +00005993 /* If argument zPath is a NULL pointer, this function is required to open
5994 ** a temporary file. Use this buffer to store the file name in.
5995 */
drhc02a43a2012-01-10 23:18:38 +00005996 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005997 const char *zName = zPath;
5998
danielk1977fee2d252007-08-18 10:59:19 +00005999 /* Check the following statements are true:
6000 **
6001 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
6002 ** (b) if CREATE is set, then READWRITE must also be set, and
6003 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00006004 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00006005 */
danielk1977b4b47412007-08-17 15:53:36 +00006006 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00006007 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00006008 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00006009 assert(isDelete==0 || isCreate);
6010
danddb0ac42010-07-14 14:48:58 +00006011 /* The main DB, main journal, WAL file and master journal are never
6012 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00006013 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6014 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
6015 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006016 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00006017
danielk1977fee2d252007-08-18 10:59:19 +00006018 /* Assert that the upper layer has set one of the "file-type" flags. */
6019 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6020 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
6021 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006022 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00006023 );
6024
drhb00d8622014-01-01 15:18:36 +00006025 /* Detect a pid change and reset the PRNG. There is a race condition
6026 ** here such that two or more threads all trying to open databases at
6027 ** the same instant might all reset the PRNG. But multiple resets
6028 ** are harmless.
6029 */
drh5ac93652015-03-21 20:59:43 +00006030 if( randomnessPid!=osGetpid(0) ){
6031 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00006032 sqlite3_randomness(0,0);
6033 }
dan08da86a2009-08-21 17:18:03 +00006034 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00006035
dan08da86a2009-08-21 17:18:03 +00006036 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00006037 UnixUnusedFd *pUnused;
6038 pUnused = findReusableFd(zName, flags);
6039 if( pUnused ){
6040 fd = pUnused->fd;
6041 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006042 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00006043 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006044 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00006045 }
6046 }
drhc68886b2017-08-18 16:09:52 +00006047 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00006048
6049 /* Database filenames are double-zero terminated if they are not
6050 ** URIs with parameters. Hence, they can always be passed into
6051 ** sqlite3_uri_parameter(). */
6052 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6053
dan08da86a2009-08-21 17:18:03 +00006054 }else if( !zName ){
6055 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00006056 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00006057 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00006058 if( rc!=SQLITE_OK ){
6059 return rc;
6060 }
6061 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006062
6063 /* Generated temporary filenames are always double-zero terminated
6064 ** for use by sqlite3_uri_parameter(). */
6065 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006066 }
6067
dan08da86a2009-08-21 17:18:03 +00006068 /* Determine the value of the flags parameter passed to POSIX function
6069 ** open(). These must be calculated even if open() is not called, as
6070 ** they may be stored as part of the file handle and used by the
6071 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006072 if( isReadonly ) openFlags |= O_RDONLY;
6073 if( isReadWrite ) openFlags |= O_RDWR;
6074 if( isCreate ) openFlags |= O_CREAT;
6075 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
drhc398c652019-11-22 00:42:01 +00006076 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
danielk1977b4b47412007-08-17 15:53:36 +00006077
danielk1977b4b47412007-08-17 15:53:36 +00006078 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006079 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006080 uid_t uid; /* Userid for the file */
6081 gid_t gid; /* Groupid for the file */
6082 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006083 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006084 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006085 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006086 return rc;
6087 }
drhad4f1e52011-03-04 15:43:57 +00006088 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006089 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006090 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006091 if( fd<0 ){
6092 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6093 /* If unable to create a journal because the directory is not
6094 ** writable, change the error code to indicate that. */
6095 rc = SQLITE_READONLY_DIRECTORY;
6096 }else if( errno!=EISDIR && isReadWrite ){
6097 /* Failed to open the file for read/write access. Try read-only. */
6098 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6099 openFlags &= ~(O_RDWR|O_CREAT);
6100 flags |= SQLITE_OPEN_READONLY;
6101 openFlags |= O_RDONLY;
6102 isReadonly = 1;
6103 fd = robust_open(zName, openFlags, openMode);
6104 }
dan08da86a2009-08-21 17:18:03 +00006105 }
6106 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006107 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6108 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006109 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006110 }
drhac7c3ac2012-02-11 19:23:48 +00006111
drh1116b172019-09-25 10:36:31 +00006112 /* The owner of the rollback journal or WAL file should always be the
6113 ** same as the owner of the database file. Try to ensure that this is
6114 ** the case. The chown() system call will be a no-op if the current
6115 ** process lacks root privileges, be we should at least try. Without
6116 ** this step, if a root process opens a database file, it can leave
6117 ** behinds a journal/WAL that is owned by root and hence make the
6118 ** database inaccessible to unprivileged processes.
6119 **
drhedf8a7b2019-09-25 11:49:36 +00006120 ** If openMode==0, then that means uid and gid are not set correctly
drh1116b172019-09-25 10:36:31 +00006121 ** (probably because SQLite is configured to use 8+3 filename mode) and
6122 ** in that case we do not want to attempt the chown().
drhac7c3ac2012-02-11 19:23:48 +00006123 */
drhedf8a7b2019-09-25 11:49:36 +00006124 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
drh6226ca22015-11-24 15:06:28 +00006125 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006126 }
danielk1977b4b47412007-08-17 15:53:36 +00006127 }
dan08da86a2009-08-21 17:18:03 +00006128 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006129 if( pOutFlags ){
6130 *pOutFlags = flags;
6131 }
6132
drhc68886b2017-08-18 16:09:52 +00006133 if( p->pPreallocatedUnused ){
6134 p->pPreallocatedUnused->fd = fd;
drh55220a62019-08-06 20:55:06 +00006135 p->pPreallocatedUnused->flags =
6136 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
dane946c392009-08-22 11:39:46 +00006137 }
6138
danielk1977b4b47412007-08-17 15:53:36 +00006139 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006140#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006141 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006142#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6143 zPath = sqlite3_mprintf("%s", zName);
6144 if( zPath==0 ){
6145 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006146 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006147 }
chw97185482008-11-17 08:05:31 +00006148#else
drh036ac7f2011-08-08 23:18:05 +00006149 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006150#endif
danielk1977b4b47412007-08-17 15:53:36 +00006151 }
drh41022642008-11-21 00:24:42 +00006152#if SQLITE_ENABLE_LOCKING_STYLE
6153 else{
dan08da86a2009-08-21 17:18:03 +00006154 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006155 }
6156#endif
drh7ed97b92010-01-20 13:07:21 +00006157
6158#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006159 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006160 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006161 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006162 return SQLITE_IOERR_ACCESS;
6163 }
6164 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6165 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6166 }
drh4bf66fd2015-02-19 02:43:02 +00006167 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6168 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6169 }
drh7ed97b92010-01-20 13:07:21 +00006170#endif
drhc02a43a2012-01-10 23:18:38 +00006171
6172 /* Set up appropriate ctrlFlags */
6173 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6174 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006175 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006176 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006177 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006178 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6179
drh7ed97b92010-01-20 13:07:21 +00006180#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006181#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006182 isAutoProxy = 1;
6183#endif
6184 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006185 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6186 int useProxy = 0;
6187
dan08da86a2009-08-21 17:18:03 +00006188 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6189 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006190 if( envforce!=NULL ){
6191 useProxy = atoi(envforce)>0;
6192 }else{
aswiftaebf4132008-11-21 00:10:35 +00006193 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6194 }
6195 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006196 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006197 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006198 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006199 if( rc!=SQLITE_OK ){
6200 /* Use unixClose to clean up the resources added in fillInUnixFile
6201 ** and clear all the structure's references. Specifically,
6202 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6203 */
6204 unixClose(pFile);
6205 return rc;
6206 }
aswiftaebf4132008-11-21 00:10:35 +00006207 }
dane946c392009-08-22 11:39:46 +00006208 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006209 }
6210 }
6211#endif
6212
dan3ed0f1c2017-09-14 21:12:07 +00006213 assert( zPath==0 || zPath[0]=='/'
6214 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6215 );
drhc02a43a2012-01-10 23:18:38 +00006216 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6217
dane946c392009-08-22 11:39:46 +00006218open_finished:
6219 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006220 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006221 }
6222 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006223}
6224
dane946c392009-08-22 11:39:46 +00006225
danielk1977b4b47412007-08-17 15:53:36 +00006226/*
danielk1977fee2d252007-08-18 10:59:19 +00006227** Delete the file at zPath. If the dirSync argument is true, fsync()
6228** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006229*/
drh6b9d6dd2008-12-03 19:34:47 +00006230static int unixDelete(
6231 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6232 const char *zPath, /* Name of file to be deleted */
6233 int dirSync /* If true, fsync() directory after deleting file */
6234){
danielk1977fee2d252007-08-18 10:59:19 +00006235 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006236 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006237 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006238 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006239 if( errno==ENOENT
6240#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006241 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006242#endif
6243 ){
dan9fc5b4a2012-11-09 20:17:26 +00006244 rc = SQLITE_IOERR_DELETE_NOENT;
6245 }else{
drhb4308162012-11-09 21:40:02 +00006246 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006247 }
drhb4308162012-11-09 21:40:02 +00006248 return rc;
drh5d4feff2010-07-14 01:45:22 +00006249 }
danielk1977d39fa702008-10-16 13:27:40 +00006250#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006251 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006252 int fd;
drh90315a22011-08-10 01:52:12 +00006253 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006254 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006255 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006256 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006257 }
drh0e9365c2011-03-02 02:08:13 +00006258 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006259 }else{
6260 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006261 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006262 }
6263 }
danielk1977d138dd82008-10-15 16:02:48 +00006264#endif
danielk1977fee2d252007-08-18 10:59:19 +00006265 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006266}
6267
danielk197790949c22007-08-17 16:50:38 +00006268/*
mistachkin48864df2013-03-21 21:20:32 +00006269** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006270** test performed depends on the value of flags:
6271**
6272** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6273** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6274** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6275**
6276** Otherwise return 0.
6277*/
danielk1977861f7452008-06-05 11:39:11 +00006278static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006279 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6280 const char *zPath, /* Path of the file to examine */
6281 int flags, /* What do we want to learn about the zPath file? */
6282 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006283){
danielk1977397d65f2008-11-19 11:35:39 +00006284 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006285 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006286 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006287
drhc398c652019-11-22 00:42:01 +00006288 /* The spec says there are three possible values for flags. But only
6289 ** two of them are actually used */
6290 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
drhd260b5b2015-11-25 18:03:33 +00006291
6292 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006293 struct stat buf;
drh96e8eeb2019-12-26 00:56:50 +00006294 *pResOut = 0==osStat(zPath, &buf) &&
drh09bee572019-12-27 13:30:46 +00006295 (!S_ISREG(buf.st_mode) || buf.st_size>0);
drh0933aad2019-11-18 17:46:38 +00006296 }else{
drhc398c652019-11-22 00:42:01 +00006297 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006298 }
danielk1977861f7452008-06-05 11:39:11 +00006299 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006300}
6301
danielk1977b4b47412007-08-17 15:53:36 +00006302/*
danielk1977b4b47412007-08-17 15:53:36 +00006303**
danielk1977b4b47412007-08-17 15:53:36 +00006304*/
dane88ec182016-01-25 17:04:48 +00006305static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006306 const char *zPath, /* Input path */
6307 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006308 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006309){
dancaf6b152016-01-25 18:05:49 +00006310 int nPath = sqlite3Strlen30(zPath);
6311 int iOff = 0;
6312 if( zPath[0]!='/' ){
6313 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006314 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006315 }
dancaf6b152016-01-25 18:05:49 +00006316 iOff = sqlite3Strlen30(zOut);
6317 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006318 }
dan23496702016-01-26 13:56:42 +00006319 if( (iOff+nPath+1)>nOut ){
6320 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6321 ** even if it returns an error. */
6322 zOut[iOff] = '\0';
6323 return SQLITE_CANTOPEN_BKPT;
6324 }
dancaf6b152016-01-25 18:05:49 +00006325 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006326 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006327}
6328
dane88ec182016-01-25 17:04:48 +00006329/*
6330** Turn a relative pathname into a full pathname. The relative path
6331** is stored as a nul-terminated string in the buffer pointed to by
6332** zPath.
6333**
6334** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6335** (in this case, MAX_PATHNAME bytes). The full-path is written to
6336** this buffer before returning.
6337*/
6338static int unixFullPathname(
6339 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6340 const char *zPath, /* Possibly relative input path */
6341 int nOut, /* Size of output buffer in bytes */
6342 char *zOut /* Output buffer */
6343){
danaf1b36b2016-01-25 18:43:05 +00006344#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006345 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006346#else
6347 int rc = SQLITE_OK;
6348 int nByte;
drhc398c652019-11-22 00:42:01 +00006349 int nLink = 0; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006350 const char *zIn = zPath; /* Input path for each iteration of loop */
6351 char *zDel = 0;
6352
6353 assert( pVfs->mxPathname==MAX_PATHNAME );
6354 UNUSED_PARAMETER(pVfs);
6355
6356 /* It's odd to simulate an io-error here, but really this is just
6357 ** using the io-error infrastructure to test that SQLite handles this
6358 ** function failing. This function could fail if, for example, the
6359 ** current working directory has been unlinked.
6360 */
6361 SimulateIOError( return SQLITE_ERROR );
6362
6363 do {
6364
dancaf6b152016-01-25 18:05:49 +00006365 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6366 ** link, or false otherwise. */
6367 int bLink = 0;
6368 struct stat buf;
6369 if( osLstat(zIn, &buf)!=0 ){
6370 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006371 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006372 }
dane88ec182016-01-25 17:04:48 +00006373 }else{
dancaf6b152016-01-25 18:05:49 +00006374 bLink = S_ISLNK(buf.st_mode);
6375 }
6376
6377 if( bLink ){
drhc398c652019-11-22 00:42:01 +00006378 nLink++;
dane88ec182016-01-25 17:04:48 +00006379 if( zDel==0 ){
6380 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006381 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
drhc398c652019-11-22 00:42:01 +00006382 }else if( nLink>=SQLITE_MAX_SYMLINKS ){
dancaf6b152016-01-25 18:05:49 +00006383 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006384 }
dancaf6b152016-01-25 18:05:49 +00006385
6386 if( rc==SQLITE_OK ){
6387 nByte = osReadlink(zIn, zDel, nOut-1);
6388 if( nByte<0 ){
6389 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006390 }else{
6391 if( zDel[0]!='/' ){
6392 int n;
6393 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6394 if( nByte+n+1>nOut ){
6395 rc = SQLITE_CANTOPEN_BKPT;
6396 }else{
6397 memmove(&zDel[n], zDel, nByte+1);
6398 memcpy(zDel, zIn, n);
6399 nByte += n;
6400 }
dancaf6b152016-01-25 18:05:49 +00006401 }
6402 zDel[nByte] = '\0';
6403 }
6404 }
6405
6406 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006407 }
6408
dan23496702016-01-26 13:56:42 +00006409 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6410 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006411 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006412 }
dancaf6b152016-01-25 18:05:49 +00006413 if( bLink==0 ) break;
6414 zIn = zOut;
6415 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006416
6417 sqlite3_free(zDel);
drhc398c652019-11-22 00:42:01 +00006418 if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
dane88ec182016-01-25 17:04:48 +00006419 return rc;
danaf1b36b2016-01-25 18:43:05 +00006420#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006421}
6422
drh0ccebe72005-06-07 22:22:50 +00006423
drh761df872006-12-21 01:29:22 +00006424#ifndef SQLITE_OMIT_LOAD_EXTENSION
6425/*
6426** Interfaces for opening a shared library, finding entry points
6427** within the shared library, and closing the shared library.
6428*/
6429#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006430static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6431 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006432 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6433}
danielk197795c8a542007-09-01 06:51:27 +00006434
6435/*
6436** SQLite calls this function immediately after a call to unixDlSym() or
6437** unixDlOpen() fails (returns a null pointer). If a more detailed error
6438** message is available, it is written to zBufOut. If no error message
6439** is available, zBufOut is left unmodified and SQLite uses a default
6440** error message.
6441*/
danielk1977397d65f2008-11-19 11:35:39 +00006442static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006443 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006444 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006445 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006446 zErr = dlerror();
6447 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006448 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006449 }
drh6c7d5c52008-11-21 20:32:33 +00006450 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006451}
drh1875f7a2008-12-08 18:19:17 +00006452static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6453 /*
6454 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6455 ** cast into a pointer to a function. And yet the library dlsym() routine
6456 ** returns a void* which is really a pointer to a function. So how do we
6457 ** use dlsym() with -pedantic-errors?
6458 **
6459 ** Variable x below is defined to be a pointer to a function taking
6460 ** parameters void* and const char* and returning a pointer to a function.
6461 ** We initialize x by assigning it a pointer to the dlsym() function.
6462 ** (That assignment requires a cast.) Then we call the function that
6463 ** x points to.
6464 **
6465 ** This work-around is unlikely to work correctly on any system where
6466 ** you really cannot cast a function pointer into void*. But then, on the
6467 ** other hand, dlsym() will not work on such a system either, so we have
6468 ** not really lost anything.
6469 */
6470 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006471 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006472 x = (void(*(*)(void*,const char*))(void))dlsym;
6473 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006474}
danielk1977397d65f2008-11-19 11:35:39 +00006475static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6476 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006477 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006478}
danielk1977b4b47412007-08-17 15:53:36 +00006479#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6480 #define unixDlOpen 0
6481 #define unixDlError 0
6482 #define unixDlSym 0
6483 #define unixDlClose 0
6484#endif
6485
6486/*
danielk197790949c22007-08-17 16:50:38 +00006487** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006488*/
danielk1977397d65f2008-11-19 11:35:39 +00006489static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6490 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006491 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006492
drhbbd42a62004-05-22 17:41:58 +00006493 /* We have to initialize zBuf to prevent valgrind from reporting
6494 ** errors. The reports issued by valgrind are incorrect - we would
6495 ** prefer that the randomness be increased by making use of the
6496 ** uninitialized space in zBuf - but valgrind errors tend to worry
6497 ** some users. Rather than argue, it seems easier just to initialize
6498 ** the whole array and silence valgrind, even if that means less randomness
6499 ** in the random seed.
6500 **
6501 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006502 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006503 ** tests repeatable.
6504 */
danielk1977b4b47412007-08-17 15:53:36 +00006505 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006506 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006507#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006508 {
drhb00d8622014-01-01 15:18:36 +00006509 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006510 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006511 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006512 time_t t;
6513 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006514 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006515 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6516 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6517 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006518 }else{
drhc18b4042012-02-10 03:10:27 +00006519 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006520 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006521 }
drhbbd42a62004-05-22 17:41:58 +00006522 }
6523#endif
drh72cbd072008-10-14 17:58:38 +00006524 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006525}
6526
danielk1977b4b47412007-08-17 15:53:36 +00006527
drhbbd42a62004-05-22 17:41:58 +00006528/*
6529** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006530** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006531** The return value is the number of microseconds of sleep actually
6532** requested from the underlying operating system, a number which
6533** might be greater than or equal to the argument, but not less
6534** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006535*/
danielk1977397d65f2008-11-19 11:35:39 +00006536static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006537#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006538 struct timespec sp;
6539
6540 sp.tv_sec = microseconds / 1000000;
6541 sp.tv_nsec = (microseconds % 1000000) * 1000;
6542 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006543 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006544 return microseconds;
6545#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006546 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006547 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006548 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006549#else
danielk1977b4b47412007-08-17 15:53:36 +00006550 int seconds = (microseconds+999999)/1000000;
6551 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006552 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006553 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006554#endif
drh88f474a2006-01-02 20:00:12 +00006555}
6556
6557/*
drh6b9d6dd2008-12-03 19:34:47 +00006558** The following variable, if set to a non-zero value, is interpreted as
6559** the number of seconds since 1970 and is used to set the result of
6560** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006561*/
6562#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006563int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006564#endif
6565
6566/*
drhb7e8ea22010-05-03 14:32:30 +00006567** Find the current time (in Universal Coordinated Time). Write into *piNow
6568** the current time and date as a Julian Day number times 86_400_000. In
6569** other words, write into *piNow the number of milliseconds since the Julian
6570** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6571** proleptic Gregorian calendar.
6572**
drh31702252011-10-12 23:13:43 +00006573** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6574** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006575*/
6576static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6577 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006578 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006579#if defined(NO_GETTOD)
6580 time_t t;
6581 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006582 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006583#elif OS_VXWORKS
6584 struct timespec sNow;
6585 clock_gettime(CLOCK_REALTIME, &sNow);
6586 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6587#else
6588 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006589 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6590 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006591#endif
6592
6593#ifdef SQLITE_TEST
6594 if( sqlite3_current_time ){
6595 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6596 }
6597#endif
6598 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006599 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006600}
6601
drhc3dfa5e2016-01-22 19:44:03 +00006602#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006603/*
drhbbd42a62004-05-22 17:41:58 +00006604** Find the current time (in Universal Coordinated Time). Write the
6605** current time and date as a Julian Day number into *prNow and
6606** return 0. Return 1 if the time and date cannot be found.
6607*/
danielk1977397d65f2008-11-19 11:35:39 +00006608static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006609 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006610 int rc;
drhff828942010-06-26 21:34:06 +00006611 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006612 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006613 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006614 return rc;
drhbbd42a62004-05-22 17:41:58 +00006615}
drh5337dac2015-11-25 15:15:03 +00006616#else
6617# define unixCurrentTime 0
6618#endif
danielk1977b4b47412007-08-17 15:53:36 +00006619
drh6b9d6dd2008-12-03 19:34:47 +00006620/*
drh1b9f2142016-03-17 16:01:23 +00006621** The xGetLastError() method is designed to return a better
6622** low-level error message when operating-system problems come up
6623** during SQLite operation. Only the integer return code is currently
6624** used.
drh6b9d6dd2008-12-03 19:34:47 +00006625*/
danielk1977397d65f2008-11-19 11:35:39 +00006626static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6627 UNUSED_PARAMETER(NotUsed);
6628 UNUSED_PARAMETER(NotUsed2);
6629 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006630 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006631}
6632
drhf2424c52010-04-26 00:04:55 +00006633
6634/*
drh734c9862008-11-28 15:37:20 +00006635************************ End of sqlite3_vfs methods ***************************
6636******************************************************************************/
6637
drh715ff302008-12-03 22:32:44 +00006638/******************************************************************************
6639************************** Begin Proxy Locking ********************************
6640**
6641** Proxy locking is a "uber-locking-method" in this sense: It uses the
6642** other locking methods on secondary lock files. Proxy locking is a
6643** meta-layer over top of the primitive locking implemented above. For
6644** this reason, the division that implements of proxy locking is deferred
6645** until late in the file (here) after all of the other I/O methods have
6646** been defined - so that the primitive locking methods are available
6647** as services to help with the implementation of proxy locking.
6648**
6649****
6650**
6651** The default locking schemes in SQLite use byte-range locks on the
6652** database file to coordinate safe, concurrent access by multiple readers
6653** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6654** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6655** as POSIX read & write locks over fixed set of locations (via fsctl),
6656** on AFP and SMB only exclusive byte-range locks are available via fsctl
6657** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6658** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6659** address in the shared range is taken for a SHARED lock, the entire
6660** shared range is taken for an EXCLUSIVE lock):
6661**
drhf2f105d2012-08-20 15:53:54 +00006662** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006663** RESERVED_BYTE 0x40000001
6664** SHARED_RANGE 0x40000002 -> 0x40000200
6665**
6666** This works well on the local file system, but shows a nearly 100x
6667** slowdown in read performance on AFP because the AFP client disables
6668** the read cache when byte-range locks are present. Enabling the read
6669** cache exposes a cache coherency problem that is present on all OS X
6670** supported network file systems. NFS and AFP both observe the
6671** close-to-open semantics for ensuring cache coherency
6672** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6673** address the requirements for concurrent database access by multiple
6674** readers and writers
6675** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6676**
6677** To address the performance and cache coherency issues, proxy file locking
6678** changes the way database access is controlled by limiting access to a
6679** single host at a time and moving file locks off of the database file
6680** and onto a proxy file on the local file system.
6681**
6682**
6683** Using proxy locks
6684** -----------------
6685**
6686** C APIs
6687**
drh4bf66fd2015-02-19 02:43:02 +00006688** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006689** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006690** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6691** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006692**
6693**
6694** SQL pragmas
6695**
6696** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6697** PRAGMA [database.]lock_proxy_file
6698**
6699** Specifying ":auto:" means that if there is a conch file with a matching
6700** host ID in it, the proxy path in the conch file will be used, otherwise
6701** a proxy path based on the user's temp dir
6702** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6703** actual proxy file name is generated from the name and path of the
6704** database file. For example:
6705**
6706** For database path "/Users/me/foo.db"
6707** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6708**
6709** Once a lock proxy is configured for a database connection, it can not
6710** be removed, however it may be switched to a different proxy path via
6711** the above APIs (assuming the conch file is not being held by another
6712** connection or process).
6713**
6714**
6715** How proxy locking works
6716** -----------------------
6717**
6718** Proxy file locking relies primarily on two new supporting files:
6719**
6720** * conch file to limit access to the database file to a single host
6721** at a time
6722**
6723** * proxy file to act as a proxy for the advisory locks normally
6724** taken on the database
6725**
6726** The conch file - to use a proxy file, sqlite must first "hold the conch"
6727** by taking an sqlite-style shared lock on the conch file, reading the
6728** contents and comparing the host's unique host ID (see below) and lock
6729** proxy path against the values stored in the conch. The conch file is
6730** stored in the same directory as the database file and the file name
6731** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006732** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006733** host ID and/or proxy path, then the lock is escalated to an exclusive
6734** lock and the conch file contents is updated with the host ID and proxy
6735** path and the lock is downgraded to a shared lock again. If the conch
6736** is held by another process (with a shared lock), the exclusive lock
6737** will fail and SQLITE_BUSY is returned.
6738**
6739** The proxy file - a single-byte file used for all advisory file locks
6740** normally taken on the database file. This allows for safe sharing
6741** of the database file for multiple readers and writers on the same
6742** host (the conch ensures that they all use the same local lock file).
6743**
drh715ff302008-12-03 22:32:44 +00006744** Requesting the lock proxy does not immediately take the conch, it is
6745** only taken when the first request to lock database file is made.
6746** This matches the semantics of the traditional locking behavior, where
6747** opening a connection to a database file does not take a lock on it.
6748** The shared lock and an open file descriptor are maintained until
6749** the connection to the database is closed.
6750**
6751** The proxy file and the lock file are never deleted so they only need
6752** to be created the first time they are used.
6753**
6754** Configuration options
6755** ---------------------
6756**
6757** SQLITE_PREFER_PROXY_LOCKING
6758**
6759** Database files accessed on non-local file systems are
6760** automatically configured for proxy locking, lock files are
6761** named automatically using the same logic as
6762** PRAGMA lock_proxy_file=":auto:"
6763**
6764** SQLITE_PROXY_DEBUG
6765**
6766** Enables the logging of error messages during host id file
6767** retrieval and creation
6768**
drh715ff302008-12-03 22:32:44 +00006769** LOCKPROXYDIR
6770**
6771** Overrides the default directory used for lock proxy files that
6772** are named automatically via the ":auto:" setting
6773**
6774** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6775**
6776** Permissions to use when creating a directory for storing the
6777** lock proxy files, only used when LOCKPROXYDIR is not set.
6778**
6779**
6780** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6781** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6782** force proxy locking to be used for every database file opened, and 0
6783** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006784** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006785** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6786*/
6787
6788/*
6789** Proxy locking is only available on MacOSX
6790*/
drhd2cb50b2009-01-09 21:41:17 +00006791#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006792
drh715ff302008-12-03 22:32:44 +00006793/*
6794** The proxyLockingContext has the path and file structures for the remote
6795** and local proxy files in it
6796*/
6797typedef struct proxyLockingContext proxyLockingContext;
6798struct proxyLockingContext {
6799 unixFile *conchFile; /* Open conch file */
6800 char *conchFilePath; /* Name of the conch file */
6801 unixFile *lockProxy; /* Open proxy lock file */
6802 char *lockProxyPath; /* Name of the proxy lock file */
6803 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006804 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006805 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006806 void *oldLockingContext; /* Original lockingcontext to restore on close */
6807 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6808};
6809
drh7ed97b92010-01-20 13:07:21 +00006810/*
6811** The proxy lock file path for the database at dbPath is written into lPath,
6812** which must point to valid, writable memory large enough for a maxLen length
6813** file path.
drh715ff302008-12-03 22:32:44 +00006814*/
drh715ff302008-12-03 22:32:44 +00006815static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6816 int len;
6817 int dbLen;
6818 int i;
6819
6820#ifdef LOCKPROXYDIR
6821 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6822#else
6823# ifdef _CS_DARWIN_USER_TEMP_DIR
6824 {
drh7ed97b92010-01-20 13:07:21 +00006825 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006826 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006827 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006828 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006829 }
drh7ed97b92010-01-20 13:07:21 +00006830 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006831 }
6832# else
6833 len = strlcpy(lPath, "/tmp/", maxLen);
6834# endif
6835#endif
6836
6837 if( lPath[len-1]!='/' ){
6838 len = strlcat(lPath, "/", maxLen);
6839 }
6840
6841 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006842 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006843 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006844 char c = dbPath[i];
6845 lPath[i+len] = (c=='/')?'_':c;
6846 }
6847 lPath[i+len]='\0';
6848 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006849 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006850 return SQLITE_OK;
6851}
6852
drh7ed97b92010-01-20 13:07:21 +00006853/*
6854 ** Creates the lock file and any missing directories in lockPath
6855 */
6856static int proxyCreateLockPath(const char *lockPath){
6857 int i, len;
6858 char buf[MAXPATHLEN];
6859 int start = 0;
6860
6861 assert(lockPath!=NULL);
6862 /* try to create all the intermediate directories */
6863 len = (int)strlen(lockPath);
6864 buf[0] = lockPath[0];
6865 for( i=1; i<len; i++ ){
6866 if( lockPath[i] == '/' && (i - start > 0) ){
6867 /* only mkdir if leaf dir != "." or "/" or ".." */
6868 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6869 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6870 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006871 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006872 int err=errno;
6873 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006874 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006875 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006876 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006877 return err;
6878 }
6879 }
6880 }
6881 start=i+1;
6882 }
6883 buf[i] = lockPath[i];
6884 }
drh62aaa6c2015-11-21 17:27:42 +00006885 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006886 return 0;
6887}
6888
drh715ff302008-12-03 22:32:44 +00006889/*
6890** Create a new VFS file descriptor (stored in memory obtained from
6891** sqlite3_malloc) and open the file named "path" in the file descriptor.
6892**
6893** The caller is responsible not only for closing the file descriptor
6894** but also for freeing the memory associated with the file descriptor.
6895*/
drh7ed97b92010-01-20 13:07:21 +00006896static int proxyCreateUnixFile(
6897 const char *path, /* path for the new unixFile */
6898 unixFile **ppFile, /* unixFile created and returned by ref */
6899 int islockfile /* if non zero missing dirs will be created */
6900) {
6901 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006902 unixFile *pNew;
6903 int rc = SQLITE_OK;
drhc398c652019-11-22 00:42:01 +00006904 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
drh715ff302008-12-03 22:32:44 +00006905 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006906 int terrno = 0;
6907 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006908
drh7ed97b92010-01-20 13:07:21 +00006909 /* 1. first try to open/create the file
6910 ** 2. if that fails, and this is a lock file (not-conch), try creating
6911 ** the parent directories and then try again.
6912 ** 3. if that fails, try to open the file read-only
6913 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6914 */
6915 pUnused = findReusableFd(path, openFlags);
6916 if( pUnused ){
6917 fd = pUnused->fd;
6918 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006919 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006920 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006921 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006922 }
6923 }
6924 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006925 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006926 terrno = errno;
6927 if( fd<0 && errno==ENOENT && islockfile ){
6928 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006929 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006930 }
6931 }
6932 }
6933 if( fd<0 ){
drhc398c652019-11-22 00:42:01 +00006934 openFlags = O_RDONLY | O_NOFOLLOW;
drh8c815d12012-02-13 20:16:37 +00006935 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006936 terrno = errno;
6937 }
6938 if( fd<0 ){
6939 if( islockfile ){
6940 return SQLITE_BUSY;
6941 }
6942 switch (terrno) {
6943 case EACCES:
6944 return SQLITE_PERM;
6945 case EIO:
6946 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6947 default:
drh9978c972010-02-23 17:36:32 +00006948 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006949 }
6950 }
6951
drhf3cdcdc2015-04-29 16:50:28 +00006952 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006953 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006954 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006955 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006956 }
6957 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006958 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006959 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006960 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006961 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006962 pUnused->fd = fd;
6963 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006964 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006965
drhc02a43a2012-01-10 23:18:38 +00006966 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006967 if( rc==SQLITE_OK ){
6968 *ppFile = pNew;
6969 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006970 }
drh7ed97b92010-01-20 13:07:21 +00006971end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006972 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006973 sqlite3_free(pNew);
6974 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006975 return rc;
6976}
6977
drh7ed97b92010-01-20 13:07:21 +00006978#ifdef SQLITE_TEST
6979/* simulate multiple hosts by creating unique hostid file paths */
6980int sqlite3_hostid_num = 0;
6981#endif
6982
6983#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6984
drhe4079e12019-09-27 16:33:27 +00006985#if HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006986/* Not always defined in the headers as it ought to be */
6987extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006988#endif
drh0ab216a2010-07-02 17:10:40 +00006989
drh7ed97b92010-01-20 13:07:21 +00006990/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6991** bytes of writable memory.
6992*/
6993static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006994 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6995 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe4079e12019-09-27 16:33:27 +00006996#if HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006997 {
drh4bf66fd2015-02-19 02:43:02 +00006998 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006999 if( gethostuuid(pHostID, &timeout) ){
7000 int err = errno;
7001 if( pError ){
7002 *pError = err;
7003 }
7004 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00007005 }
drh7ed97b92010-01-20 13:07:21 +00007006 }
drh3d4435b2011-08-26 20:55:50 +00007007#else
7008 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00007009#endif
drh7ed97b92010-01-20 13:07:21 +00007010#ifdef SQLITE_TEST
7011 /* simulate multiple hosts by creating unique hostid file paths */
7012 if( sqlite3_hostid_num != 0){
7013 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7014 }
7015#endif
7016
7017 return SQLITE_OK;
7018}
7019
7020/* The conch file contains the header, host id and lock file path
7021 */
7022#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7023#define PROXY_HEADERLEN 1 /* conch file header length */
7024#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7025#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7026
7027/*
7028** Takes an open conch file, copies the contents to a new path and then moves
7029** it back. The newly created file's file descriptor is assigned to the
7030** conch file structure and finally the original conch file descriptor is
7031** closed. Returns zero if successful.
7032*/
7033static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7034 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7035 unixFile *conchFile = pCtx->conchFile;
7036 char tPath[MAXPATHLEN];
7037 char buf[PROXY_MAXCONCHLEN];
7038 char *cPath = pCtx->conchFilePath;
7039 size_t readLen = 0;
7040 size_t pathLen = 0;
7041 char errmsg[64] = "";
7042 int fd = -1;
7043 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00007044 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00007045
7046 /* create a new path by replace the trailing '-conch' with '-break' */
7047 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7048 if( pathLen>MAXPATHLEN || pathLen<6 ||
7049 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00007050 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00007051 goto end_breaklock;
7052 }
7053 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00007054 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007055 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00007056 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00007057 goto end_breaklock;
7058 }
7059 /* write it out to the temporary break file */
drhc398c652019-11-22 00:42:01 +00007060 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
drh7ed97b92010-01-20 13:07:21 +00007061 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00007062 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007063 goto end_breaklock;
7064 }
drhe562be52011-03-02 18:01:10 +00007065 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00007066 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007067 goto end_breaklock;
7068 }
7069 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00007070 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007071 goto end_breaklock;
7072 }
7073 rc = 0;
7074 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007075 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007076 conchFile->h = fd;
7077 conchFile->openFlags = O_RDWR | O_CREAT;
7078
7079end_breaklock:
7080 if( rc ){
7081 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007082 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007083 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007084 }
7085 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7086 }
7087 return rc;
7088}
7089
7090/* Take the requested lock on the conch file and break a stale lock if the
7091** host id matches.
7092*/
7093static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7094 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7095 unixFile *conchFile = pCtx->conchFile;
7096 int rc = SQLITE_OK;
7097 int nTries = 0;
7098 struct timespec conchModTime;
7099
drh3d4435b2011-08-26 20:55:50 +00007100 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007101 do {
7102 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7103 nTries ++;
7104 if( rc==SQLITE_BUSY ){
7105 /* If the lock failed (busy):
7106 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7107 * 2nd try: fail if the mod time changed or host id is different, wait
7108 * 10 sec and try again
7109 * 3rd try: break the lock unless the mod time has changed.
7110 */
7111 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007112 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007113 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007114 return SQLITE_IOERR_LOCK;
7115 }
7116
7117 if( nTries==1 ){
7118 conchModTime = buf.st_mtimespec;
7119 usleep(500000); /* wait 0.5 sec and try the lock again*/
7120 continue;
7121 }
7122
7123 assert( nTries>1 );
7124 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7125 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7126 return SQLITE_BUSY;
7127 }
7128
7129 if( nTries==2 ){
7130 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007131 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007132 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007133 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007134 return SQLITE_IOERR_LOCK;
7135 }
7136 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7137 /* don't break the lock if the host id doesn't match */
7138 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7139 return SQLITE_BUSY;
7140 }
7141 }else{
7142 /* don't break the lock on short read or a version mismatch */
7143 return SQLITE_BUSY;
7144 }
7145 usleep(10000000); /* wait 10 sec and try the lock again */
7146 continue;
7147 }
7148
7149 assert( nTries==3 );
7150 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7151 rc = SQLITE_OK;
7152 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007153 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007154 }
7155 if( !rc ){
7156 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7157 }
7158 }
7159 }
7160 } while( rc==SQLITE_BUSY && nTries<3 );
7161
7162 return rc;
7163}
7164
7165/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007166** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7167** lockPath means that the lockPath in the conch file will be used if the
7168** host IDs match, or a new lock path will be generated automatically
7169** and written to the conch file.
7170*/
7171static int proxyTakeConch(unixFile *pFile){
7172 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7173
drh7ed97b92010-01-20 13:07:21 +00007174 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007175 return SQLITE_OK;
7176 }else{
7177 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007178 uuid_t myHostID;
7179 int pError = 0;
7180 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007181 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007182 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007183 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007184 int createConch = 0;
7185 int hostIdMatch = 0;
7186 int readLen = 0;
7187 int tryOldLockPath = 0;
7188 int forceNewLockPath = 0;
7189
drh308c2a52010-05-14 11:30:18 +00007190 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007191 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007192 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007193
drh7ed97b92010-01-20 13:07:21 +00007194 rc = proxyGetHostID(myHostID, &pError);
7195 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007196 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007197 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007198 }
drh7ed97b92010-01-20 13:07:21 +00007199 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007200 if( rc!=SQLITE_OK ){
7201 goto end_takeconch;
7202 }
drh7ed97b92010-01-20 13:07:21 +00007203 /* read the existing conch file */
7204 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7205 if( readLen<0 ){
7206 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007207 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007208 rc = SQLITE_IOERR_READ;
7209 goto end_takeconch;
7210 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7211 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7212 /* a short read or version format mismatch means we need to create a new
7213 ** conch file.
7214 */
7215 createConch = 1;
7216 }
7217 /* if the host id matches and the lock path already exists in the conch
7218 ** we'll try to use the path there, if we can't open that path, we'll
7219 ** retry with a new auto-generated path
7220 */
7221 do { /* in case we need to try again for an :auto: named lock file */
7222
7223 if( !createConch && !forceNewLockPath ){
7224 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7225 PROXY_HOSTIDLEN);
7226 /* if the conch has data compare the contents */
7227 if( !pCtx->lockProxyPath ){
7228 /* for auto-named local lock file, just check the host ID and we'll
7229 ** use the local lock file path that's already in there
7230 */
7231 if( hostIdMatch ){
7232 size_t pathLen = (readLen - PROXY_PATHINDEX);
7233
7234 if( pathLen>=MAXPATHLEN ){
7235 pathLen=MAXPATHLEN-1;
7236 }
7237 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7238 lockPath[pathLen] = 0;
7239 tempLockPath = lockPath;
7240 tryOldLockPath = 1;
7241 /* create a copy of the lock path if the conch is taken */
7242 goto end_takeconch;
7243 }
7244 }else if( hostIdMatch
7245 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7246 readLen-PROXY_PATHINDEX)
7247 ){
7248 /* conch host and lock path match */
7249 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007250 }
drh7ed97b92010-01-20 13:07:21 +00007251 }
7252
7253 /* if the conch isn't writable and doesn't match, we can't take it */
7254 if( (conchFile->openFlags&O_RDWR) == 0 ){
7255 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007256 goto end_takeconch;
7257 }
drh7ed97b92010-01-20 13:07:21 +00007258
7259 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007260 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007261 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7262 tempLockPath = lockPath;
7263 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007264 }
drh7ed97b92010-01-20 13:07:21 +00007265
7266 /* update conch with host and path (this will fail if other process
7267 ** has a shared lock already), if the host id matches, use the big
7268 ** stick.
drh715ff302008-12-03 22:32:44 +00007269 */
drh7ed97b92010-01-20 13:07:21 +00007270 futimes(conchFile->h, NULL);
7271 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007272 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007273 /* We are trying for an exclusive lock but another thread in this
7274 ** same process is still holding a shared lock. */
7275 rc = SQLITE_BUSY;
7276 } else {
7277 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007278 }
drh715ff302008-12-03 22:32:44 +00007279 }else{
drh4bf66fd2015-02-19 02:43:02 +00007280 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007281 }
drh7ed97b92010-01-20 13:07:21 +00007282 if( rc==SQLITE_OK ){
7283 char writeBuffer[PROXY_MAXCONCHLEN];
7284 int writeSize = 0;
7285
7286 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7287 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7288 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007289 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7290 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007291 }else{
7292 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7293 }
7294 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007295 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007296 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007297 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007298 /* If we created a new conch file (not just updated the contents of a
7299 ** valid conch file), try to match the permissions of the database
7300 */
7301 if( rc==SQLITE_OK && createConch ){
7302 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007303 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007304 if( err==0 ){
7305 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7306 S_IROTH|S_IWOTH);
7307 /* try to match the database file R/W permissions, ignore failure */
7308#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007309 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007310#else
drhff812312011-02-23 13:33:46 +00007311 do{
drhe562be52011-03-02 18:01:10 +00007312 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007313 }while( rc==(-1) && errno==EINTR );
7314 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007315 int code = errno;
7316 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7317 cmode, code, strerror(code));
7318 } else {
7319 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7320 }
7321 }else{
7322 int code = errno;
7323 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7324 err, code, strerror(code));
7325#endif
7326 }
drh715ff302008-12-03 22:32:44 +00007327 }
7328 }
drh7ed97b92010-01-20 13:07:21 +00007329 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7330
7331 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007332 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007333 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007334 int fd;
drh7ed97b92010-01-20 13:07:21 +00007335 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007336 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007337 }
7338 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007339 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007340 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007341 if( fd>=0 ){
7342 pFile->h = fd;
7343 }else{
drh9978c972010-02-23 17:36:32 +00007344 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007345 during locking */
7346 }
7347 }
7348 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7349 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7350 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7351 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7352 /* we couldn't create the proxy lock file with the old lock file path
7353 ** so try again via auto-naming
7354 */
7355 forceNewLockPath = 1;
7356 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007357 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007358 }
7359 }
7360 if( rc==SQLITE_OK ){
7361 /* Need to make a copy of path if we extracted the value
7362 ** from the conch file or the path was allocated on the stack
7363 */
7364 if( tempLockPath ){
7365 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7366 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007367 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007368 }
7369 }
7370 }
7371 if( rc==SQLITE_OK ){
7372 pCtx->conchHeld = 1;
7373
7374 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7375 afpLockingContext *afpCtx;
7376 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7377 afpCtx->dbPath = pCtx->lockProxyPath;
7378 }
7379 } else {
7380 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7381 }
drh308c2a52010-05-14 11:30:18 +00007382 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7383 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007384 return rc;
drh308c2a52010-05-14 11:30:18 +00007385 } while (1); /* in case we need to retry the :auto: lock file -
7386 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007387 }
7388}
7389
7390/*
7391** If pFile holds a lock on a conch file, then release that lock.
7392*/
7393static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007394 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007395 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7396 unixFile *conchFile; /* Name of the conch file */
7397
7398 pCtx = (proxyLockingContext *)pFile->lockingContext;
7399 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007400 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007401 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007402 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007403 if( pCtx->conchHeld>0 ){
7404 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7405 }
drh715ff302008-12-03 22:32:44 +00007406 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007407 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7408 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007409 return rc;
7410}
7411
7412/*
7413** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007414** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007415** Make *pConchPath point to the new name. Return SQLITE_OK on success
7416** or SQLITE_NOMEM if unable to obtain memory.
7417**
7418** The caller is responsible for ensuring that the allocated memory
7419** space is eventually freed.
7420**
7421** *pConchPath is set to NULL if a memory allocation error occurs.
7422*/
7423static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7424 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007425 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007426 char *conchPath; /* buffer in which to construct conch name */
7427
7428 /* Allocate space for the conch filename and initialize the name to
7429 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007430 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007431 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007432 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007433 }
7434 memcpy(conchPath, dbPath, len+1);
7435
7436 /* now insert a "." before the last / character */
7437 for( i=(len-1); i>=0; i-- ){
7438 if( conchPath[i]=='/' ){
7439 i++;
7440 break;
7441 }
7442 }
7443 conchPath[i]='.';
7444 while ( i<len ){
7445 conchPath[i+1]=dbPath[i];
7446 i++;
7447 }
7448
7449 /* append the "-conch" suffix to the file */
7450 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007451 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007452
7453 return SQLITE_OK;
7454}
7455
7456
7457/* Takes a fully configured proxy locking-style unix file and switches
7458** the local lock file path
7459*/
7460static int switchLockProxyPath(unixFile *pFile, const char *path) {
7461 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7462 char *oldPath = pCtx->lockProxyPath;
7463 int rc = SQLITE_OK;
7464
drh308c2a52010-05-14 11:30:18 +00007465 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007466 return SQLITE_BUSY;
7467 }
7468
7469 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7470 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7471 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7472 return SQLITE_OK;
7473 }else{
7474 unixFile *lockProxy = pCtx->lockProxy;
7475 pCtx->lockProxy=NULL;
7476 pCtx->conchHeld = 0;
7477 if( lockProxy!=NULL ){
7478 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7479 if( rc ) return rc;
7480 sqlite3_free(lockProxy);
7481 }
7482 sqlite3_free(oldPath);
7483 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7484 }
7485
7486 return rc;
7487}
7488
7489/*
7490** pFile is a file that has been opened by a prior xOpen call. dbPath
7491** is a string buffer at least MAXPATHLEN+1 characters in size.
7492**
7493** This routine find the filename associated with pFile and writes it
7494** int dbPath.
7495*/
7496static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007497#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007498 if( pFile->pMethod == &afpIoMethods ){
7499 /* afp style keeps a reference to the db path in the filePath field
7500 ** of the struct */
drhea678832008-12-10 19:26:22 +00007501 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007502 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7503 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007504 } else
drh715ff302008-12-03 22:32:44 +00007505#endif
7506 if( pFile->pMethod == &dotlockIoMethods ){
7507 /* dot lock style uses the locking context to store the dot lock
7508 ** file path */
7509 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7510 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7511 }else{
7512 /* all other styles use the locking context to store the db file path */
7513 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007514 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007515 }
7516 return SQLITE_OK;
7517}
7518
7519/*
7520** Takes an already filled in unix file and alters it so all file locking
7521** will be performed on the local proxy lock file. The following fields
7522** are preserved in the locking context so that they can be restored and
7523** the unix structure properly cleaned up at close time:
7524** ->lockingContext
7525** ->pMethod
7526*/
7527static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7528 proxyLockingContext *pCtx;
7529 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7530 char *lockPath=NULL;
7531 int rc = SQLITE_OK;
7532
drh308c2a52010-05-14 11:30:18 +00007533 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007534 return SQLITE_BUSY;
7535 }
7536 proxyGetDbPathForUnixFile(pFile, dbPath);
7537 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7538 lockPath=NULL;
7539 }else{
7540 lockPath=(char *)path;
7541 }
7542
drh308c2a52010-05-14 11:30:18 +00007543 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007544 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007545
drhf3cdcdc2015-04-29 16:50:28 +00007546 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007547 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007548 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007549 }
7550 memset(pCtx, 0, sizeof(*pCtx));
7551
7552 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7553 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007554 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7555 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7556 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7557 ** (c) the file system is read-only, then enable no-locking access.
7558 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7559 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7560 */
7561 struct statfs fsInfo;
7562 struct stat conchInfo;
7563 int goLockless = 0;
7564
drh99ab3b12011-03-02 15:09:07 +00007565 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007566 int err = errno;
7567 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7568 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7569 }
7570 }
7571 if( goLockless ){
7572 pCtx->conchHeld = -1; /* read only FS/ lockless */
7573 rc = SQLITE_OK;
7574 }
7575 }
drh715ff302008-12-03 22:32:44 +00007576 }
7577 if( rc==SQLITE_OK && lockPath ){
7578 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7579 }
7580
7581 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007582 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7583 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007584 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007585 }
7586 }
7587 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007588 /* all memory is allocated, proxys are created and assigned,
7589 ** switch the locking context and pMethod then return.
7590 */
drh715ff302008-12-03 22:32:44 +00007591 pCtx->oldLockingContext = pFile->lockingContext;
7592 pFile->lockingContext = pCtx;
7593 pCtx->pOldMethod = pFile->pMethod;
7594 pFile->pMethod = &proxyIoMethods;
7595 }else{
7596 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007597 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007598 sqlite3_free(pCtx->conchFile);
7599 }
drhd56b1212010-08-11 06:14:15 +00007600 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007601 sqlite3_free(pCtx->conchFilePath);
7602 sqlite3_free(pCtx);
7603 }
drh308c2a52010-05-14 11:30:18 +00007604 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7605 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007606 return rc;
7607}
7608
7609
7610/*
7611** This routine handles sqlite3_file_control() calls that are specific
7612** to proxy locking.
7613*/
7614static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7615 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007616 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007617 unixFile *pFile = (unixFile*)id;
7618 if( pFile->pMethod == &proxyIoMethods ){
7619 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7620 proxyTakeConch(pFile);
7621 if( pCtx->lockProxyPath ){
7622 *(const char **)pArg = pCtx->lockProxyPath;
7623 }else{
7624 *(const char **)pArg = ":auto: (not held)";
7625 }
7626 } else {
7627 *(const char **)pArg = NULL;
7628 }
7629 return SQLITE_OK;
7630 }
drh4bf66fd2015-02-19 02:43:02 +00007631 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007632 unixFile *pFile = (unixFile*)id;
7633 int rc = SQLITE_OK;
7634 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7635 if( pArg==NULL || (const char *)pArg==0 ){
7636 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007637 /* turn off proxy locking - not supported. If support is added for
7638 ** switching proxy locking mode off then it will need to fail if
7639 ** the journal mode is WAL mode.
7640 */
drh715ff302008-12-03 22:32:44 +00007641 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7642 }else{
7643 /* turn off proxy locking - already off - NOOP */
7644 rc = SQLITE_OK;
7645 }
7646 }else{
7647 const char *proxyPath = (const char *)pArg;
7648 if( isProxyStyle ){
7649 proxyLockingContext *pCtx =
7650 (proxyLockingContext*)pFile->lockingContext;
7651 if( !strcmp(pArg, ":auto:")
7652 || (pCtx->lockProxyPath &&
7653 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7654 ){
7655 rc = SQLITE_OK;
7656 }else{
7657 rc = switchLockProxyPath(pFile, proxyPath);
7658 }
7659 }else{
7660 /* turn on proxy file locking */
7661 rc = proxyTransformUnixFile(pFile, proxyPath);
7662 }
7663 }
7664 return rc;
7665 }
7666 default: {
7667 assert( 0 ); /* The call assures that only valid opcodes are sent */
7668 }
7669 }
drh8616cff2019-07-13 16:15:23 +00007670 /*NOTREACHED*/ assert(0);
drh715ff302008-12-03 22:32:44 +00007671 return SQLITE_ERROR;
7672}
7673
7674/*
7675** Within this division (the proxying locking implementation) the procedures
7676** above this point are all utilities. The lock-related methods of the
7677** proxy-locking sqlite3_io_method object follow.
7678*/
7679
7680
7681/*
7682** This routine checks if there is a RESERVED lock held on the specified
7683** file by this or any other process. If such a lock is held, set *pResOut
7684** to a non-zero value otherwise *pResOut is set to zero. The return value
7685** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7686*/
7687static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7688 unixFile *pFile = (unixFile*)id;
7689 int rc = proxyTakeConch(pFile);
7690 if( rc==SQLITE_OK ){
7691 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007692 if( pCtx->conchHeld>0 ){
7693 unixFile *proxy = pCtx->lockProxy;
7694 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7695 }else{ /* conchHeld < 0 is lockless */
7696 pResOut=0;
7697 }
drh715ff302008-12-03 22:32:44 +00007698 }
7699 return rc;
7700}
7701
7702/*
drh308c2a52010-05-14 11:30:18 +00007703** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007704** of the following:
7705**
7706** (1) SHARED_LOCK
7707** (2) RESERVED_LOCK
7708** (3) PENDING_LOCK
7709** (4) EXCLUSIVE_LOCK
7710**
7711** Sometimes when requesting one lock state, additional lock states
7712** are inserted in between. The locking might fail on one of the later
7713** transitions leaving the lock state different from what it started but
7714** still short of its goal. The following chart shows the allowed
7715** transitions and the inserted intermediate states:
7716**
7717** UNLOCKED -> SHARED
7718** SHARED -> RESERVED
7719** SHARED -> (PENDING) -> EXCLUSIVE
7720** RESERVED -> (PENDING) -> EXCLUSIVE
7721** PENDING -> EXCLUSIVE
7722**
7723** This routine will only increase a lock. Use the sqlite3OsUnlock()
7724** routine to lower a locking level.
7725*/
drh308c2a52010-05-14 11:30:18 +00007726static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007727 unixFile *pFile = (unixFile*)id;
7728 int rc = proxyTakeConch(pFile);
7729 if( rc==SQLITE_OK ){
7730 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007731 if( pCtx->conchHeld>0 ){
7732 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007733 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7734 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007735 }else{
7736 /* conchHeld < 0 is lockless */
7737 }
drh715ff302008-12-03 22:32:44 +00007738 }
7739 return rc;
7740}
7741
7742
7743/*
drh308c2a52010-05-14 11:30:18 +00007744** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007745** must be either NO_LOCK or SHARED_LOCK.
7746**
7747** If the locking level of the file descriptor is already at or below
7748** the requested locking level, this routine is a no-op.
7749*/
drh308c2a52010-05-14 11:30:18 +00007750static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007751 unixFile *pFile = (unixFile*)id;
7752 int rc = proxyTakeConch(pFile);
7753 if( rc==SQLITE_OK ){
7754 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007755 if( pCtx->conchHeld>0 ){
7756 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007757 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7758 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007759 }else{
7760 /* conchHeld < 0 is lockless */
7761 }
drh715ff302008-12-03 22:32:44 +00007762 }
7763 return rc;
7764}
7765
7766/*
7767** Close a file that uses proxy locks.
7768*/
7769static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007770 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007771 unixFile *pFile = (unixFile*)id;
7772 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7773 unixFile *lockProxy = pCtx->lockProxy;
7774 unixFile *conchFile = pCtx->conchFile;
7775 int rc = SQLITE_OK;
7776
7777 if( lockProxy ){
7778 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7779 if( rc ) return rc;
7780 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7781 if( rc ) return rc;
7782 sqlite3_free(lockProxy);
7783 pCtx->lockProxy = 0;
7784 }
7785 if( conchFile ){
7786 if( pCtx->conchHeld ){
7787 rc = proxyReleaseConch(pFile);
7788 if( rc ) return rc;
7789 }
7790 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7791 if( rc ) return rc;
7792 sqlite3_free(conchFile);
7793 }
drhd56b1212010-08-11 06:14:15 +00007794 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007795 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007796 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007797 /* restore the original locking context and pMethod then close it */
7798 pFile->lockingContext = pCtx->oldLockingContext;
7799 pFile->pMethod = pCtx->pOldMethod;
7800 sqlite3_free(pCtx);
7801 return pFile->pMethod->xClose(id);
7802 }
7803 return SQLITE_OK;
7804}
7805
7806
7807
drhd2cb50b2009-01-09 21:41:17 +00007808#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007809/*
7810** The proxy locking style is intended for use with AFP filesystems.
7811** And since AFP is only supported on MacOSX, the proxy locking is also
7812** restricted to MacOSX.
7813**
7814**
7815******************* End of the proxy lock implementation **********************
7816******************************************************************************/
7817
drh734c9862008-11-28 15:37:20 +00007818/*
danielk1977e339d652008-06-28 11:23:00 +00007819** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007820**
7821** This routine registers all VFS implementations for unix-like operating
7822** systems. This routine, and the sqlite3_os_end() routine that follows,
7823** should be the only routines in this file that are visible from other
7824** files.
drh6b9d6dd2008-12-03 19:34:47 +00007825**
7826** This routine is called once during SQLite initialization and by a
7827** single thread. The memory allocation and mutex subsystems have not
7828** necessarily been initialized when this routine is called, and so they
7829** should not be used.
drh153c62c2007-08-24 03:51:33 +00007830*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007831int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007832 /*
7833 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007834 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7835 ** to the "finder" function. (pAppData is a pointer to a pointer because
7836 ** silly C90 rules prohibit a void* from being cast to a function pointer
7837 ** and so we have to go through the intermediate pointer to avoid problems
7838 ** when compiling with -pedantic-errors on GCC.)
7839 **
7840 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007841 ** finder-function. The finder-function returns a pointer to the
7842 ** sqlite_io_methods object that implements the desired locking
7843 ** behaviors. See the division above that contains the IOMETHODS
7844 ** macro for addition information on finder-functions.
7845 **
7846 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7847 ** object. But the "autolockIoFinder" available on MacOSX does a little
7848 ** more than that; it looks at the filesystem type that hosts the
7849 ** database file and tries to choose an locking method appropriate for
7850 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007851 */
drh7708e972008-11-29 00:56:52 +00007852 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007853 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007854 sizeof(unixFile), /* szOsFile */ \
7855 MAX_PATHNAME, /* mxPathname */ \
7856 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007857 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007858 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007859 unixOpen, /* xOpen */ \
7860 unixDelete, /* xDelete */ \
7861 unixAccess, /* xAccess */ \
7862 unixFullPathname, /* xFullPathname */ \
7863 unixDlOpen, /* xDlOpen */ \
7864 unixDlError, /* xDlError */ \
7865 unixDlSym, /* xDlSym */ \
7866 unixDlClose, /* xDlClose */ \
7867 unixRandomness, /* xRandomness */ \
7868 unixSleep, /* xSleep */ \
7869 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007870 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007871 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007872 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007873 unixGetSystemCall, /* xGetSystemCall */ \
7874 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007875 }
7876
drh6b9d6dd2008-12-03 19:34:47 +00007877 /*
7878 ** All default VFSes for unix are contained in the following array.
7879 **
7880 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7881 ** by the SQLite core when the VFS is registered. So the following
7882 ** array cannot be const.
7883 */
danielk1977e339d652008-06-28 11:23:00 +00007884 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007885#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007886 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007887#elif OS_VXWORKS
7888 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007889#else
7890 UNIXVFS("unix", posixIoFinder ),
7891#endif
7892 UNIXVFS("unix-none", nolockIoFinder ),
7893 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007894 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007895#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007896 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007897#endif
drhe89b2912015-03-03 20:42:01 +00007898#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007899 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007900#endif
drhe89b2912015-03-03 20:42:01 +00007901#if SQLITE_ENABLE_LOCKING_STYLE
7902 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007903#endif
drhd2cb50b2009-01-09 21:41:17 +00007904#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007905 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007906 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007907 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007908#endif
drh153c62c2007-08-24 03:51:33 +00007909 };
drh6b9d6dd2008-12-03 19:34:47 +00007910 unsigned int i; /* Loop counter */
7911
drh2aa5a002011-04-13 13:42:25 +00007912 /* Double-check that the aSyscall[] array has been constructed
7913 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007914 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007915
drh6b9d6dd2008-12-03 19:34:47 +00007916 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007917 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007918 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007919 }
drh56115892018-02-05 16:39:12 +00007920 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007921 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007922}
danielk1977e339d652008-06-28 11:23:00 +00007923
7924/*
drh6b9d6dd2008-12-03 19:34:47 +00007925** Shutdown the operating system interface.
7926**
7927** Some operating systems might need to do some cleanup in this routine,
7928** to release dynamically allocated objects. But not on unix.
7929** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007930*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007931int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007932 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007933 return SQLITE_OK;
7934}
drhdce8bdb2007-08-16 13:01:44 +00007935
danielk197729bafea2008-06-26 10:41:19 +00007936#endif /* SQLITE_OS_UNIX */