blob: a4dd2f906c3db62feef30d44f04b4b7185204ac7 [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){
1568 int rc = osFcntl(h,F_SETLK,pLock);
drhfd725632018-03-26 20:43:05 +00001569 while( rc<0 && pFile->iBusyTimeout>0 ){
drhf0119b22018-03-26 17:40:53 +00001570 /* On systems that support some kind of blocking file lock with a timeout,
1571 ** make appropriate changes here to invoke that blocking file lock. On
1572 ** generic posix, however, there is no such API. So we simply try the
1573 ** lock once every millisecond until either the timeout expires, or until
1574 ** the lock is obtained. */
drhfd725632018-03-26 20:43:05 +00001575 usleep(1000);
1576 rc = osFcntl(h,F_SETLK,pLock);
1577 pFile->iBusyTimeout--;
drhf0119b22018-03-26 17:40:53 +00001578 }
1579 return rc;
1580}
1581#endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
1582
1583
1584/*
drha7e61d82011-03-12 17:02:57 +00001585** Attempt to set a system-lock on the file pFile. The lock is
1586** described by pLock.
1587**
drh77197112011-03-15 19:08:48 +00001588** If the pFile was opened read/write from unix-excl, then the only lock
1589** ever obtained is an exclusive lock, and it is obtained exactly once
drha7e61d82011-03-12 17:02:57 +00001590** the first time any lock is attempted. All subsequent system locking
1591** operations become no-ops. Locking operations still happen internally,
1592** in order to coordinate access between separate database connections
1593** within this process, but all of that is handled in memory and the
1594** operating system does not participate.
drh77197112011-03-15 19:08:48 +00001595**
1596** This function is a pass-through to fcntl(F_SETLK) if pFile is using
1597** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
1598** and is read-only.
dan661d71a2011-03-30 19:08:03 +00001599**
1600** Zero is returned if the call completes successfully, or -1 if a call
1601** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
drha7e61d82011-03-12 17:02:57 +00001602*/
1603static int unixFileLock(unixFile *pFile, struct flock *pLock){
1604 int rc;
drh3cb93392011-03-12 18:10:44 +00001605 unixInodeInfo *pInode = pFile->pInode;
drh3cb93392011-03-12 18:10:44 +00001606 assert( pInode!=0 );
drhda6dc242018-07-23 21:10:37 +00001607 assert( sqlite3_mutex_held(pInode->pLockMutex) );
drh50358ad2015-12-02 01:04:33 +00001608 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
drh3cb93392011-03-12 18:10:44 +00001609 if( pInode->bProcessLock==0 ){
drha7e61d82011-03-12 17:02:57 +00001610 struct flock lock;
drh3cb93392011-03-12 18:10:44 +00001611 assert( pInode->nLock==0 );
drha7e61d82011-03-12 17:02:57 +00001612 lock.l_whence = SEEK_SET;
1613 lock.l_start = SHARED_FIRST;
1614 lock.l_len = SHARED_SIZE;
1615 lock.l_type = F_WRLCK;
drhf0119b22018-03-26 17:40:53 +00001616 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
drha7e61d82011-03-12 17:02:57 +00001617 if( rc<0 ) return rc;
drh3cb93392011-03-12 18:10:44 +00001618 pInode->bProcessLock = 1;
1619 pInode->nLock++;
drha7e61d82011-03-12 17:02:57 +00001620 }else{
1621 rc = 0;
1622 }
1623 }else{
drhf0119b22018-03-26 17:40:53 +00001624 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
drha7e61d82011-03-12 17:02:57 +00001625 }
1626 return rc;
1627}
1628
1629/*
drh308c2a52010-05-14 11:30:18 +00001630** Lock the file with the lock specified by parameter eFileLock - one
danielk19779a1d0ab2004-06-01 14:09:28 +00001631** of the following:
1632**
drh2ac3ee92004-06-07 16:27:46 +00001633** (1) SHARED_LOCK
1634** (2) RESERVED_LOCK
1635** (3) PENDING_LOCK
1636** (4) EXCLUSIVE_LOCK
1637**
drhb3e04342004-06-08 00:47:47 +00001638** Sometimes when requesting one lock state, additional lock states
1639** are inserted in between. The locking might fail on one of the later
1640** transitions leaving the lock state different from what it started but
1641** still short of its goal. The following chart shows the allowed
1642** transitions and the inserted intermediate states:
1643**
1644** UNLOCKED -> SHARED
1645** SHARED -> RESERVED
1646** SHARED -> (PENDING) -> EXCLUSIVE
1647** RESERVED -> (PENDING) -> EXCLUSIVE
1648** PENDING -> EXCLUSIVE
drh2ac3ee92004-06-07 16:27:46 +00001649**
drha6abd042004-06-09 17:37:22 +00001650** This routine will only increase a lock. Use the sqlite3OsUnlock()
1651** routine to lower a locking level.
danielk19779a1d0ab2004-06-01 14:09:28 +00001652*/
drh308c2a52010-05-14 11:30:18 +00001653static int unixLock(sqlite3_file *id, int eFileLock){
danielk1977f42f25c2004-06-25 07:21:28 +00001654 /* The following describes the implementation of the various locks and
1655 ** lock transitions in terms of the POSIX advisory shared and exclusive
1656 ** lock primitives (called read-locks and write-locks below, to avoid
1657 ** confusion with SQLite lock names). The algorithms are complicated
drhf878e6e2016-04-07 13:45:20 +00001658 ** slightly in order to be compatible with Windows95 systems simultaneously
danielk1977f42f25c2004-06-25 07:21:28 +00001659 ** accessing the same database file, in case that is ever required.
1660 **
1661 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1662 ** byte', each single bytes at well known offsets, and the 'shared byte
1663 ** range', a range of 510 bytes at a well known offset.
1664 **
1665 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
drhf878e6e2016-04-07 13:45:20 +00001666 ** byte'. If this is successful, 'shared byte range' is read-locked
1667 ** and the lock on the 'pending byte' released. (Legacy note: When
1668 ** SQLite was first developed, Windows95 systems were still very common,
1669 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
1670 ** single randomly selected by from the 'shared byte range' is locked.
1671 ** Windows95 is now pretty much extinct, but this work-around for the
1672 ** lack of shared-locks on Windows95 lives on, for backwards
1673 ** compatibility.)
danielk1977f42f25c2004-06-25 07:21:28 +00001674 **
danielk197790ba3bd2004-06-25 08:32:25 +00001675 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
1676 ** A RESERVED lock is implemented by grabbing a write-lock on the
1677 ** 'reserved byte'.
danielk1977f42f25c2004-06-25 07:21:28 +00001678 **
1679 ** A process may only obtain a PENDING lock after it has obtained a
danielk197790ba3bd2004-06-25 08:32:25 +00001680 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
1681 ** on the 'pending byte'. This ensures that no new SHARED locks can be
1682 ** obtained, but existing SHARED locks are allowed to persist. A process
1683 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
1684 ** This property is used by the algorithm for rolling back a journal file
1685 ** after a crash.
danielk1977f42f25c2004-06-25 07:21:28 +00001686 **
danielk197790ba3bd2004-06-25 08:32:25 +00001687 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
1688 ** implemented by obtaining a write-lock on the entire 'shared byte
1689 ** range'. Since all other locks require a read-lock on one of the bytes
1690 ** within this range, this ensures that no other locks are held on the
1691 ** database.
danielk1977f42f25c2004-06-25 07:21:28 +00001692 */
danielk19779a1d0ab2004-06-01 14:09:28 +00001693 int rc = SQLITE_OK;
drh054889e2005-11-30 03:20:31 +00001694 unixFile *pFile = (unixFile*)id;
drhb07028f2011-10-14 21:49:18 +00001695 unixInodeInfo *pInode;
danielk19779a1d0ab2004-06-01 14:09:28 +00001696 struct flock lock;
drh383d30f2010-02-26 13:07:37 +00001697 int tErrno = 0;
danielk19779a1d0ab2004-06-01 14:09:28 +00001698
drh054889e2005-11-30 03:20:31 +00001699 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001700 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1701 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh91eb93c2015-03-03 19:56:20 +00001702 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001703 osGetpid(0)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001704
1705 /* If there is already a lock of this type or more restrictive on the
danielk1977ad94b582007-08-20 06:44:22 +00001706 ** unixFile, do nothing. Don't use the end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00001707 ** unixEnterMutex() hasn't been called yet.
danielk19779a1d0ab2004-06-01 14:09:28 +00001708 */
drh308c2a52010-05-14 11:30:18 +00001709 if( pFile->eFileLock>=eFileLock ){
1710 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1711 azFileLock(eFileLock)));
danielk19779a1d0ab2004-06-01 14:09:28 +00001712 return SQLITE_OK;
1713 }
1714
drh0c2694b2009-09-03 16:23:44 +00001715 /* Make sure the locking sequence is correct.
1716 ** (1) We never move from unlocked to anything higher than shared lock.
1717 ** (2) SQLite never explicitly requests a pendig lock.
1718 ** (3) A shared lock is always held when a reserve lock is requested.
drh2ac3ee92004-06-07 16:27:46 +00001719 */
drh308c2a52010-05-14 11:30:18 +00001720 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1721 assert( eFileLock!=PENDING_LOCK );
1722 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drh2ac3ee92004-06-07 16:27:46 +00001723
drh8af6c222010-05-14 12:43:01 +00001724 /* This mutex is needed because pFile->pInode is shared across threads
drhb3e04342004-06-08 00:47:47 +00001725 */
drh8af6c222010-05-14 12:43:01 +00001726 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001727 sqlite3_mutex_enter(pInode->pLockMutex);
drh029b44b2006-01-15 00:13:15 +00001728
danielk1977ad94b582007-08-20 06:44:22 +00001729 /* If some thread using this PID has a lock via a different unixFile*
danielk19779a1d0ab2004-06-01 14:09:28 +00001730 ** handle that precludes the requested lock, return BUSY.
1731 */
drh8af6c222010-05-14 12:43:01 +00001732 if( (pFile->eFileLock!=pInode->eFileLock &&
1733 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
danielk19779a1d0ab2004-06-01 14:09:28 +00001734 ){
1735 rc = SQLITE_BUSY;
1736 goto end_lock;
1737 }
1738
1739 /* If a SHARED lock is requested, and some thread using this PID already
1740 ** has a SHARED or RESERVED lock, then increment reference counts and
1741 ** return SQLITE_OK.
1742 */
drh308c2a52010-05-14 11:30:18 +00001743 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00001744 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00001745 assert( eFileLock==SHARED_LOCK );
1746 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00001747 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00001748 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001749 pInode->nShared++;
1750 pInode->nLock++;
danielk19779a1d0ab2004-06-01 14:09:28 +00001751 goto end_lock;
1752 }
1753
danielk19779a1d0ab2004-06-01 14:09:28 +00001754
drh3cde3bb2004-06-12 02:17:14 +00001755 /* A PENDING lock is needed before acquiring a SHARED lock and before
1756 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1757 ** be released.
danielk19779a1d0ab2004-06-01 14:09:28 +00001758 */
drh0c2694b2009-09-03 16:23:44 +00001759 lock.l_len = 1L;
1760 lock.l_whence = SEEK_SET;
drh308c2a52010-05-14 11:30:18 +00001761 if( eFileLock==SHARED_LOCK
1762 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh3cde3bb2004-06-12 02:17:14 +00001763 ){
drh308c2a52010-05-14 11:30:18 +00001764 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
drh2ac3ee92004-06-07 16:27:46 +00001765 lock.l_start = PENDING_BYTE;
dan661d71a2011-03-30 19:08:03 +00001766 if( unixFileLock(pFile, &lock) ){
drh0c2694b2009-09-03 16:23:44 +00001767 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001768 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001769 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001770 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001771 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001772 goto end_lock;
1773 }
drh3cde3bb2004-06-12 02:17:14 +00001774 }
1775
1776
1777 /* If control gets to this point, then actually go ahead and make
1778 ** operating system calls for the specified lock.
1779 */
drh308c2a52010-05-14 11:30:18 +00001780 if( eFileLock==SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001781 assert( pInode->nShared==0 );
1782 assert( pInode->eFileLock==0 );
dan661d71a2011-03-30 19:08:03 +00001783 assert( rc==SQLITE_OK );
danielk19779a1d0ab2004-06-01 14:09:28 +00001784
drh2ac3ee92004-06-07 16:27:46 +00001785 /* Now get the read-lock */
drh7ed97b92010-01-20 13:07:21 +00001786 lock.l_start = SHARED_FIRST;
1787 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001788 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001789 tErrno = errno;
dan661d71a2011-03-30 19:08:03 +00001790 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drh7ed97b92010-01-20 13:07:21 +00001791 }
dan661d71a2011-03-30 19:08:03 +00001792
drh2ac3ee92004-06-07 16:27:46 +00001793 /* Drop the temporary PENDING lock */
1794 lock.l_start = PENDING_BYTE;
1795 lock.l_len = 1L;
danielk19779a1d0ab2004-06-01 14:09:28 +00001796 lock.l_type = F_UNLCK;
dan661d71a2011-03-30 19:08:03 +00001797 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
1798 /* This could happen with a network mount */
1799 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001800 rc = SQLITE_IOERR_UNLOCK;
drh2b4b5962005-06-15 17:47:55 +00001801 }
dan661d71a2011-03-30 19:08:03 +00001802
1803 if( rc ){
1804 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001805 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001806 }
dan661d71a2011-03-30 19:08:03 +00001807 goto end_lock;
drhbbd42a62004-05-22 17:41:58 +00001808 }else{
drh308c2a52010-05-14 11:30:18 +00001809 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00001810 pInode->nLock++;
1811 pInode->nShared = 1;
drhbbd42a62004-05-22 17:41:58 +00001812 }
drh8af6c222010-05-14 12:43:01 +00001813 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh3cde3bb2004-06-12 02:17:14 +00001814 /* We are trying for an exclusive lock but another thread in this
1815 ** same process is still holding a shared lock. */
1816 rc = SQLITE_BUSY;
drhbbd42a62004-05-22 17:41:58 +00001817 }else{
drh3cde3bb2004-06-12 02:17:14 +00001818 /* The request was for a RESERVED or EXCLUSIVE lock. It is
danielk19779a1d0ab2004-06-01 14:09:28 +00001819 ** assumed that there is a SHARED or greater lock on the file
1820 ** already.
1821 */
drh308c2a52010-05-14 11:30:18 +00001822 assert( 0!=pFile->eFileLock );
danielk19779a1d0ab2004-06-01 14:09:28 +00001823 lock.l_type = F_WRLCK;
dan661d71a2011-03-30 19:08:03 +00001824
1825 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
1826 if( eFileLock==RESERVED_LOCK ){
1827 lock.l_start = RESERVED_BYTE;
1828 lock.l_len = 1L;
1829 }else{
1830 lock.l_start = SHARED_FIRST;
1831 lock.l_len = SHARED_SIZE;
danielk19779a1d0ab2004-06-01 14:09:28 +00001832 }
dan661d71a2011-03-30 19:08:03 +00001833
1834 if( unixFileLock(pFile, &lock) ){
drh7ed97b92010-01-20 13:07:21 +00001835 tErrno = errno;
aswift5b1a2562008-08-22 00:22:35 +00001836 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
dan661d71a2011-03-30 19:08:03 +00001837 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00001838 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00001839 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001840 }
drhbbd42a62004-05-22 17:41:58 +00001841 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001842
drh8f941bc2009-01-14 23:03:40 +00001843
drhd3d8c042012-05-29 17:02:40 +00001844#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001845 /* Set up the transaction-counter change checking flags when
1846 ** transitioning from a SHARED to a RESERVED lock. The change
1847 ** from SHARED to RESERVED marks the beginning of a normal
1848 ** write operation (not a hot journal rollback).
1849 */
1850 if( rc==SQLITE_OK
drh308c2a52010-05-14 11:30:18 +00001851 && pFile->eFileLock<=SHARED_LOCK
1852 && eFileLock==RESERVED_LOCK
drh8f941bc2009-01-14 23:03:40 +00001853 ){
1854 pFile->transCntrChng = 0;
1855 pFile->dbUpdate = 0;
1856 pFile->inNormalWrite = 1;
1857 }
1858#endif
1859
1860
danielk1977ecb2a962004-06-02 06:30:16 +00001861 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00001862 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00001863 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00001864 }else if( eFileLock==EXCLUSIVE_LOCK ){
1865 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00001866 pInode->eFileLock = PENDING_LOCK;
danielk1977ecb2a962004-06-02 06:30:16 +00001867 }
danielk19779a1d0ab2004-06-01 14:09:28 +00001868
1869end_lock:
drhda6dc242018-07-23 21:10:37 +00001870 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00001871 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1872 rc==SQLITE_OK ? "ok" : "failed"));
drhbbd42a62004-05-22 17:41:58 +00001873 return rc;
1874}
1875
1876/*
dan08da86a2009-08-21 17:18:03 +00001877** Add the file descriptor used by file handle pFile to the corresponding
dane946c392009-08-22 11:39:46 +00001878** pUnused list.
dan08da86a2009-08-21 17:18:03 +00001879*/
1880static void setPendingFd(unixFile *pFile){
drhd91c68f2010-05-14 14:52:25 +00001881 unixInodeInfo *pInode = pFile->pInode;
drhc68886b2017-08-18 16:09:52 +00001882 UnixUnusedFd *p = pFile->pPreallocatedUnused;
drhef52b362018-08-13 22:50:34 +00001883 assert( unixFileMutexHeld(pFile) );
drh8af6c222010-05-14 12:43:01 +00001884 p->pNext = pInode->pUnused;
1885 pInode->pUnused = p;
dane946c392009-08-22 11:39:46 +00001886 pFile->h = -1;
drhc68886b2017-08-18 16:09:52 +00001887 pFile->pPreallocatedUnused = 0;
dan08da86a2009-08-21 17:18:03 +00001888}
1889
1890/*
drh308c2a52010-05-14 11:30:18 +00001891** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drha6abd042004-06-09 17:37:22 +00001892** must be either NO_LOCK or SHARED_LOCK.
1893**
1894** If the locking level of the file descriptor is already at or below
1895** the requested locking level, this routine is a no-op.
drh7ed97b92010-01-20 13:07:21 +00001896**
1897** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1898** the byte range is divided into 2 parts and the first part is unlocked then
1899** set to a read lock, then the other part is simply unlocked. This works
1900** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1901** remove the write lock on a region when a read lock is set.
drhbbd42a62004-05-22 17:41:58 +00001902*/
drha7e61d82011-03-12 17:02:57 +00001903static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
drh7ed97b92010-01-20 13:07:21 +00001904 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00001905 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00001906 struct flock lock;
1907 int rc = SQLITE_OK;
drha6abd042004-06-09 17:37:22 +00001908
drh054889e2005-11-30 03:20:31 +00001909 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00001910 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00001911 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00001912 osGetpid(0)));
drha6abd042004-06-09 17:37:22 +00001913
drh308c2a52010-05-14 11:30:18 +00001914 assert( eFileLock<=SHARED_LOCK );
1915 if( pFile->eFileLock<=eFileLock ){
drha6abd042004-06-09 17:37:22 +00001916 return SQLITE_OK;
1917 }
drh8af6c222010-05-14 12:43:01 +00001918 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00001919 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00001920 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00001921 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00001922 assert( pInode->eFileLock==pFile->eFileLock );
drh8f941bc2009-01-14 23:03:40 +00001923
drhd3d8c042012-05-29 17:02:40 +00001924#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00001925 /* When reducing a lock such that other processes can start
1926 ** reading the database file again, make sure that the
1927 ** transaction counter was updated if any part of the database
1928 ** file changed. If the transaction counter is not updated,
1929 ** other connections to the same file might not realize that
1930 ** the file has changed and hence might not know to flush their
1931 ** cache. The use of a stale cache can lead to database corruption.
1932 */
drh8f941bc2009-01-14 23:03:40 +00001933 pFile->inNormalWrite = 0;
1934#endif
1935
drh7ed97b92010-01-20 13:07:21 +00001936 /* downgrading to a shared lock on NFS involves clearing the write lock
1937 ** before establishing the readlock - to avoid a race condition we downgrade
1938 ** the lock in 2 blocks, so that part of the range will be covered by a
1939 ** write lock until the rest is covered by a read lock:
1940 ** 1: [WWWWW]
1941 ** 2: [....W]
1942 ** 3: [RRRRW]
1943 ** 4: [RRRR.]
1944 */
drh308c2a52010-05-14 11:30:18 +00001945 if( eFileLock==SHARED_LOCK ){
drh30f776f2011-02-25 03:25:07 +00001946#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
drh87e79ae2011-03-08 13:06:41 +00001947 (void)handleNFSUnlock;
drh30f776f2011-02-25 03:25:07 +00001948 assert( handleNFSUnlock==0 );
1949#endif
1950#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00001951 if( handleNFSUnlock ){
drha712b4b2015-02-19 16:12:04 +00001952 int tErrno; /* Error code from system call errors */
drh7ed97b92010-01-20 13:07:21 +00001953 off_t divSize = SHARED_SIZE - 1;
1954
1955 lock.l_type = F_UNLCK;
1956 lock.l_whence = SEEK_SET;
1957 lock.l_start = SHARED_FIRST;
1958 lock.l_len = divSize;
dan211fb082011-04-01 09:04:36 +00001959 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001960 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001961 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001962 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001963 goto end_unlock;
aswift5b1a2562008-08-22 00:22:35 +00001964 }
drh7ed97b92010-01-20 13:07:21 +00001965 lock.l_type = F_RDLCK;
1966 lock.l_whence = SEEK_SET;
1967 lock.l_start = SHARED_FIRST;
1968 lock.l_len = divSize;
drha7e61d82011-03-12 17:02:57 +00001969 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001970 tErrno = errno;
drh7ed97b92010-01-20 13:07:21 +00001971 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1972 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00001973 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001974 }
1975 goto end_unlock;
1976 }
1977 lock.l_type = F_UNLCK;
1978 lock.l_whence = SEEK_SET;
1979 lock.l_start = SHARED_FIRST+divSize;
1980 lock.l_len = SHARED_SIZE-divSize;
drha7e61d82011-03-12 17:02:57 +00001981 if( unixFileLock(pFile, &lock)==(-1) ){
drhc05a9a82010-03-04 16:12:34 +00001982 tErrno = errno;
danea83bc62011-04-01 11:56:32 +00001983 rc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00001984 storeLastErrno(pFile, tErrno);
drh7ed97b92010-01-20 13:07:21 +00001985 goto end_unlock;
1986 }
drh30f776f2011-02-25 03:25:07 +00001987 }else
1988#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
1989 {
drh7ed97b92010-01-20 13:07:21 +00001990 lock.l_type = F_RDLCK;
1991 lock.l_whence = SEEK_SET;
1992 lock.l_start = SHARED_FIRST;
1993 lock.l_len = SHARED_SIZE;
dan661d71a2011-03-30 19:08:03 +00001994 if( unixFileLock(pFile, &lock) ){
danea83bc62011-04-01 11:56:32 +00001995 /* In theory, the call to unixFileLock() cannot fail because another
1996 ** process is holding an incompatible lock. If it does, this
1997 ** indicates that the other process is not following the locking
1998 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
1999 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
2000 ** an assert to fail). */
2001 rc = SQLITE_IOERR_RDLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002002 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00002003 goto end_unlock;
2004 }
drh9c105bb2004-10-02 20:38:28 +00002005 }
2006 }
drhbbd42a62004-05-22 17:41:58 +00002007 lock.l_type = F_UNLCK;
2008 lock.l_whence = SEEK_SET;
drha6abd042004-06-09 17:37:22 +00002009 lock.l_start = PENDING_BYTE;
2010 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
dan661d71a2011-03-30 19:08:03 +00002011 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002012 pInode->eFileLock = SHARED_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002013 }else{
danea83bc62011-04-01 11:56:32 +00002014 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002015 storeLastErrno(pFile, errno);
drhcd731cf2009-03-28 23:23:02 +00002016 goto end_unlock;
drh2b4b5962005-06-15 17:47:55 +00002017 }
drhbbd42a62004-05-22 17:41:58 +00002018 }
drh308c2a52010-05-14 11:30:18 +00002019 if( eFileLock==NO_LOCK ){
drha6abd042004-06-09 17:37:22 +00002020 /* Decrement the shared lock counter. Release the lock using an
2021 ** OS call only when all threads in this same process have released
2022 ** the lock.
2023 */
drh8af6c222010-05-14 12:43:01 +00002024 pInode->nShared--;
2025 if( pInode->nShared==0 ){
drha6abd042004-06-09 17:37:22 +00002026 lock.l_type = F_UNLCK;
2027 lock.l_whence = SEEK_SET;
2028 lock.l_start = lock.l_len = 0L;
dan661d71a2011-03-30 19:08:03 +00002029 if( unixFileLock(pFile, &lock)==0 ){
drh8af6c222010-05-14 12:43:01 +00002030 pInode->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002031 }else{
danea83bc62011-04-01 11:56:32 +00002032 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002033 storeLastErrno(pFile, errno);
drh8af6c222010-05-14 12:43:01 +00002034 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00002035 pFile->eFileLock = NO_LOCK;
drh2b4b5962005-06-15 17:47:55 +00002036 }
drha6abd042004-06-09 17:37:22 +00002037 }
2038
drhbbd42a62004-05-22 17:41:58 +00002039 /* Decrement the count of locks against this same file. When the
2040 ** count reaches zero, close any other file descriptors whose close
2041 ** was deferred because of outstanding locks.
2042 */
drh8af6c222010-05-14 12:43:01 +00002043 pInode->nLock--;
2044 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00002045 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbbd42a62004-05-22 17:41:58 +00002046 }
drhf2f105d2012-08-20 15:53:54 +00002047
aswift5b1a2562008-08-22 00:22:35 +00002048end_unlock:
drhda6dc242018-07-23 21:10:37 +00002049 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00002050 if( rc==SQLITE_OK ){
2051 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00002052 }
drh9c105bb2004-10-02 20:38:28 +00002053 return rc;
drhbbd42a62004-05-22 17:41:58 +00002054}
2055
2056/*
drh308c2a52010-05-14 11:30:18 +00002057** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00002058** must be either NO_LOCK or SHARED_LOCK.
2059**
2060** If the locking level of the file descriptor is already at or below
2061** the requested locking level, this routine is a no-op.
2062*/
drh308c2a52010-05-14 11:30:18 +00002063static int unixUnlock(sqlite3_file *id, int eFileLock){
danf52a4692013-10-31 18:49:58 +00002064#if SQLITE_MAX_MMAP_SIZE>0
dana1afc742013-03-25 13:50:49 +00002065 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
danf52a4692013-10-31 18:49:58 +00002066#endif
drha7e61d82011-03-12 17:02:57 +00002067 return posixUnlock(id, eFileLock, 0);
drh7ed97b92010-01-20 13:07:21 +00002068}
2069
mistachkine98844f2013-08-24 00:59:24 +00002070#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002071static int unixMapfile(unixFile *pFd, i64 nByte);
2072static void unixUnmapfile(unixFile *pFd);
mistachkine98844f2013-08-24 00:59:24 +00002073#endif
danf23da962013-03-23 21:00:41 +00002074
drh7ed97b92010-01-20 13:07:21 +00002075/*
danielk1977e339d652008-06-28 11:23:00 +00002076** This function performs the parts of the "close file" operation
2077** common to all locking schemes. It closes the directory and file
2078** handles, if they are valid, and sets all fields of the unixFile
2079** structure to 0.
drh9b35ea62008-11-29 02:20:26 +00002080**
2081** It is *not* necessary to hold the mutex when this routine is called,
2082** even on VxWorks. A mutex will be acquired on VxWorks by the
2083** vxworksReleaseFileId() routine.
danielk1977e339d652008-06-28 11:23:00 +00002084*/
2085static int closeUnixFile(sqlite3_file *id){
2086 unixFile *pFile = (unixFile*)id;
mistachkine98844f2013-08-24 00:59:24 +00002087#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00002088 unixUnmapfile(pFile);
mistachkine98844f2013-08-24 00:59:24 +00002089#endif
dan661d71a2011-03-30 19:08:03 +00002090 if( pFile->h>=0 ){
2091 robust_close(pFile, pFile->h, __LINE__);
2092 pFile->h = -1;
2093 }
2094#if OS_VXWORKS
2095 if( pFile->pId ){
drhc02a43a2012-01-10 23:18:38 +00002096 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
drh036ac7f2011-08-08 23:18:05 +00002097 osUnlink(pFile->pId->zCanonicalName);
dan661d71a2011-03-30 19:08:03 +00002098 }
2099 vxworksReleaseFileId(pFile->pId);
2100 pFile->pId = 0;
2101 }
2102#endif
drh0bdbc902014-06-16 18:35:06 +00002103#ifdef SQLITE_UNLINK_AFTER_CLOSE
2104 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
2105 osUnlink(pFile->zPath);
2106 sqlite3_free(*(char**)&pFile->zPath);
2107 pFile->zPath = 0;
2108 }
2109#endif
dan661d71a2011-03-30 19:08:03 +00002110 OSTRACE(("CLOSE %-3d\n", pFile->h));
2111 OpenCounter(-1);
drhc68886b2017-08-18 16:09:52 +00002112 sqlite3_free(pFile->pPreallocatedUnused);
dan661d71a2011-03-30 19:08:03 +00002113 memset(pFile, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00002114 return SQLITE_OK;
2115}
2116
2117/*
danielk1977e3026632004-06-22 11:29:02 +00002118** Close a file.
2119*/
danielk197762079062007-08-15 17:08:46 +00002120static int unixClose(sqlite3_file *id){
aswiftaebf4132008-11-21 00:10:35 +00002121 int rc = SQLITE_OK;
dan661d71a2011-03-30 19:08:03 +00002122 unixFile *pFile = (unixFile *)id;
drhef52b362018-08-13 22:50:34 +00002123 unixInodeInfo *pInode = pFile->pInode;
2124
2125 assert( pInode!=0 );
drhfbc7e882013-04-11 01:16:15 +00002126 verifyDbFile(pFile);
dan661d71a2011-03-30 19:08:03 +00002127 unixUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00002128 assert( unixFileMutexNotheld(pFile) );
dan661d71a2011-03-30 19:08:03 +00002129 unixEnterMutex();
2130
2131 /* unixFile.pInode is always valid here. Otherwise, a different close
2132 ** routine (e.g. nolockClose()) would be called instead.
2133 */
2134 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
drhef52b362018-08-13 22:50:34 +00002135 sqlite3_mutex_enter(pInode->pLockMutex);
drh3fcef1a2018-08-16 16:24:24 +00002136 if( pInode->nLock ){
dan661d71a2011-03-30 19:08:03 +00002137 /* If there are outstanding locks, do not actually close the file just
2138 ** yet because that would clear those locks. Instead, add the file
2139 ** descriptor to pInode->pUnused list. It will be automatically closed
2140 ** when the last lock is cleared.
2141 */
2142 setPendingFd(pFile);
danielk1977e3026632004-06-22 11:29:02 +00002143 }
drhef52b362018-08-13 22:50:34 +00002144 sqlite3_mutex_leave(pInode->pLockMutex);
dan661d71a2011-03-30 19:08:03 +00002145 releaseInodeInfo(pFile);
2146 rc = closeUnixFile(id);
2147 unixLeaveMutex();
aswiftaebf4132008-11-21 00:10:35 +00002148 return rc;
danielk1977e3026632004-06-22 11:29:02 +00002149}
2150
drh734c9862008-11-28 15:37:20 +00002151/************** End of the posix advisory lock implementation *****************
2152******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00002153
drh734c9862008-11-28 15:37:20 +00002154/******************************************************************************
2155****************************** No-op Locking **********************************
2156**
2157** Of the various locking implementations available, this is by far the
2158** simplest: locking is ignored. No attempt is made to lock the database
2159** file for reading or writing.
2160**
2161** This locking mode is appropriate for use on read-only databases
2162** (ex: databases that are burned into CD-ROM, for example.) It can
2163** also be used if the application employs some external mechanism to
2164** prevent simultaneous access of the same database by two or more
2165** database connections. But there is a serious risk of database
2166** corruption if this locking mode is used in situations where multiple
2167** database connections are accessing the same database file at the same
2168** time and one or more of those connections are writing.
2169*/
drhbfe66312006-10-03 17:40:40 +00002170
drh734c9862008-11-28 15:37:20 +00002171static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
2172 UNUSED_PARAMETER(NotUsed);
2173 *pResOut = 0;
2174 return SQLITE_OK;
2175}
drh734c9862008-11-28 15:37:20 +00002176static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
2177 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2178 return SQLITE_OK;
2179}
drh734c9862008-11-28 15:37:20 +00002180static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
2181 UNUSED_PARAMETER2(NotUsed, NotUsed2);
2182 return SQLITE_OK;
2183}
2184
2185/*
drh9b35ea62008-11-29 02:20:26 +00002186** Close the file.
drh734c9862008-11-28 15:37:20 +00002187*/
2188static int nolockClose(sqlite3_file *id) {
drh9b35ea62008-11-29 02:20:26 +00002189 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002190}
2191
2192/******************* End of the no-op lock implementation *********************
2193******************************************************************************/
2194
2195/******************************************************************************
2196************************* Begin dot-file Locking ******************************
2197**
mistachkin48864df2013-03-21 21:20:32 +00002198** The dotfile locking implementation uses the existence of separate lock
drh9ef6bc42011-11-04 02:24:02 +00002199** files (really a directory) to control access to the database. This works
2200** on just about every filesystem imaginable. But there are serious downsides:
drh734c9862008-11-28 15:37:20 +00002201**
2202** (1) There is zero concurrency. A single reader blocks all other
2203** connections from reading or writing the database.
2204**
2205** (2) An application crash or power loss can leave stale lock files
2206** sitting around that need to be cleared manually.
2207**
2208** Nevertheless, a dotlock is an appropriate locking mode for use if no
2209** other locking strategy is available.
drh7708e972008-11-29 00:56:52 +00002210**
drh9ef6bc42011-11-04 02:24:02 +00002211** Dotfile locking works by creating a subdirectory in the same directory as
2212** the database and with the same name but with a ".lock" extension added.
mistachkin48864df2013-03-21 21:20:32 +00002213** The existence of a lock directory implies an EXCLUSIVE lock. All other
drh9ef6bc42011-11-04 02:24:02 +00002214** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
drh734c9862008-11-28 15:37:20 +00002215*/
2216
2217/*
2218** The file suffix added to the data base filename in order to create the
drh9ef6bc42011-11-04 02:24:02 +00002219** lock directory.
drh734c9862008-11-28 15:37:20 +00002220*/
2221#define DOTLOCK_SUFFIX ".lock"
2222
drh7708e972008-11-29 00:56:52 +00002223/*
2224** This routine checks if there is a RESERVED lock held on the specified
2225** file by this or any other process. If such a lock is held, set *pResOut
2226** to a non-zero value otherwise *pResOut is set to zero. The return value
2227** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2228**
2229** In dotfile locking, either a lock exists or it does not. So in this
2230** variation of CheckReservedLock(), *pResOut is set to true if any lock
2231** is held on the file and false if the file is unlocked.
2232*/
drh734c9862008-11-28 15:37:20 +00002233static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
2234 int rc = SQLITE_OK;
2235 int reserved = 0;
2236 unixFile *pFile = (unixFile*)id;
2237
2238 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2239
2240 assert( pFile );
drha8de1e12015-11-30 00:05:39 +00002241 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
drh308c2a52010-05-14 11:30:18 +00002242 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002243 *pResOut = reserved;
2244 return rc;
2245}
2246
drh7708e972008-11-29 00:56:52 +00002247/*
drh308c2a52010-05-14 11:30:18 +00002248** Lock the file with the lock specified by parameter eFileLock - one
drh7708e972008-11-29 00:56:52 +00002249** of the following:
2250**
2251** (1) SHARED_LOCK
2252** (2) RESERVED_LOCK
2253** (3) PENDING_LOCK
2254** (4) EXCLUSIVE_LOCK
2255**
2256** Sometimes when requesting one lock state, additional lock states
2257** are inserted in between. The locking might fail on one of the later
2258** transitions leaving the lock state different from what it started but
2259** still short of its goal. The following chart shows the allowed
2260** transitions and the inserted intermediate states:
2261**
2262** UNLOCKED -> SHARED
2263** SHARED -> RESERVED
2264** SHARED -> (PENDING) -> EXCLUSIVE
2265** RESERVED -> (PENDING) -> EXCLUSIVE
2266** PENDING -> EXCLUSIVE
2267**
2268** This routine will only increase a lock. Use the sqlite3OsUnlock()
2269** routine to lower a locking level.
2270**
2271** With dotfile locking, we really only support state (4): EXCLUSIVE.
2272** But we track the other locking levels internally.
2273*/
drh308c2a52010-05-14 11:30:18 +00002274static int dotlockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002275 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00002276 char *zLockFile = (char *)pFile->lockingContext;
drh7708e972008-11-29 00:56:52 +00002277 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002278
drh7708e972008-11-29 00:56:52 +00002279
2280 /* If we have any lock, then the lock file already exists. All we have
2281 ** to do is adjust our internal record of the lock level.
2282 */
drh308c2a52010-05-14 11:30:18 +00002283 if( pFile->eFileLock > NO_LOCK ){
2284 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002285 /* Always update the timestamp on the old file */
drhdbe4b882011-06-20 18:00:17 +00002286#ifdef HAVE_UTIME
2287 utime(zLockFile, NULL);
2288#else
drh734c9862008-11-28 15:37:20 +00002289 utimes(zLockFile, NULL);
2290#endif
drh7708e972008-11-29 00:56:52 +00002291 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002292 }
2293
2294 /* grab an exclusive lock */
drh9ef6bc42011-11-04 02:24:02 +00002295 rc = osMkdir(zLockFile, 0777);
2296 if( rc<0 ){
2297 /* failed to open/create the lock directory */
drh734c9862008-11-28 15:37:20 +00002298 int tErrno = errno;
2299 if( EEXIST == tErrno ){
2300 rc = SQLITE_BUSY;
2301 } else {
2302 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
drha8de1e12015-11-30 00:05:39 +00002303 if( rc!=SQLITE_BUSY ){
drh4bf66fd2015-02-19 02:43:02 +00002304 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002305 }
2306 }
drh7708e972008-11-29 00:56:52 +00002307 return rc;
drh734c9862008-11-28 15:37:20 +00002308 }
drh734c9862008-11-28 15:37:20 +00002309
2310 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002311 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002312 return rc;
2313}
2314
drh7708e972008-11-29 00:56:52 +00002315/*
drh308c2a52010-05-14 11:30:18 +00002316** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7708e972008-11-29 00:56:52 +00002317** must be either NO_LOCK or SHARED_LOCK.
2318**
2319** If the locking level of the file descriptor is already at or below
2320** the requested locking level, this routine is a no-op.
2321**
2322** When the locking level reaches NO_LOCK, delete the lock file.
2323*/
drh308c2a52010-05-14 11:30:18 +00002324static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002325 unixFile *pFile = (unixFile*)id;
2326 char *zLockFile = (char *)pFile->lockingContext;
drh9ef6bc42011-11-04 02:24:02 +00002327 int rc;
drh734c9862008-11-28 15:37:20 +00002328
2329 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002330 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002331 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002332 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002333
2334 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002335 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002336 return SQLITE_OK;
2337 }
drh7708e972008-11-29 00:56:52 +00002338
2339 /* To downgrade to shared, simply update our internal notion of the
2340 ** lock state. No need to mess with the file on disk.
2341 */
drh308c2a52010-05-14 11:30:18 +00002342 if( eFileLock==SHARED_LOCK ){
2343 pFile->eFileLock = SHARED_LOCK;
drh734c9862008-11-28 15:37:20 +00002344 return SQLITE_OK;
2345 }
2346
drh7708e972008-11-29 00:56:52 +00002347 /* To fully unlock the database, delete the lock file */
drh308c2a52010-05-14 11:30:18 +00002348 assert( eFileLock==NO_LOCK );
drh9ef6bc42011-11-04 02:24:02 +00002349 rc = osRmdir(zLockFile);
drh9ef6bc42011-11-04 02:24:02 +00002350 if( rc<0 ){
drh0d588bb2009-06-17 13:09:38 +00002351 int tErrno = errno;
drha8de1e12015-11-30 00:05:39 +00002352 if( tErrno==ENOENT ){
2353 rc = SQLITE_OK;
2354 }else{
danea83bc62011-04-01 11:56:32 +00002355 rc = SQLITE_IOERR_UNLOCK;
drh4bf66fd2015-02-19 02:43:02 +00002356 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002357 }
2358 return rc;
2359 }
drh308c2a52010-05-14 11:30:18 +00002360 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002361 return SQLITE_OK;
2362}
2363
2364/*
drh9b35ea62008-11-29 02:20:26 +00002365** Close a file. Make sure the lock has been released before closing.
drh734c9862008-11-28 15:37:20 +00002366*/
2367static int dotlockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002368 unixFile *pFile = (unixFile*)id;
2369 assert( id!=0 );
2370 dotlockUnlock(id, NO_LOCK);
2371 sqlite3_free(pFile->lockingContext);
2372 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002373}
2374/****************** End of the dot-file lock implementation *******************
2375******************************************************************************/
2376
2377/******************************************************************************
2378************************** Begin flock Locking ********************************
2379**
2380** Use the flock() system call to do file locking.
2381**
drh6b9d6dd2008-12-03 19:34:47 +00002382** flock() locking is like dot-file locking in that the various
2383** fine-grain locking levels supported by SQLite are collapsed into
2384** a single exclusive lock. In other words, SHARED, RESERVED, and
2385** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
2386** still works when you do this, but concurrency is reduced since
2387** only a single process can be reading the database at a time.
2388**
drhe89b2912015-03-03 20:42:01 +00002389** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
drh734c9862008-11-28 15:37:20 +00002390*/
drhe89b2912015-03-03 20:42:01 +00002391#if SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002392
drh6b9d6dd2008-12-03 19:34:47 +00002393/*
drhff812312011-02-23 13:33:46 +00002394** Retry flock() calls that fail with EINTR
2395*/
2396#ifdef EINTR
2397static int robust_flock(int fd, int op){
2398 int rc;
2399 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
2400 return rc;
2401}
2402#else
drh5c819272011-02-23 14:00:12 +00002403# define robust_flock(a,b) flock(a,b)
drhff812312011-02-23 13:33:46 +00002404#endif
2405
2406
2407/*
drh6b9d6dd2008-12-03 19:34:47 +00002408** This routine checks if there is a RESERVED lock held on the specified
2409** file by this or any other process. If such a lock is held, set *pResOut
2410** to a non-zero value otherwise *pResOut is set to zero. The return value
2411** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2412*/
drh734c9862008-11-28 15:37:20 +00002413static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
2414 int rc = SQLITE_OK;
2415 int reserved = 0;
2416 unixFile *pFile = (unixFile*)id;
2417
2418 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2419
2420 assert( pFile );
2421
2422 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002423 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002424 reserved = 1;
2425 }
2426
2427 /* Otherwise see if some other process holds it. */
2428 if( !reserved ){
2429 /* attempt to get the lock */
drhff812312011-02-23 13:33:46 +00002430 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
drh734c9862008-11-28 15:37:20 +00002431 if( !lrc ){
2432 /* got the lock, unlock it */
drhff812312011-02-23 13:33:46 +00002433 lrc = robust_flock(pFile->h, LOCK_UN);
drh734c9862008-11-28 15:37:20 +00002434 if ( lrc ) {
2435 int tErrno = errno;
2436 /* unlock failed with an error */
danea83bc62011-04-01 11:56:32 +00002437 lrc = SQLITE_IOERR_UNLOCK;
drha8de1e12015-11-30 00:05:39 +00002438 storeLastErrno(pFile, tErrno);
2439 rc = lrc;
drh734c9862008-11-28 15:37:20 +00002440 }
2441 } else {
2442 int tErrno = errno;
2443 reserved = 1;
2444 /* someone else might have it reserved */
2445 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2446 if( IS_LOCK_ERROR(lrc) ){
drh4bf66fd2015-02-19 02:43:02 +00002447 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002448 rc = lrc;
2449 }
2450 }
2451 }
drh308c2a52010-05-14 11:30:18 +00002452 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002453
2454#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002455 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002456 rc = SQLITE_OK;
2457 reserved=1;
2458 }
2459#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2460 *pResOut = reserved;
2461 return rc;
2462}
2463
drh6b9d6dd2008-12-03 19:34:47 +00002464/*
drh308c2a52010-05-14 11:30:18 +00002465** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002466** of the following:
2467**
2468** (1) SHARED_LOCK
2469** (2) RESERVED_LOCK
2470** (3) PENDING_LOCK
2471** (4) EXCLUSIVE_LOCK
2472**
2473** Sometimes when requesting one lock state, additional lock states
2474** are inserted in between. The locking might fail on one of the later
2475** transitions leaving the lock state different from what it started but
2476** still short of its goal. The following chart shows the allowed
2477** transitions and the inserted intermediate states:
2478**
2479** UNLOCKED -> SHARED
2480** SHARED -> RESERVED
2481** SHARED -> (PENDING) -> EXCLUSIVE
2482** RESERVED -> (PENDING) -> EXCLUSIVE
2483** PENDING -> EXCLUSIVE
2484**
2485** flock() only really support EXCLUSIVE locks. We track intermediate
2486** lock states in the sqlite3_file structure, but all locks SHARED or
2487** above are really EXCLUSIVE locks and exclude all other processes from
2488** access the file.
2489**
2490** This routine will only increase a lock. Use the sqlite3OsUnlock()
2491** routine to lower a locking level.
2492*/
drh308c2a52010-05-14 11:30:18 +00002493static int flockLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002494 int rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002495 unixFile *pFile = (unixFile*)id;
2496
2497 assert( pFile );
2498
2499 /* if we already have a lock, it is exclusive.
2500 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002501 if (pFile->eFileLock > NO_LOCK) {
2502 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002503 return SQLITE_OK;
2504 }
2505
2506 /* grab an exclusive lock */
2507
drhff812312011-02-23 13:33:46 +00002508 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
drh734c9862008-11-28 15:37:20 +00002509 int tErrno = errno;
2510 /* didn't get, must be busy */
2511 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2512 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002513 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002514 }
2515 } else {
2516 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002517 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002518 }
drh308c2a52010-05-14 11:30:18 +00002519 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2520 rc==SQLITE_OK ? "ok" : "failed"));
drh734c9862008-11-28 15:37:20 +00002521#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
drh2e233812017-08-22 15:21:54 +00002522 if( (rc & 0xff) == SQLITE_IOERR ){
drh734c9862008-11-28 15:37:20 +00002523 rc = SQLITE_BUSY;
2524 }
2525#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2526 return rc;
2527}
2528
drh6b9d6dd2008-12-03 19:34:47 +00002529
2530/*
drh308c2a52010-05-14 11:30:18 +00002531** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002532** must be either NO_LOCK or SHARED_LOCK.
2533**
2534** If the locking level of the file descriptor is already at or below
2535** the requested locking level, this routine is a no-op.
2536*/
drh308c2a52010-05-14 11:30:18 +00002537static int flockUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002538 unixFile *pFile = (unixFile*)id;
2539
2540 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002541 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002542 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002543 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002544
2545 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002546 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002547 return SQLITE_OK;
2548 }
2549
2550 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002551 if (eFileLock==SHARED_LOCK) {
2552 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002553 return SQLITE_OK;
2554 }
2555
2556 /* no, really, unlock. */
danea83bc62011-04-01 11:56:32 +00002557 if( robust_flock(pFile->h, LOCK_UN) ){
drh734c9862008-11-28 15:37:20 +00002558#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
danea83bc62011-04-01 11:56:32 +00002559 return SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00002560#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
danea83bc62011-04-01 11:56:32 +00002561 return SQLITE_IOERR_UNLOCK;
2562 }else{
drh308c2a52010-05-14 11:30:18 +00002563 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002564 return SQLITE_OK;
2565 }
2566}
2567
2568/*
2569** Close a file.
2570*/
2571static int flockClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00002572 assert( id!=0 );
2573 flockUnlock(id, NO_LOCK);
2574 return closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002575}
2576
2577#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
2578
2579/******************* End of the flock lock implementation *********************
2580******************************************************************************/
2581
2582/******************************************************************************
2583************************ Begin Named Semaphore Locking ************************
2584**
2585** Named semaphore locking is only supported on VxWorks.
drh6b9d6dd2008-12-03 19:34:47 +00002586**
2587** Semaphore locking is like dot-lock and flock in that it really only
2588** supports EXCLUSIVE locking. Only a single process can read or write
2589** the database file at a time. This reduces potential concurrency, but
2590** makes the lock implementation much easier.
drh734c9862008-11-28 15:37:20 +00002591*/
2592#if OS_VXWORKS
2593
drh6b9d6dd2008-12-03 19:34:47 +00002594/*
2595** This routine checks if there is a RESERVED lock held on the specified
2596** file by this or any other process. If such a lock is held, set *pResOut
2597** to a non-zero value otherwise *pResOut is set to zero. The return value
2598** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2599*/
drh8cd5b252015-03-02 22:06:43 +00002600static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
drh734c9862008-11-28 15:37:20 +00002601 int rc = SQLITE_OK;
2602 int reserved = 0;
2603 unixFile *pFile = (unixFile*)id;
2604
2605 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2606
2607 assert( pFile );
2608
2609 /* Check if a thread in this process holds such a lock */
drh308c2a52010-05-14 11:30:18 +00002610 if( pFile->eFileLock>SHARED_LOCK ){
drh734c9862008-11-28 15:37:20 +00002611 reserved = 1;
2612 }
2613
2614 /* Otherwise see if some other process holds it. */
2615 if( !reserved ){
drh8af6c222010-05-14 12:43:01 +00002616 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002617
2618 if( sem_trywait(pSem)==-1 ){
2619 int tErrno = errno;
2620 if( EAGAIN != tErrno ){
2621 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
drh4bf66fd2015-02-19 02:43:02 +00002622 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002623 } else {
2624 /* someone else has the lock when we are in NO_LOCK */
drh308c2a52010-05-14 11:30:18 +00002625 reserved = (pFile->eFileLock < SHARED_LOCK);
drh734c9862008-11-28 15:37:20 +00002626 }
2627 }else{
2628 /* we could have it if we want it */
2629 sem_post(pSem);
2630 }
2631 }
drh308c2a52010-05-14 11:30:18 +00002632 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
drh734c9862008-11-28 15:37:20 +00002633
2634 *pResOut = reserved;
2635 return rc;
2636}
2637
drh6b9d6dd2008-12-03 19:34:47 +00002638/*
drh308c2a52010-05-14 11:30:18 +00002639** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002640** of the following:
2641**
2642** (1) SHARED_LOCK
2643** (2) RESERVED_LOCK
2644** (3) PENDING_LOCK
2645** (4) EXCLUSIVE_LOCK
2646**
2647** Sometimes when requesting one lock state, additional lock states
2648** are inserted in between. The locking might fail on one of the later
2649** transitions leaving the lock state different from what it started but
2650** still short of its goal. The following chart shows the allowed
2651** transitions and the inserted intermediate states:
2652**
2653** UNLOCKED -> SHARED
2654** SHARED -> RESERVED
2655** SHARED -> (PENDING) -> EXCLUSIVE
2656** RESERVED -> (PENDING) -> EXCLUSIVE
2657** PENDING -> EXCLUSIVE
2658**
2659** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2660** lock states in the sqlite3_file structure, but all locks SHARED or
2661** above are really EXCLUSIVE locks and exclude all other processes from
2662** access the file.
2663**
2664** This routine will only increase a lock. Use the sqlite3OsUnlock()
2665** routine to lower a locking level.
2666*/
drh8cd5b252015-03-02 22:06:43 +00002667static int semXLock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002668 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002669 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002670 int rc = SQLITE_OK;
2671
2672 /* if we already have a lock, it is exclusive.
2673 ** Just adjust level and punt on outta here. */
drh308c2a52010-05-14 11:30:18 +00002674 if (pFile->eFileLock > NO_LOCK) {
2675 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002676 rc = SQLITE_OK;
2677 goto sem_end_lock;
2678 }
2679
2680 /* lock semaphore now but bail out when already locked. */
2681 if( sem_trywait(pSem)==-1 ){
2682 rc = SQLITE_BUSY;
2683 goto sem_end_lock;
2684 }
2685
2686 /* got it, set the type and return ok */
drh308c2a52010-05-14 11:30:18 +00002687 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002688
2689 sem_end_lock:
2690 return rc;
2691}
2692
drh6b9d6dd2008-12-03 19:34:47 +00002693/*
drh308c2a52010-05-14 11:30:18 +00002694** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh6b9d6dd2008-12-03 19:34:47 +00002695** must be either NO_LOCK or SHARED_LOCK.
2696**
2697** If the locking level of the file descriptor is already at or below
2698** the requested locking level, this routine is a no-op.
2699*/
drh8cd5b252015-03-02 22:06:43 +00002700static int semXUnlock(sqlite3_file *id, int eFileLock) {
drh734c9862008-11-28 15:37:20 +00002701 unixFile *pFile = (unixFile*)id;
drh8af6c222010-05-14 12:43:01 +00002702 sem_t *pSem = pFile->pInode->pSem;
drh734c9862008-11-28 15:37:20 +00002703
2704 assert( pFile );
2705 assert( pSem );
drh308c2a52010-05-14 11:30:18 +00002706 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
drh5ac93652015-03-21 20:59:43 +00002707 pFile->eFileLock, osGetpid(0)));
drh308c2a52010-05-14 11:30:18 +00002708 assert( eFileLock<=SHARED_LOCK );
drh734c9862008-11-28 15:37:20 +00002709
2710 /* no-op if possible */
drh308c2a52010-05-14 11:30:18 +00002711 if( pFile->eFileLock==eFileLock ){
drh734c9862008-11-28 15:37:20 +00002712 return SQLITE_OK;
2713 }
2714
2715 /* shared can just be set because we always have an exclusive */
drh308c2a52010-05-14 11:30:18 +00002716 if (eFileLock==SHARED_LOCK) {
2717 pFile->eFileLock = eFileLock;
drh734c9862008-11-28 15:37:20 +00002718 return SQLITE_OK;
2719 }
2720
2721 /* no, really unlock. */
2722 if ( sem_post(pSem)==-1 ) {
2723 int rc, tErrno = errno;
2724 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2725 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002726 storeLastErrno(pFile, tErrno);
drh734c9862008-11-28 15:37:20 +00002727 }
2728 return rc;
2729 }
drh308c2a52010-05-14 11:30:18 +00002730 pFile->eFileLock = NO_LOCK;
drh734c9862008-11-28 15:37:20 +00002731 return SQLITE_OK;
2732}
2733
2734/*
2735 ** Close a file.
drhbfe66312006-10-03 17:40:40 +00002736 */
drh8cd5b252015-03-02 22:06:43 +00002737static int semXClose(sqlite3_file *id) {
drh734c9862008-11-28 15:37:20 +00002738 if( id ){
2739 unixFile *pFile = (unixFile*)id;
drh8cd5b252015-03-02 22:06:43 +00002740 semXUnlock(id, NO_LOCK);
drh734c9862008-11-28 15:37:20 +00002741 assert( pFile );
drh095908e2018-08-13 20:46:18 +00002742 assert( unixFileMutexNotheld(pFile) );
drh734c9862008-11-28 15:37:20 +00002743 unixEnterMutex();
danb0ac3e32010-06-16 10:55:42 +00002744 releaseInodeInfo(pFile);
drh734c9862008-11-28 15:37:20 +00002745 unixLeaveMutex();
chw78a13182009-04-07 05:35:03 +00002746 closeUnixFile(id);
drh734c9862008-11-28 15:37:20 +00002747 }
2748 return SQLITE_OK;
2749}
2750
2751#endif /* OS_VXWORKS */
2752/*
2753** Named semaphore locking is only available on VxWorks.
2754**
2755*************** End of the named semaphore lock implementation ****************
2756******************************************************************************/
2757
2758
2759/******************************************************************************
2760*************************** Begin AFP Locking *********************************
2761**
2762** AFP is the Apple Filing Protocol. AFP is a network filesystem found
2763** on Apple Macintosh computers - both OS9 and OSX.
2764**
2765** Third-party implementations of AFP are available. But this code here
2766** only works on OSX.
2767*/
2768
drhd2cb50b2009-01-09 21:41:17 +00002769#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh734c9862008-11-28 15:37:20 +00002770/*
2771** The afpLockingContext structure contains all afp lock specific state
2772*/
drhbfe66312006-10-03 17:40:40 +00002773typedef struct afpLockingContext afpLockingContext;
2774struct afpLockingContext {
drh7ed97b92010-01-20 13:07:21 +00002775 int reserved;
drh6b9d6dd2008-12-03 19:34:47 +00002776 const char *dbPath; /* Name of the open file */
drhbfe66312006-10-03 17:40:40 +00002777};
2778
2779struct ByteRangeLockPB2
2780{
2781 unsigned long long offset; /* offset to first byte to lock */
2782 unsigned long long length; /* nbr of bytes to lock */
2783 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2784 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2785 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
2786 int fd; /* file desc to assoc this lock with */
2787};
2788
drhfd131da2007-08-07 17:13:03 +00002789#define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
drhbfe66312006-10-03 17:40:40 +00002790
drh6b9d6dd2008-12-03 19:34:47 +00002791/*
2792** This is a utility for setting or clearing a bit-range lock on an
2793** AFP filesystem.
2794**
2795** Return SQLITE_OK on success, SQLITE_BUSY on failure.
2796*/
2797static int afpSetLock(
2798 const char *path, /* Name of the file to be locked or unlocked */
2799 unixFile *pFile, /* Open file descriptor on path */
2800 unsigned long long offset, /* First byte to be locked */
2801 unsigned long long length, /* Number of bytes to lock */
2802 int setLockFlag /* True to set lock. False to clear lock */
danielk1977ad94b582007-08-20 06:44:22 +00002803){
drh6b9d6dd2008-12-03 19:34:47 +00002804 struct ByteRangeLockPB2 pb;
2805 int err;
drhbfe66312006-10-03 17:40:40 +00002806
2807 pb.unLockFlag = setLockFlag ? 0 : 1;
2808 pb.startEndFlag = 0;
2809 pb.offset = offset;
2810 pb.length = length;
aswift5b1a2562008-08-22 00:22:35 +00002811 pb.fd = pFile->h;
aswiftaebf4132008-11-21 00:10:35 +00002812
drh308c2a52010-05-14 11:30:18 +00002813 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
drh734c9862008-11-28 15:37:20 +00002814 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
drh308c2a52010-05-14 11:30:18 +00002815 offset, length));
drhbfe66312006-10-03 17:40:40 +00002816 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2817 if ( err==-1 ) {
aswift5b1a2562008-08-22 00:22:35 +00002818 int rc;
2819 int tErrno = errno;
drh308c2a52010-05-14 11:30:18 +00002820 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2821 path, tErrno, strerror(tErrno)));
aswiftaebf4132008-11-21 00:10:35 +00002822#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2823 rc = SQLITE_BUSY;
2824#else
drh734c9862008-11-28 15:37:20 +00002825 rc = sqliteErrorFromPosixError(tErrno,
2826 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
aswiftaebf4132008-11-21 00:10:35 +00002827#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
aswift5b1a2562008-08-22 00:22:35 +00002828 if( IS_LOCK_ERROR(rc) ){
drh4bf66fd2015-02-19 02:43:02 +00002829 storeLastErrno(pFile, tErrno);
aswift5b1a2562008-08-22 00:22:35 +00002830 }
2831 return rc;
drhbfe66312006-10-03 17:40:40 +00002832 } else {
aswift5b1a2562008-08-22 00:22:35 +00002833 return SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00002834 }
2835}
2836
drh6b9d6dd2008-12-03 19:34:47 +00002837/*
2838** This routine checks if there is a RESERVED lock held on the specified
2839** file by this or any other process. If such a lock is held, set *pResOut
2840** to a non-zero value otherwise *pResOut is set to zero. The return value
2841** is set to SQLITE_OK unless an I/O error occurs during lock checking.
2842*/
danielk1977e339d652008-06-28 11:23:00 +00002843static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
aswift5b1a2562008-08-22 00:22:35 +00002844 int rc = SQLITE_OK;
2845 int reserved = 0;
drhbfe66312006-10-03 17:40:40 +00002846 unixFile *pFile = (unixFile*)id;
drh3d4435b2011-08-26 20:55:50 +00002847 afpLockingContext *context;
drhbfe66312006-10-03 17:40:40 +00002848
aswift5b1a2562008-08-22 00:22:35 +00002849 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2850
2851 assert( pFile );
drh3d4435b2011-08-26 20:55:50 +00002852 context = (afpLockingContext *) pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00002853 if( context->reserved ){
2854 *pResOut = 1;
2855 return SQLITE_OK;
2856 }
drhda6dc242018-07-23 21:10:37 +00002857 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
drhbfe66312006-10-03 17:40:40 +00002858 /* Check if a thread in this process holds such a lock */
drh8af6c222010-05-14 12:43:01 +00002859 if( pFile->pInode->eFileLock>SHARED_LOCK ){
aswift5b1a2562008-08-22 00:22:35 +00002860 reserved = 1;
drhbfe66312006-10-03 17:40:40 +00002861 }
2862
2863 /* Otherwise see if some other process holds it.
2864 */
aswift5b1a2562008-08-22 00:22:35 +00002865 if( !reserved ){
2866 /* lock the RESERVED byte */
drh6b9d6dd2008-12-03 19:34:47 +00002867 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
aswift5b1a2562008-08-22 00:22:35 +00002868 if( SQLITE_OK==lrc ){
drhbfe66312006-10-03 17:40:40 +00002869 /* if we succeeded in taking the reserved lock, unlock it to restore
2870 ** the original state */
drh6b9d6dd2008-12-03 19:34:47 +00002871 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
aswift5b1a2562008-08-22 00:22:35 +00002872 } else {
2873 /* if we failed to get the lock then someone else must have it */
2874 reserved = 1;
2875 }
2876 if( IS_LOCK_ERROR(lrc) ){
2877 rc=lrc;
drhbfe66312006-10-03 17:40:40 +00002878 }
2879 }
drhbfe66312006-10-03 17:40:40 +00002880
drhda6dc242018-07-23 21:10:37 +00002881 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00002882 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
aswift5b1a2562008-08-22 00:22:35 +00002883
2884 *pResOut = reserved;
2885 return rc;
drhbfe66312006-10-03 17:40:40 +00002886}
2887
drh6b9d6dd2008-12-03 19:34:47 +00002888/*
drh308c2a52010-05-14 11:30:18 +00002889** Lock the file with the lock specified by parameter eFileLock - one
drh6b9d6dd2008-12-03 19:34:47 +00002890** of the following:
2891**
2892** (1) SHARED_LOCK
2893** (2) RESERVED_LOCK
2894** (3) PENDING_LOCK
2895** (4) EXCLUSIVE_LOCK
2896**
2897** Sometimes when requesting one lock state, additional lock states
2898** are inserted in between. The locking might fail on one of the later
2899** transitions leaving the lock state different from what it started but
2900** still short of its goal. The following chart shows the allowed
2901** transitions and the inserted intermediate states:
2902**
2903** UNLOCKED -> SHARED
2904** SHARED -> RESERVED
2905** SHARED -> (PENDING) -> EXCLUSIVE
2906** RESERVED -> (PENDING) -> EXCLUSIVE
2907** PENDING -> EXCLUSIVE
2908**
2909** This routine will only increase a lock. Use the sqlite3OsUnlock()
2910** routine to lower a locking level.
2911*/
drh308c2a52010-05-14 11:30:18 +00002912static int afpLock(sqlite3_file *id, int eFileLock){
drhbfe66312006-10-03 17:40:40 +00002913 int rc = SQLITE_OK;
2914 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00002915 unixInodeInfo *pInode = pFile->pInode;
drhbfe66312006-10-03 17:40:40 +00002916 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
drhbfe66312006-10-03 17:40:40 +00002917
2918 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00002919 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2920 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
drh5ac93652015-03-21 20:59:43 +00002921 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
drh339eb0b2008-03-07 15:34:11 +00002922
drhbfe66312006-10-03 17:40:40 +00002923 /* If there is already a lock of this type or more restrictive on the
drh339eb0b2008-03-07 15:34:11 +00002924 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
drh6c7d5c52008-11-21 20:32:33 +00002925 ** unixEnterMutex() hasn't been called yet.
drh339eb0b2008-03-07 15:34:11 +00002926 */
drh308c2a52010-05-14 11:30:18 +00002927 if( pFile->eFileLock>=eFileLock ){
2928 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2929 azFileLock(eFileLock)));
drhbfe66312006-10-03 17:40:40 +00002930 return SQLITE_OK;
2931 }
2932
2933 /* Make sure the locking sequence is correct
drh7ed97b92010-01-20 13:07:21 +00002934 ** (1) We never move from unlocked to anything higher than shared lock.
2935 ** (2) SQLite never explicitly requests a pendig lock.
2936 ** (3) A shared lock is always held when a reserve lock is requested.
drh339eb0b2008-03-07 15:34:11 +00002937 */
drh308c2a52010-05-14 11:30:18 +00002938 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2939 assert( eFileLock!=PENDING_LOCK );
2940 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
drhbfe66312006-10-03 17:40:40 +00002941
drh8af6c222010-05-14 12:43:01 +00002942 /* This mutex is needed because pFile->pInode is shared across threads
drh339eb0b2008-03-07 15:34:11 +00002943 */
drh8af6c222010-05-14 12:43:01 +00002944 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00002945 sqlite3_mutex_enter(pInode->pLockMutex);
drh7ed97b92010-01-20 13:07:21 +00002946
2947 /* If some thread using this PID has a lock via a different unixFile*
2948 ** handle that precludes the requested lock, return BUSY.
2949 */
drh8af6c222010-05-14 12:43:01 +00002950 if( (pFile->eFileLock!=pInode->eFileLock &&
2951 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
drh7ed97b92010-01-20 13:07:21 +00002952 ){
2953 rc = SQLITE_BUSY;
2954 goto afp_end_lock;
2955 }
2956
2957 /* If a SHARED lock is requested, and some thread using this PID already
2958 ** has a SHARED or RESERVED lock, then increment reference counts and
2959 ** return SQLITE_OK.
2960 */
drh308c2a52010-05-14 11:30:18 +00002961 if( eFileLock==SHARED_LOCK &&
drh8af6c222010-05-14 12:43:01 +00002962 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
drh308c2a52010-05-14 11:30:18 +00002963 assert( eFileLock==SHARED_LOCK );
2964 assert( pFile->eFileLock==0 );
drh8af6c222010-05-14 12:43:01 +00002965 assert( pInode->nShared>0 );
drh308c2a52010-05-14 11:30:18 +00002966 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00002967 pInode->nShared++;
2968 pInode->nLock++;
drh7ed97b92010-01-20 13:07:21 +00002969 goto afp_end_lock;
2970 }
drhbfe66312006-10-03 17:40:40 +00002971
2972 /* A PENDING lock is needed before acquiring a SHARED lock and before
drh339eb0b2008-03-07 15:34:11 +00002973 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2974 ** be released.
2975 */
drh308c2a52010-05-14 11:30:18 +00002976 if( eFileLock==SHARED_LOCK
2977 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
drh339eb0b2008-03-07 15:34:11 +00002978 ){
2979 int failed;
drh6b9d6dd2008-12-03 19:34:47 +00002980 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
drhbfe66312006-10-03 17:40:40 +00002981 if (failed) {
aswift5b1a2562008-08-22 00:22:35 +00002982 rc = failed;
drhbfe66312006-10-03 17:40:40 +00002983 goto afp_end_lock;
2984 }
2985 }
2986
2987 /* If control gets to this point, then actually go ahead and make
drh339eb0b2008-03-07 15:34:11 +00002988 ** operating system calls for the specified lock.
2989 */
drh308c2a52010-05-14 11:30:18 +00002990 if( eFileLock==SHARED_LOCK ){
drh3d4435b2011-08-26 20:55:50 +00002991 int lrc1, lrc2, lrc1Errno = 0;
drh7ed97b92010-01-20 13:07:21 +00002992 long lk, mask;
drhbfe66312006-10-03 17:40:40 +00002993
drh8af6c222010-05-14 12:43:01 +00002994 assert( pInode->nShared==0 );
2995 assert( pInode->eFileLock==0 );
drh7ed97b92010-01-20 13:07:21 +00002996
2997 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
aswift5b1a2562008-08-22 00:22:35 +00002998 /* Now get the read-lock SHARED_LOCK */
drhbfe66312006-10-03 17:40:40 +00002999 /* note that the quality of the randomness doesn't matter that much */
3000 lk = random();
drh8af6c222010-05-14 12:43:01 +00003001 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
drh6b9d6dd2008-12-03 19:34:47 +00003002 lrc1 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003003 SHARED_FIRST+pInode->sharedByte, 1, 1);
aswift5b1a2562008-08-22 00:22:35 +00003004 if( IS_LOCK_ERROR(lrc1) ){
3005 lrc1Errno = pFile->lastErrno;
drhbfe66312006-10-03 17:40:40 +00003006 }
aswift5b1a2562008-08-22 00:22:35 +00003007 /* Drop the temporary PENDING lock */
drh6b9d6dd2008-12-03 19:34:47 +00003008 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
drhbfe66312006-10-03 17:40:40 +00003009
aswift5b1a2562008-08-22 00:22:35 +00003010 if( IS_LOCK_ERROR(lrc1) ) {
drh4bf66fd2015-02-19 02:43:02 +00003011 storeLastErrno(pFile, lrc1Errno);
aswift5b1a2562008-08-22 00:22:35 +00003012 rc = lrc1;
3013 goto afp_end_lock;
3014 } else if( IS_LOCK_ERROR(lrc2) ){
3015 rc = lrc2;
3016 goto afp_end_lock;
3017 } else if( lrc1 != SQLITE_OK ) {
3018 rc = lrc1;
drhbfe66312006-10-03 17:40:40 +00003019 } else {
drh308c2a52010-05-14 11:30:18 +00003020 pFile->eFileLock = SHARED_LOCK;
drh8af6c222010-05-14 12:43:01 +00003021 pInode->nLock++;
3022 pInode->nShared = 1;
drhbfe66312006-10-03 17:40:40 +00003023 }
drh8af6c222010-05-14 12:43:01 +00003024 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00003025 /* We are trying for an exclusive lock but another thread in this
3026 ** same process is still holding a shared lock. */
3027 rc = SQLITE_BUSY;
drhbfe66312006-10-03 17:40:40 +00003028 }else{
3029 /* The request was for a RESERVED or EXCLUSIVE lock. It is
3030 ** assumed that there is a SHARED or greater lock on the file
3031 ** already.
3032 */
3033 int failed = 0;
drh308c2a52010-05-14 11:30:18 +00003034 assert( 0!=pFile->eFileLock );
3035 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003036 /* Acquire a RESERVED lock */
drh6b9d6dd2008-12-03 19:34:47 +00003037 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
drh7ed97b92010-01-20 13:07:21 +00003038 if( !failed ){
3039 context->reserved = 1;
3040 }
drhbfe66312006-10-03 17:40:40 +00003041 }
drh308c2a52010-05-14 11:30:18 +00003042 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
drhbfe66312006-10-03 17:40:40 +00003043 /* Acquire an EXCLUSIVE lock */
3044
3045 /* Remove the shared lock before trying the range. we'll need to
danielk1977e339d652008-06-28 11:23:00 +00003046 ** reestablish the shared lock if we can't get the afpUnlock
drhbfe66312006-10-03 17:40:40 +00003047 */
drh6b9d6dd2008-12-03 19:34:47 +00003048 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
drh8af6c222010-05-14 12:43:01 +00003049 pInode->sharedByte, 1, 0)) ){
aswiftaebf4132008-11-21 00:10:35 +00003050 int failed2 = SQLITE_OK;
drhbfe66312006-10-03 17:40:40 +00003051 /* now attemmpt to get the exclusive lock range */
drh6b9d6dd2008-12-03 19:34:47 +00003052 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
drhbfe66312006-10-03 17:40:40 +00003053 SHARED_SIZE, 1);
drh6b9d6dd2008-12-03 19:34:47 +00003054 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
drh8af6c222010-05-14 12:43:01 +00003055 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
aswiftaebf4132008-11-21 00:10:35 +00003056 /* Can't reestablish the shared lock. Sqlite can't deal, this is
3057 ** a critical I/O error
3058 */
drh2e233812017-08-22 15:21:54 +00003059 rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
aswiftaebf4132008-11-21 00:10:35 +00003060 SQLITE_IOERR_LOCK;
3061 goto afp_end_lock;
3062 }
3063 }else{
aswift5b1a2562008-08-22 00:22:35 +00003064 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003065 }
3066 }
aswift5b1a2562008-08-22 00:22:35 +00003067 if( failed ){
3068 rc = failed;
drhbfe66312006-10-03 17:40:40 +00003069 }
3070 }
3071
3072 if( rc==SQLITE_OK ){
drh308c2a52010-05-14 11:30:18 +00003073 pFile->eFileLock = eFileLock;
drh8af6c222010-05-14 12:43:01 +00003074 pInode->eFileLock = eFileLock;
drh308c2a52010-05-14 11:30:18 +00003075 }else if( eFileLock==EXCLUSIVE_LOCK ){
3076 pFile->eFileLock = PENDING_LOCK;
drh8af6c222010-05-14 12:43:01 +00003077 pInode->eFileLock = PENDING_LOCK;
drhbfe66312006-10-03 17:40:40 +00003078 }
3079
3080afp_end_lock:
drhda6dc242018-07-23 21:10:37 +00003081 sqlite3_mutex_leave(pInode->pLockMutex);
drh308c2a52010-05-14 11:30:18 +00003082 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
3083 rc==SQLITE_OK ? "ok" : "failed"));
drhbfe66312006-10-03 17:40:40 +00003084 return rc;
3085}
3086
3087/*
drh308c2a52010-05-14 11:30:18 +00003088** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh339eb0b2008-03-07 15:34:11 +00003089** must be either NO_LOCK or SHARED_LOCK.
3090**
3091** If the locking level of the file descriptor is already at or below
3092** the requested locking level, this routine is a no-op.
3093*/
drh308c2a52010-05-14 11:30:18 +00003094static int afpUnlock(sqlite3_file *id, int eFileLock) {
drhbfe66312006-10-03 17:40:40 +00003095 int rc = SQLITE_OK;
3096 unixFile *pFile = (unixFile*)id;
drhd91c68f2010-05-14 14:52:25 +00003097 unixInodeInfo *pInode;
drh7ed97b92010-01-20 13:07:21 +00003098 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
3099 int skipShared = 0;
3100#ifdef SQLITE_TEST
3101 int h = pFile->h;
3102#endif
drhbfe66312006-10-03 17:40:40 +00003103
3104 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003105 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
drh8af6c222010-05-14 12:43:01 +00003106 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
drh5ac93652015-03-21 20:59:43 +00003107 osGetpid(0)));
aswift5b1a2562008-08-22 00:22:35 +00003108
drh308c2a52010-05-14 11:30:18 +00003109 assert( eFileLock<=SHARED_LOCK );
3110 if( pFile->eFileLock<=eFileLock ){
drhbfe66312006-10-03 17:40:40 +00003111 return SQLITE_OK;
3112 }
drh8af6c222010-05-14 12:43:01 +00003113 pInode = pFile->pInode;
drhda6dc242018-07-23 21:10:37 +00003114 sqlite3_mutex_enter(pInode->pLockMutex);
drh8af6c222010-05-14 12:43:01 +00003115 assert( pInode->nShared!=0 );
drh308c2a52010-05-14 11:30:18 +00003116 if( pFile->eFileLock>SHARED_LOCK ){
drh8af6c222010-05-14 12:43:01 +00003117 assert( pInode->eFileLock==pFile->eFileLock );
drh7ed97b92010-01-20 13:07:21 +00003118 SimulateIOErrorBenign(1);
3119 SimulateIOError( h=(-1) )
3120 SimulateIOErrorBenign(0);
3121
drhd3d8c042012-05-29 17:02:40 +00003122#ifdef SQLITE_DEBUG
drh7ed97b92010-01-20 13:07:21 +00003123 /* When reducing a lock such that other processes can start
3124 ** reading the database file again, make sure that the
3125 ** transaction counter was updated if any part of the database
3126 ** file changed. If the transaction counter is not updated,
3127 ** other connections to the same file might not realize that
3128 ** the file has changed and hence might not know to flush their
3129 ** cache. The use of a stale cache can lead to database corruption.
3130 */
3131 assert( pFile->inNormalWrite==0
3132 || pFile->dbUpdate==0
3133 || pFile->transCntrChng==1 );
3134 pFile->inNormalWrite = 0;
3135#endif
aswiftaebf4132008-11-21 00:10:35 +00003136
drh308c2a52010-05-14 11:30:18 +00003137 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003138 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
drh8af6c222010-05-14 12:43:01 +00003139 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
aswiftaebf4132008-11-21 00:10:35 +00003140 /* only re-establish the shared lock if necessary */
drh8af6c222010-05-14 12:43:01 +00003141 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
drh7ed97b92010-01-20 13:07:21 +00003142 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
3143 } else {
3144 skipShared = 1;
aswiftaebf4132008-11-21 00:10:35 +00003145 }
3146 }
drh308c2a52010-05-14 11:30:18 +00003147 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
drh7ed97b92010-01-20 13:07:21 +00003148 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
aswiftaebf4132008-11-21 00:10:35 +00003149 }
drh308c2a52010-05-14 11:30:18 +00003150 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
drh7ed97b92010-01-20 13:07:21 +00003151 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
3152 if( !rc ){
3153 context->reserved = 0;
3154 }
aswiftaebf4132008-11-21 00:10:35 +00003155 }
drh8af6c222010-05-14 12:43:01 +00003156 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
3157 pInode->eFileLock = SHARED_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003158 }
aswiftaebf4132008-11-21 00:10:35 +00003159 }
drh308c2a52010-05-14 11:30:18 +00003160 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
drhbfe66312006-10-03 17:40:40 +00003161
drh7ed97b92010-01-20 13:07:21 +00003162 /* Decrement the shared lock counter. Release the lock using an
3163 ** OS call only when all threads in this same process have released
3164 ** the lock.
3165 */
drh8af6c222010-05-14 12:43:01 +00003166 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
3167 pInode->nShared--;
3168 if( pInode->nShared==0 ){
drh7ed97b92010-01-20 13:07:21 +00003169 SimulateIOErrorBenign(1);
3170 SimulateIOError( h=(-1) )
3171 SimulateIOErrorBenign(0);
3172 if( !skipShared ){
3173 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
3174 }
3175 if( !rc ){
drh8af6c222010-05-14 12:43:01 +00003176 pInode->eFileLock = NO_LOCK;
drh308c2a52010-05-14 11:30:18 +00003177 pFile->eFileLock = NO_LOCK;
drh7ed97b92010-01-20 13:07:21 +00003178 }
3179 }
3180 if( rc==SQLITE_OK ){
drh8af6c222010-05-14 12:43:01 +00003181 pInode->nLock--;
3182 assert( pInode->nLock>=0 );
drhef52b362018-08-13 22:50:34 +00003183 if( pInode->nLock==0 ) closePendingFds(pFile);
drhbfe66312006-10-03 17:40:40 +00003184 }
drhbfe66312006-10-03 17:40:40 +00003185 }
drh7ed97b92010-01-20 13:07:21 +00003186
drhda6dc242018-07-23 21:10:37 +00003187 sqlite3_mutex_leave(pInode->pLockMutex);
drh095908e2018-08-13 20:46:18 +00003188 if( rc==SQLITE_OK ){
3189 pFile->eFileLock = eFileLock;
drh095908e2018-08-13 20:46:18 +00003190 }
drhbfe66312006-10-03 17:40:40 +00003191 return rc;
3192}
3193
3194/*
drh339eb0b2008-03-07 15:34:11 +00003195** Close a file & cleanup AFP specific locking context
3196*/
danielk1977e339d652008-06-28 11:23:00 +00003197static int afpClose(sqlite3_file *id) {
drh7ed97b92010-01-20 13:07:21 +00003198 int rc = SQLITE_OK;
drha8de1e12015-11-30 00:05:39 +00003199 unixFile *pFile = (unixFile*)id;
3200 assert( id!=0 );
3201 afpUnlock(id, NO_LOCK);
drh095908e2018-08-13 20:46:18 +00003202 assert( unixFileMutexNotheld(pFile) );
drha8de1e12015-11-30 00:05:39 +00003203 unixEnterMutex();
drhef52b362018-08-13 22:50:34 +00003204 if( pFile->pInode ){
3205 unixInodeInfo *pInode = pFile->pInode;
3206 sqlite3_mutex_enter(pInode->pLockMutex);
drhcb4e4b02018-09-06 19:36:29 +00003207 if( pInode->nLock ){
drhef52b362018-08-13 22:50:34 +00003208 /* If there are outstanding locks, do not actually close the file just
3209 ** yet because that would clear those locks. Instead, add the file
3210 ** descriptor to pInode->aPending. It will be automatically closed when
3211 ** the last lock is cleared.
3212 */
3213 setPendingFd(pFile);
3214 }
3215 sqlite3_mutex_leave(pInode->pLockMutex);
danielk1977e339d652008-06-28 11:23:00 +00003216 }
drha8de1e12015-11-30 00:05:39 +00003217 releaseInodeInfo(pFile);
3218 sqlite3_free(pFile->lockingContext);
3219 rc = closeUnixFile(id);
3220 unixLeaveMutex();
drh7ed97b92010-01-20 13:07:21 +00003221 return rc;
drhbfe66312006-10-03 17:40:40 +00003222}
3223
drhd2cb50b2009-01-09 21:41:17 +00003224#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh734c9862008-11-28 15:37:20 +00003225/*
3226** The code above is the AFP lock implementation. The code is specific
3227** to MacOSX and does not work on other unix platforms. No alternative
3228** is available. If you don't compile for a mac, then the "unix-afp"
3229** VFS is not available.
3230**
3231********************* End of the AFP lock implementation **********************
3232******************************************************************************/
drhbfe66312006-10-03 17:40:40 +00003233
drh7ed97b92010-01-20 13:07:21 +00003234/******************************************************************************
3235*************************** Begin NFS Locking ********************************/
3236
3237#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3238/*
drh308c2a52010-05-14 11:30:18 +00003239 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh7ed97b92010-01-20 13:07:21 +00003240 ** must be either NO_LOCK or SHARED_LOCK.
3241 **
3242 ** If the locking level of the file descriptor is already at or below
3243 ** the requested locking level, this routine is a no-op.
3244 */
drh308c2a52010-05-14 11:30:18 +00003245static int nfsUnlock(sqlite3_file *id, int eFileLock){
drha7e61d82011-03-12 17:02:57 +00003246 return posixUnlock(id, eFileLock, 1);
drh7ed97b92010-01-20 13:07:21 +00003247}
3248
3249#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3250/*
3251** The code above is the NFS lock implementation. The code is specific
3252** to MacOSX and does not work on other unix platforms. No alternative
3253** is available.
3254**
3255********************* End of the NFS lock implementation **********************
3256******************************************************************************/
drh734c9862008-11-28 15:37:20 +00003257
3258/******************************************************************************
3259**************** Non-locking sqlite3_file methods *****************************
3260**
3261** The next division contains implementations for all methods of the
3262** sqlite3_file object other than the locking methods. The locking
3263** methods were defined in divisions above (one locking method per
3264** division). Those methods that are common to all locking modes
3265** are gather together into this division.
3266*/
drhbfe66312006-10-03 17:40:40 +00003267
3268/*
drh734c9862008-11-28 15:37:20 +00003269** Seek to the offset passed as the second argument, then read cnt
3270** bytes into pBuf. Return the number of bytes actually read.
3271**
3272** NB: If you define USE_PREAD or USE_PREAD64, then it might also
3273** be necessary to define _XOPEN_SOURCE to be 500. This varies from
3274** one system to another. Since SQLite does not define USE_PREAD
peter.d.reid60ec9142014-09-06 16:39:46 +00003275** in any form by default, we will not attempt to define _XOPEN_SOURCE.
drh734c9862008-11-28 15:37:20 +00003276** See tickets #2741 and #2681.
3277**
3278** To avoid stomping the errno value on a failed read the lastErrno value
3279** is set before returning.
drh339eb0b2008-03-07 15:34:11 +00003280*/
drh734c9862008-11-28 15:37:20 +00003281static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
3282 int got;
drh58024642011-11-07 18:16:00 +00003283 int prior = 0;
drha46cadc2016-03-04 03:02:06 +00003284#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
3285 i64 newOffset;
3286#endif
drh734c9862008-11-28 15:37:20 +00003287 TIMER_START;
drhc1fd2cf2012-10-01 12:16:26 +00003288 assert( cnt==(cnt&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003289 assert( id->h>2 );
drh58024642011-11-07 18:16:00 +00003290 do{
drh734c9862008-11-28 15:37:20 +00003291#if defined(USE_PREAD)
drh58024642011-11-07 18:16:00 +00003292 got = osPread(id->h, pBuf, cnt, offset);
3293 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003294#elif defined(USE_PREAD64)
drh58024642011-11-07 18:16:00 +00003295 got = osPread64(id->h, pBuf, cnt, offset);
3296 SimulateIOError( got = -1 );
drh734c9862008-11-28 15:37:20 +00003297#else
drha46cadc2016-03-04 03:02:06 +00003298 newOffset = lseek(id->h, offset, SEEK_SET);
3299 SimulateIOError( newOffset = -1 );
3300 if( newOffset<0 ){
3301 storeLastErrno((unixFile*)id, errno);
3302 return -1;
3303 }
3304 got = osRead(id->h, pBuf, cnt);
drh734c9862008-11-28 15:37:20 +00003305#endif
drh58024642011-11-07 18:16:00 +00003306 if( got==cnt ) break;
3307 if( got<0 ){
3308 if( errno==EINTR ){ got = 1; continue; }
3309 prior = 0;
drh4bf66fd2015-02-19 02:43:02 +00003310 storeLastErrno((unixFile*)id, errno);
drh58024642011-11-07 18:16:00 +00003311 break;
3312 }else if( got>0 ){
3313 cnt -= got;
3314 offset += got;
3315 prior += got;
3316 pBuf = (void*)(got + (char*)pBuf);
3317 }
3318 }while( got>0 );
drh734c9862008-11-28 15:37:20 +00003319 TIMER_END;
drh58024642011-11-07 18:16:00 +00003320 OSTRACE(("READ %-3d %5d %7lld %llu\n",
3321 id->h, got+prior, offset-prior, TIMER_ELAPSED));
3322 return got+prior;
drhbfe66312006-10-03 17:40:40 +00003323}
3324
3325/*
drh734c9862008-11-28 15:37:20 +00003326** Read data from a file into a buffer. Return SQLITE_OK if all
3327** bytes were read successfully and SQLITE_IOERR if anything goes
3328** wrong.
drh339eb0b2008-03-07 15:34:11 +00003329*/
drh734c9862008-11-28 15:37:20 +00003330static int unixRead(
3331 sqlite3_file *id,
3332 void *pBuf,
3333 int amt,
3334 sqlite3_int64 offset
3335){
dan08da86a2009-08-21 17:18:03 +00003336 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003337 int got;
3338 assert( id );
drh6cf9d8d2013-05-09 18:12:40 +00003339 assert( offset>=0 );
3340 assert( amt>0 );
drh08c6d442009-02-09 17:34:07 +00003341
dan08da86a2009-08-21 17:18:03 +00003342 /* If this is a database file (not a journal, master-journal or temp
3343 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003344#if 0
drhc68886b2017-08-18 16:09:52 +00003345 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003346 || offset>=PENDING_BYTE+512
3347 || offset+amt<=PENDING_BYTE
3348 );
dan7c246102010-04-12 19:00:29 +00003349#endif
drh08c6d442009-02-09 17:34:07 +00003350
drh9b4c59f2013-04-15 17:03:42 +00003351#if SQLITE_MAX_MMAP_SIZE>0
drh6c569632013-03-26 18:48:11 +00003352 /* Deal with as much of this read request as possible by transfering
3353 ** data from the memory mapping using memcpy(). */
danf23da962013-03-23 21:00:41 +00003354 if( offset<pFile->mmapSize ){
3355 if( offset+amt <= pFile->mmapSize ){
3356 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
3357 return SQLITE_OK;
3358 }else{
3359 int nCopy = pFile->mmapSize - offset;
3360 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
3361 pBuf = &((u8 *)pBuf)[nCopy];
3362 amt -= nCopy;
3363 offset += nCopy;
3364 }
3365 }
drh6e0b6d52013-04-09 16:19:20 +00003366#endif
danf23da962013-03-23 21:00:41 +00003367
dan08da86a2009-08-21 17:18:03 +00003368 got = seekAndRead(pFile, offset, pBuf, amt);
drh734c9862008-11-28 15:37:20 +00003369 if( got==amt ){
3370 return SQLITE_OK;
3371 }else if( got<0 ){
3372 /* lastErrno set by seekAndRead */
3373 return SQLITE_IOERR_READ;
3374 }else{
drh4bf66fd2015-02-19 02:43:02 +00003375 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003376 /* Unread parts of the buffer must be zero-filled */
3377 memset(&((char*)pBuf)[got], 0, amt-got);
3378 return SQLITE_IOERR_SHORT_READ;
3379 }
3380}
3381
3382/*
dan47a2b4a2013-04-26 16:09:29 +00003383** Attempt to seek the file-descriptor passed as the first argument to
3384** absolute offset iOff, then attempt to write nBuf bytes of data from
3385** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
3386** return the actual number of bytes written (which may be less than
3387** nBuf).
3388*/
3389static int seekAndWriteFd(
3390 int fd, /* File descriptor to write to */
3391 i64 iOff, /* File offset to begin writing at */
3392 const void *pBuf, /* Copy data from this buffer to the file */
3393 int nBuf, /* Size of buffer pBuf in bytes */
3394 int *piErrno /* OUT: Error number if error occurs */
3395){
3396 int rc = 0; /* Value returned by system call */
3397
3398 assert( nBuf==(nBuf&0x1ffff) );
drh35a03792013-08-29 23:34:53 +00003399 assert( fd>2 );
drhe1818ec2015-12-01 16:21:35 +00003400 assert( piErrno!=0 );
dan47a2b4a2013-04-26 16:09:29 +00003401 nBuf &= 0x1ffff;
3402 TIMER_START;
3403
3404#if defined(USE_PREAD)
drh2da47d32015-02-21 00:56:05 +00003405 do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
dan47a2b4a2013-04-26 16:09:29 +00003406#elif defined(USE_PREAD64)
drh2da47d32015-02-21 00:56:05 +00003407 do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
dan47a2b4a2013-04-26 16:09:29 +00003408#else
3409 do{
3410 i64 iSeek = lseek(fd, iOff, SEEK_SET);
drhe1818ec2015-12-01 16:21:35 +00003411 SimulateIOError( iSeek = -1 );
3412 if( iSeek<0 ){
3413 rc = -1;
3414 break;
dan47a2b4a2013-04-26 16:09:29 +00003415 }
3416 rc = osWrite(fd, pBuf, nBuf);
3417 }while( rc<0 && errno==EINTR );
3418#endif
3419
3420 TIMER_END;
3421 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
3422
drhe1818ec2015-12-01 16:21:35 +00003423 if( rc<0 ) *piErrno = errno;
dan47a2b4a2013-04-26 16:09:29 +00003424 return rc;
3425}
3426
3427
3428/*
drh734c9862008-11-28 15:37:20 +00003429** Seek to the offset in id->offset then read cnt bytes into pBuf.
3430** Return the number of bytes actually read. Update the offset.
3431**
3432** To avoid stomping the errno value on a failed write the lastErrno value
3433** is set before returning.
3434*/
3435static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
dan47a2b4a2013-04-26 16:09:29 +00003436 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
drh734c9862008-11-28 15:37:20 +00003437}
3438
3439
3440/*
3441** Write data from a buffer into a file. Return SQLITE_OK on success
3442** or some other error code on failure.
3443*/
3444static int unixWrite(
3445 sqlite3_file *id,
3446 const void *pBuf,
3447 int amt,
3448 sqlite3_int64 offset
3449){
dan08da86a2009-08-21 17:18:03 +00003450 unixFile *pFile = (unixFile*)id;
drh734c9862008-11-28 15:37:20 +00003451 int wrote = 0;
3452 assert( id );
3453 assert( amt>0 );
drh8f941bc2009-01-14 23:03:40 +00003454
dan08da86a2009-08-21 17:18:03 +00003455 /* If this is a database file (not a journal, master-journal or temp
3456 ** file), the bytes in the locking range should never be read or written. */
dan7c246102010-04-12 19:00:29 +00003457#if 0
drhc68886b2017-08-18 16:09:52 +00003458 assert( pFile->pPreallocatedUnused==0
dan08da86a2009-08-21 17:18:03 +00003459 || offset>=PENDING_BYTE+512
3460 || offset+amt<=PENDING_BYTE
3461 );
dan7c246102010-04-12 19:00:29 +00003462#endif
drh08c6d442009-02-09 17:34:07 +00003463
drhd3d8c042012-05-29 17:02:40 +00003464#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00003465 /* If we are doing a normal write to a database file (as opposed to
3466 ** doing a hot-journal rollback or a write to some file other than a
3467 ** normal database file) then record the fact that the database
3468 ** has changed. If the transaction counter is modified, record that
3469 ** fact too.
3470 */
dan08da86a2009-08-21 17:18:03 +00003471 if( pFile->inNormalWrite ){
drh8f941bc2009-01-14 23:03:40 +00003472 pFile->dbUpdate = 1; /* The database has been modified */
3473 if( offset<=24 && offset+amt>=27 ){
drha6d90f02009-01-16 23:47:42 +00003474 int rc;
drh8f941bc2009-01-14 23:03:40 +00003475 char oldCntr[4];
3476 SimulateIOErrorBenign(1);
drha6d90f02009-01-16 23:47:42 +00003477 rc = seekAndRead(pFile, 24, oldCntr, 4);
drh8f941bc2009-01-14 23:03:40 +00003478 SimulateIOErrorBenign(0);
drha6d90f02009-01-16 23:47:42 +00003479 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
drh8f941bc2009-01-14 23:03:40 +00003480 pFile->transCntrChng = 1; /* The transaction counter has changed */
3481 }
3482 }
3483 }
3484#endif
3485
danfe33e392015-11-17 20:56:06 +00003486#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00003487 /* Deal with as much of this write request as possible by transfering
3488 ** data from the memory mapping using memcpy(). */
3489 if( offset<pFile->mmapSize ){
3490 if( offset+amt <= pFile->mmapSize ){
3491 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
3492 return SQLITE_OK;
3493 }else{
3494 int nCopy = pFile->mmapSize - offset;
3495 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
3496 pBuf = &((u8 *)pBuf)[nCopy];
3497 amt -= nCopy;
3498 offset += nCopy;
3499 }
3500 }
drh6e0b6d52013-04-09 16:19:20 +00003501#endif
drh02bf8b42015-09-01 23:51:53 +00003502
3503 while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
drh734c9862008-11-28 15:37:20 +00003504 amt -= wrote;
3505 offset += wrote;
3506 pBuf = &((char*)pBuf)[wrote];
3507 }
3508 SimulateIOError(( wrote=(-1), amt=1 ));
3509 SimulateDiskfullError(( wrote=0, amt=1 ));
dan6e09d692010-07-27 18:34:15 +00003510
drh02bf8b42015-09-01 23:51:53 +00003511 if( amt>wrote ){
drha21b83b2011-04-15 12:36:10 +00003512 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
drh734c9862008-11-28 15:37:20 +00003513 /* lastErrno set by seekAndWrite */
3514 return SQLITE_IOERR_WRITE;
3515 }else{
drh4bf66fd2015-02-19 02:43:02 +00003516 storeLastErrno(pFile, 0); /* not a system error */
drh734c9862008-11-28 15:37:20 +00003517 return SQLITE_FULL;
3518 }
3519 }
dan6e09d692010-07-27 18:34:15 +00003520
drh734c9862008-11-28 15:37:20 +00003521 return SQLITE_OK;
3522}
3523
3524#ifdef SQLITE_TEST
3525/*
3526** Count the number of fullsyncs and normal syncs. This is used to test
drh6b9d6dd2008-12-03 19:34:47 +00003527** that syncs and fullsyncs are occurring at the right times.
drh734c9862008-11-28 15:37:20 +00003528*/
3529int sqlite3_sync_count = 0;
3530int sqlite3_fullsync_count = 0;
3531#endif
3532
3533/*
drh89240432009-03-25 01:06:01 +00003534** We do not trust systems to provide a working fdatasync(). Some do.
drh20f8e132011-08-31 21:01:55 +00003535** Others do no. To be safe, we will stick with the (slightly slower)
3536** fsync(). If you know that your system does support fdatasync() correctly,
drhf7a4a1b2015-01-10 18:02:45 +00003537** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003538*/
drhf7a4a1b2015-01-10 18:02:45 +00003539#if !defined(fdatasync) && !HAVE_FDATASYNC
drh734c9862008-11-28 15:37:20 +00003540# define fdatasync fsync
3541#endif
3542
3543/*
3544** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
3545** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
3546** only available on Mac OS X. But that could change.
3547*/
3548#ifdef F_FULLFSYNC
3549# define HAVE_FULLFSYNC 1
3550#else
3551# define HAVE_FULLFSYNC 0
3552#endif
3553
3554
3555/*
3556** The fsync() system call does not work as advertised on many
3557** unix systems. The following procedure is an attempt to make
3558** it work better.
3559**
3560** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
3561** for testing when we want to run through the test suite quickly.
3562** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
3563** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
3564** or power failure will likely corrupt the database file.
drh0b647ff2009-03-21 14:41:04 +00003565**
3566** SQLite sets the dataOnly flag if the size of the file is unchanged.
3567** The idea behind dataOnly is that it should only write the file content
3568** to disk, not the inode. We only set dataOnly if the file size is
3569** unchanged since the file size is part of the inode. However,
3570** Ted Ts'o tells us that fdatasync() will also write the inode if the
3571** file size has changed. The only real difference between fdatasync()
3572** and fsync(), Ted tells us, is that fdatasync() will not flush the
3573** inode if the mtime or owner or other inode attributes have changed.
3574** We only care about the file size, not the other file attributes, so
3575** as far as SQLite is concerned, an fdatasync() is always adequate.
3576** So, we always use fdatasync() if it is available, regardless of
3577** the value of the dataOnly flag.
drh734c9862008-11-28 15:37:20 +00003578*/
3579static int full_fsync(int fd, int fullSync, int dataOnly){
chw97185482008-11-17 08:05:31 +00003580 int rc;
drh734c9862008-11-28 15:37:20 +00003581
3582 /* The following "ifdef/elif/else/" block has the same structure as
3583 ** the one below. It is replicated here solely to avoid cluttering
3584 ** up the real code with the UNUSED_PARAMETER() macros.
3585 */
3586#ifdef SQLITE_NO_SYNC
3587 UNUSED_PARAMETER(fd);
3588 UNUSED_PARAMETER(fullSync);
3589 UNUSED_PARAMETER(dataOnly);
3590#elif HAVE_FULLFSYNC
3591 UNUSED_PARAMETER(dataOnly);
3592#else
3593 UNUSED_PARAMETER(fullSync);
drh0b647ff2009-03-21 14:41:04 +00003594 UNUSED_PARAMETER(dataOnly);
drh734c9862008-11-28 15:37:20 +00003595#endif
3596
3597 /* Record the number of times that we do a normal fsync() and
3598 ** FULLSYNC. This is used during testing to verify that this procedure
3599 ** gets called with the correct arguments.
3600 */
3601#ifdef SQLITE_TEST
3602 if( fullSync ) sqlite3_fullsync_count++;
3603 sqlite3_sync_count++;
3604#endif
3605
3606 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
drh2c8fd122015-12-02 02:33:36 +00003607 ** no-op. But go ahead and call fstat() to validate the file
3608 ** descriptor as we need a method to provoke a failure during
3609 ** coverate testing.
drh734c9862008-11-28 15:37:20 +00003610 */
3611#ifdef SQLITE_NO_SYNC
drh2c8fd122015-12-02 02:33:36 +00003612 {
3613 struct stat buf;
3614 rc = osFstat(fd, &buf);
3615 }
drh734c9862008-11-28 15:37:20 +00003616#elif HAVE_FULLFSYNC
3617 if( fullSync ){
drh99ab3b12011-03-02 15:09:07 +00003618 rc = osFcntl(fd, F_FULLFSYNC, 0);
drh734c9862008-11-28 15:37:20 +00003619 }else{
3620 rc = 1;
3621 }
3622 /* If the FULLFSYNC failed, fall back to attempting an fsync().
drh6b9d6dd2008-12-03 19:34:47 +00003623 ** It shouldn't be possible for fullfsync to fail on the local
3624 ** file system (on OSX), so failure indicates that FULLFSYNC
3625 ** isn't supported for this file system. So, attempt an fsync
3626 ** and (for now) ignore the overhead of a superfluous fcntl call.
3627 ** It'd be better to detect fullfsync support once and avoid
3628 ** the fcntl call every time sync is called.
3629 */
drh734c9862008-11-28 15:37:20 +00003630 if( rc ) rc = fsync(fd);
3631
drh7ed97b92010-01-20 13:07:21 +00003632#elif defined(__APPLE__)
3633 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
3634 ** so currently we default to the macro that redefines fdatasync to fsync
3635 */
3636 rc = fsync(fd);
drh734c9862008-11-28 15:37:20 +00003637#else
drh0b647ff2009-03-21 14:41:04 +00003638 rc = fdatasync(fd);
drhc7288ee2009-01-15 04:30:02 +00003639#if OS_VXWORKS
drh0b647ff2009-03-21 14:41:04 +00003640 if( rc==-1 && errno==ENOTSUP ){
drh734c9862008-11-28 15:37:20 +00003641 rc = fsync(fd);
3642 }
drh0b647ff2009-03-21 14:41:04 +00003643#endif /* OS_VXWORKS */
drh734c9862008-11-28 15:37:20 +00003644#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3645
3646 if( OS_VXWORKS && rc!= -1 ){
3647 rc = 0;
3648 }
chw97185482008-11-17 08:05:31 +00003649 return rc;
drhbfe66312006-10-03 17:40:40 +00003650}
3651
drh734c9862008-11-28 15:37:20 +00003652/*
drh0059eae2011-08-08 23:48:40 +00003653** Open a file descriptor to the directory containing file zFilename.
3654** If successful, *pFd is set to the opened file descriptor and
3655** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
3656** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
3657** value.
3658**
drh90315a22011-08-10 01:52:12 +00003659** The directory file descriptor is used for only one thing - to
3660** fsync() a directory to make sure file creation and deletion events
3661** are flushed to disk. Such fsyncs are not needed on newer
3662** journaling filesystems, but are required on older filesystems.
3663**
3664** This routine can be overridden using the xSetSysCall interface.
3665** The ability to override this routine was added in support of the
3666** chromium sandbox. Opening a directory is a security risk (we are
3667** told) so making it overrideable allows the chromium sandbox to
3668** replace this routine with a harmless no-op. To make this routine
3669** a no-op, replace it with a stub that returns SQLITE_OK but leaves
3670** *pFd set to a negative number.
3671**
drh0059eae2011-08-08 23:48:40 +00003672** If SQLITE_OK is returned, the caller is responsible for closing
3673** the file descriptor *pFd using close().
3674*/
3675static int openDirectory(const char *zFilename, int *pFd){
3676 int ii;
3677 int fd = -1;
3678 char zDirname[MAX_PATHNAME+1];
3679
3680 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
drhdc278512015-12-07 18:18:33 +00003681 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
3682 if( ii>0 ){
drh0059eae2011-08-08 23:48:40 +00003683 zDirname[ii] = '\0';
drhdc278512015-12-07 18:18:33 +00003684 }else{
3685 if( zDirname[0]!='/' ) zDirname[0] = '.';
3686 zDirname[1] = 0;
3687 }
drhc398c652019-11-22 00:42:01 +00003688 fd = robust_open(zDirname, O_RDONLY|O_BINARY|O_NOFOLLOW, 0);
drhdc278512015-12-07 18:18:33 +00003689 if( fd>=0 ){
3690 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
drh0059eae2011-08-08 23:48:40 +00003691 }
3692 *pFd = fd;
drhacb6b282015-11-26 10:37:05 +00003693 if( fd>=0 ) return SQLITE_OK;
3694 return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
drh0059eae2011-08-08 23:48:40 +00003695}
3696
3697/*
drh734c9862008-11-28 15:37:20 +00003698** Make sure all writes to a particular file are committed to disk.
3699**
3700** If dataOnly==0 then both the file itself and its metadata (file
3701** size, access time, etc) are synced. If dataOnly!=0 then only the
3702** file data is synced.
3703**
3704** Under Unix, also make sure that the directory entry for the file
3705** has been created by fsync-ing the directory that contains the file.
3706** If we do not do this and we encounter a power failure, the directory
3707** entry for the journal might not exist after we reboot. The next
3708** SQLite to access the file will not know that the journal exists (because
3709** the directory entry for the journal was never created) and the transaction
3710** will not roll back - possibly leading to database corruption.
3711*/
3712static int unixSync(sqlite3_file *id, int flags){
3713 int rc;
3714 unixFile *pFile = (unixFile*)id;
3715
3716 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
3717 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
3718
3719 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
3720 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3721 || (flags&0x0F)==SQLITE_SYNC_FULL
3722 );
3723
3724 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3725 ** line is to test that doing so does not cause any problems.
3726 */
3727 SimulateDiskfullError( return SQLITE_FULL );
3728
3729 assert( pFile );
drh308c2a52010-05-14 11:30:18 +00003730 OSTRACE(("SYNC %-3d\n", pFile->h));
drh734c9862008-11-28 15:37:20 +00003731 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3732 SimulateIOError( rc=1 );
3733 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003734 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003735 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003736 }
drh0059eae2011-08-08 23:48:40 +00003737
3738 /* Also fsync the directory containing the file if the DIRSYNC flag
mistachkin48864df2013-03-21 21:20:32 +00003739 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
drh90315a22011-08-10 01:52:12 +00003740 ** are unable to fsync a directory, so ignore errors on the fsync.
drh0059eae2011-08-08 23:48:40 +00003741 */
3742 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
3743 int dirfd;
3744 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
drh308c2a52010-05-14 11:30:18 +00003745 HAVE_FULLFSYNC, isFullsync));
drh90315a22011-08-10 01:52:12 +00003746 rc = osOpenDirectory(pFile->zPath, &dirfd);
drhacb6b282015-11-26 10:37:05 +00003747 if( rc==SQLITE_OK ){
drh0059eae2011-08-08 23:48:40 +00003748 full_fsync(dirfd, 0, 0);
3749 robust_close(pFile, dirfd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00003750 }else{
3751 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00003752 rc = SQLITE_OK;
drh734c9862008-11-28 15:37:20 +00003753 }
drh0059eae2011-08-08 23:48:40 +00003754 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
drh734c9862008-11-28 15:37:20 +00003755 }
3756 return rc;
3757}
3758
3759/*
3760** Truncate an open file to a specified size
3761*/
3762static int unixTruncate(sqlite3_file *id, i64 nByte){
dan6e09d692010-07-27 18:34:15 +00003763 unixFile *pFile = (unixFile *)id;
drh734c9862008-11-28 15:37:20 +00003764 int rc;
dan6e09d692010-07-27 18:34:15 +00003765 assert( pFile );
drh734c9862008-11-28 15:37:20 +00003766 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
dan6e09d692010-07-27 18:34:15 +00003767
3768 /* If the user has configured a chunk-size for this file, truncate the
3769 ** file so that it consists of an integer number of chunks (i.e. the
3770 ** actual file size after the operation may be larger than the requested
3771 ** size).
3772 */
drhb8af4b72012-04-05 20:04:39 +00003773 if( pFile->szChunk>0 ){
dan6e09d692010-07-27 18:34:15 +00003774 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
3775 }
3776
dan2ee53412014-09-06 16:49:40 +00003777 rc = robust_ftruncate(pFile->h, nByte);
drh734c9862008-11-28 15:37:20 +00003778 if( rc ){
drh4bf66fd2015-02-19 02:43:02 +00003779 storeLastErrno(pFile, errno);
dane18d4952011-02-21 11:46:24 +00003780 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
drh734c9862008-11-28 15:37:20 +00003781 }else{
drhd3d8c042012-05-29 17:02:40 +00003782#ifdef SQLITE_DEBUG
drh3313b142009-11-06 04:13:18 +00003783 /* If we are doing a normal write to a database file (as opposed to
3784 ** doing a hot-journal rollback or a write to some file other than a
3785 ** normal database file) and we truncate the file to zero length,
3786 ** that effectively updates the change counter. This might happen
3787 ** when restoring a database using the backup API from a zero-length
3788 ** source.
3789 */
dan6e09d692010-07-27 18:34:15 +00003790 if( pFile->inNormalWrite && nByte==0 ){
3791 pFile->transCntrChng = 1;
drh3313b142009-11-06 04:13:18 +00003792 }
danf23da962013-03-23 21:00:41 +00003793#endif
danc0003312013-03-22 17:46:11 +00003794
mistachkine98844f2013-08-24 00:59:24 +00003795#if SQLITE_MAX_MMAP_SIZE>0
danc0003312013-03-22 17:46:11 +00003796 /* If the file was just truncated to a size smaller than the currently
3797 ** mapped region, reduce the effective mapping size as well. SQLite will
3798 ** use read() and write() to access data beyond this point from now on.
3799 */
3800 if( nByte<pFile->mmapSize ){
3801 pFile->mmapSize = nByte;
3802 }
mistachkine98844f2013-08-24 00:59:24 +00003803#endif
drh3313b142009-11-06 04:13:18 +00003804
drh734c9862008-11-28 15:37:20 +00003805 return SQLITE_OK;
3806 }
3807}
3808
3809/*
3810** Determine the current size of a file in bytes
3811*/
3812static int unixFileSize(sqlite3_file *id, i64 *pSize){
3813 int rc;
3814 struct stat buf;
drh3044b512014-06-16 16:41:52 +00003815 assert( id );
3816 rc = osFstat(((unixFile*)id)->h, &buf);
drh734c9862008-11-28 15:37:20 +00003817 SimulateIOError( rc=1 );
3818 if( rc!=0 ){
drh4bf66fd2015-02-19 02:43:02 +00003819 storeLastErrno((unixFile*)id, errno);
drh734c9862008-11-28 15:37:20 +00003820 return SQLITE_IOERR_FSTAT;
3821 }
3822 *pSize = buf.st_size;
3823
drh8af6c222010-05-14 12:43:01 +00003824 /* When opening a zero-size database, the findInodeInfo() procedure
drh734c9862008-11-28 15:37:20 +00003825 ** writes a single byte into that file in order to work around a bug
3826 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3827 ** layers, we need to report this file size as zero even though it is
3828 ** really 1. Ticket #3260.
3829 */
3830 if( *pSize==1 ) *pSize = 0;
3831
3832
3833 return SQLITE_OK;
3834}
3835
drhd2cb50b2009-01-09 21:41:17 +00003836#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00003837/*
3838** Handler for proxy-locking file-control verbs. Defined below in the
3839** proxying locking division.
3840*/
3841static int proxyFileControl(sqlite3_file*,int,void*);
drh947bd802008-12-04 12:34:15 +00003842#endif
drh715ff302008-12-03 22:32:44 +00003843
dan502019c2010-07-28 14:26:17 +00003844/*
3845** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
drh3d4435b2011-08-26 20:55:50 +00003846** file-control operation. Enlarge the database to nBytes in size
3847** (rounded up to the next chunk-size). If the database is already
3848** nBytes or larger, this routine is a no-op.
dan502019c2010-07-28 14:26:17 +00003849*/
3850static int fcntlSizeHint(unixFile *pFile, i64 nByte){
mistachkind589a542011-08-30 01:23:34 +00003851 if( pFile->szChunk>0 ){
dan502019c2010-07-28 14:26:17 +00003852 i64 nSize; /* Required file size */
3853 struct stat buf; /* Used to hold return values of fstat() */
3854
drh4bf66fd2015-02-19 02:43:02 +00003855 if( osFstat(pFile->h, &buf) ){
3856 return SQLITE_IOERR_FSTAT;
3857 }
dan502019c2010-07-28 14:26:17 +00003858
3859 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3860 if( nSize>(i64)buf.st_size ){
dan661d71a2011-03-30 19:08:03 +00003861
dan502019c2010-07-28 14:26:17 +00003862#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
dan661d71a2011-03-30 19:08:03 +00003863 /* The code below is handling the return value of osFallocate()
3864 ** correctly. posix_fallocate() is defined to "returns zero on success,
3865 ** or an error number on failure". See the manpage for details. */
3866 int err;
drhff812312011-02-23 13:33:46 +00003867 do{
dan661d71a2011-03-30 19:08:03 +00003868 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
3869 }while( err==EINTR );
drh789df142018-06-02 14:37:39 +00003870 if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
dan502019c2010-07-28 14:26:17 +00003871#else
dan592bf7f2014-12-30 19:58:31 +00003872 /* If the OS does not have posix_fallocate(), fake it. Write a
3873 ** single byte to the last byte in each block that falls entirely
3874 ** within the extended region. Then, if required, a single byte
3875 ** at offset (nSize-1), to set the size of the file correctly.
3876 ** This is a similar technique to that used by glibc on systems
3877 ** that do not have a real fallocate() call.
dan502019c2010-07-28 14:26:17 +00003878 */
3879 int nBlk = buf.st_blksize; /* File-system block size */
danef3d66c2015-01-06 21:31:47 +00003880 int nWrite = 0; /* Number of bytes written by seekAndWrite */
dan502019c2010-07-28 14:26:17 +00003881 i64 iWrite; /* Next offset to write to */
dan502019c2010-07-28 14:26:17 +00003882
drh053378d2015-12-01 22:09:42 +00003883 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
dan592bf7f2014-12-30 19:58:31 +00003884 assert( iWrite>=buf.st_size );
dan592bf7f2014-12-30 19:58:31 +00003885 assert( ((iWrite+1)%nBlk)==0 );
drh053378d2015-12-01 22:09:42 +00003886 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
3887 if( iWrite>=nSize ) iWrite = nSize - 1;
danef3d66c2015-01-06 21:31:47 +00003888 nWrite = seekAndWrite(pFile, iWrite, "", 1);
dandc5df0f2011-04-06 19:15:45 +00003889 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
dandc5df0f2011-04-06 19:15:45 +00003890 }
dan502019c2010-07-28 14:26:17 +00003891#endif
3892 }
3893 }
3894
mistachkine98844f2013-08-24 00:59:24 +00003895#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00003896 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
danf23da962013-03-23 21:00:41 +00003897 int rc;
3898 if( pFile->szChunk<=0 ){
3899 if( robust_ftruncate(pFile->h, nByte) ){
drh4bf66fd2015-02-19 02:43:02 +00003900 storeLastErrno(pFile, errno);
danf23da962013-03-23 21:00:41 +00003901 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
3902 }
3903 }
3904
3905 rc = unixMapfile(pFile, nByte);
3906 return rc;
3907 }
mistachkine98844f2013-08-24 00:59:24 +00003908#endif
danf23da962013-03-23 21:00:41 +00003909
dan502019c2010-07-28 14:26:17 +00003910 return SQLITE_OK;
3911}
danielk1977ad94b582007-08-20 06:44:22 +00003912
danielk1977e3026632004-06-22 11:29:02 +00003913/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003914** If *pArg is initially negative then this is a query. Set *pArg to
drhf12b3f62011-12-21 14:42:29 +00003915** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
3916**
3917** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
3918*/
3919static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
3920 if( *pArg<0 ){
3921 *pArg = (pFile->ctrlFlags & mask)!=0;
3922 }else if( (*pArg)==0 ){
3923 pFile->ctrlFlags &= ~mask;
3924 }else{
3925 pFile->ctrlFlags |= mask;
3926 }
3927}
3928
drh696b33e2012-12-06 19:01:42 +00003929/* Forward declaration */
3930static int unixGetTempname(int nBuf, char *zBuf);
3931
drhf12b3f62011-12-21 14:42:29 +00003932/*
drh9e33c2c2007-08-31 18:34:59 +00003933** Information and control of an open file handle.
drh18839212005-11-26 03:43:23 +00003934*/
drhcc6bb3e2007-08-31 16:11:35 +00003935static int unixFileControl(sqlite3_file *id, int op, void *pArg){
drhf0b190d2011-07-26 16:03:07 +00003936 unixFile *pFile = (unixFile*)id;
drh9e33c2c2007-08-31 18:34:59 +00003937 switch( op ){
drhd76dba72017-07-22 16:00:34 +00003938#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00003939 case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
3940 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003941 return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003942 }
3943 case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
3944 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
drh344f7632017-07-28 13:18:35 +00003945 return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003946 }
3947 case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
3948 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
drh344f7632017-07-28 13:18:35 +00003949 return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
danefe16972017-07-20 19:49:14 +00003950 }
drhd76dba72017-07-22 16:00:34 +00003951#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00003952
drh9e33c2c2007-08-31 18:34:59 +00003953 case SQLITE_FCNTL_LOCKSTATE: {
drhf0b190d2011-07-26 16:03:07 +00003954 *(int*)pArg = pFile->eFileLock;
drh9e33c2c2007-08-31 18:34:59 +00003955 return SQLITE_OK;
3956 }
drh4bf66fd2015-02-19 02:43:02 +00003957 case SQLITE_FCNTL_LAST_ERRNO: {
drhf0b190d2011-07-26 16:03:07 +00003958 *(int*)pArg = pFile->lastErrno;
drh7708e972008-11-29 00:56:52 +00003959 return SQLITE_OK;
3960 }
dan6e09d692010-07-27 18:34:15 +00003961 case SQLITE_FCNTL_CHUNK_SIZE: {
drhf0b190d2011-07-26 16:03:07 +00003962 pFile->szChunk = *(int *)pArg;
dan502019c2010-07-28 14:26:17 +00003963 return SQLITE_OK;
dan6e09d692010-07-27 18:34:15 +00003964 }
drh9ff27ec2010-05-19 19:26:05 +00003965 case SQLITE_FCNTL_SIZE_HINT: {
danda04ea42011-08-23 05:10:39 +00003966 int rc;
3967 SimulateIOErrorBenign(1);
3968 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
3969 SimulateIOErrorBenign(0);
3970 return rc;
drhf0b190d2011-07-26 16:03:07 +00003971 }
3972 case SQLITE_FCNTL_PERSIST_WAL: {
drhf12b3f62011-12-21 14:42:29 +00003973 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
3974 return SQLITE_OK;
3975 }
drhcb15f352011-12-23 01:04:17 +00003976 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
3977 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
drhf0b190d2011-07-26 16:03:07 +00003978 return SQLITE_OK;
drh9ff27ec2010-05-19 19:26:05 +00003979 }
drhde60fc22011-12-14 17:53:36 +00003980 case SQLITE_FCNTL_VFSNAME: {
3981 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
3982 return SQLITE_OK;
3983 }
drh696b33e2012-12-06 19:01:42 +00003984 case SQLITE_FCNTL_TEMPFILENAME: {
drhf3cdcdc2015-04-29 16:50:28 +00003985 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
drh696b33e2012-12-06 19:01:42 +00003986 if( zTFile ){
3987 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
3988 *(char**)pArg = zTFile;
3989 }
3990 return SQLITE_OK;
3991 }
drhb959a012013-12-07 12:29:22 +00003992 case SQLITE_FCNTL_HAS_MOVED: {
3993 *(int*)pArg = fileHasMoved(pFile);
3994 return SQLITE_OK;
3995 }
drhf0119b22018-03-26 17:40:53 +00003996#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3997 case SQLITE_FCNTL_LOCK_TIMEOUT: {
dan97ccc1b2020-03-27 17:23:17 +00003998 int iOld = pFile->iBusyTimeout;
drhf0119b22018-03-26 17:40:53 +00003999 pFile->iBusyTimeout = *(int*)pArg;
dan97ccc1b2020-03-27 17:23:17 +00004000 *(int*)pArg = iOld;
drhf0119b22018-03-26 17:40:53 +00004001 return SQLITE_OK;
4002 }
4003#endif
mistachkine98844f2013-08-24 00:59:24 +00004004#if SQLITE_MAX_MMAP_SIZE>0
drh9b4c59f2013-04-15 17:03:42 +00004005 case SQLITE_FCNTL_MMAP_SIZE: {
drh34f74902013-04-03 13:09:18 +00004006 i64 newLimit = *(i64*)pArg;
drh34e258c2013-05-23 01:40:53 +00004007 int rc = SQLITE_OK;
drh9b4c59f2013-04-15 17:03:42 +00004008 if( newLimit>sqlite3GlobalConfig.mxMmap ){
4009 newLimit = sqlite3GlobalConfig.mxMmap;
4010 }
dan43c1e622017-08-07 18:13:28 +00004011
4012 /* The value of newLimit may be eventually cast to (size_t) and passed
mistachkine35395a2017-08-07 19:06:54 +00004013 ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
4014 ** 64-bit type. */
dan089df502017-08-07 18:54:10 +00004015 if( newLimit>0 && sizeof(size_t)<8 ){
dan43c1e622017-08-07 18:13:28 +00004016 newLimit = (newLimit & 0x7FFFFFFF);
4017 }
4018
drh9b4c59f2013-04-15 17:03:42 +00004019 *(i64*)pArg = pFile->mmapSizeMax;
drh34e258c2013-05-23 01:40:53 +00004020 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
drh9b4c59f2013-04-15 17:03:42 +00004021 pFile->mmapSizeMax = newLimit;
drh34e258c2013-05-23 01:40:53 +00004022 if( pFile->mmapSize>0 ){
4023 unixUnmapfile(pFile);
4024 rc = unixMapfile(pFile, -1);
4025 }
danbcb8a862013-04-08 15:30:41 +00004026 }
drh34e258c2013-05-23 01:40:53 +00004027 return rc;
danb2d3de32013-03-14 18:34:37 +00004028 }
mistachkine98844f2013-08-24 00:59:24 +00004029#endif
drhd3d8c042012-05-29 17:02:40 +00004030#ifdef SQLITE_DEBUG
drh8f941bc2009-01-14 23:03:40 +00004031 /* The pager calls this method to signal that it has done
4032 ** a rollback and that the database is therefore unchanged and
4033 ** it hence it is OK for the transaction change counter to be
4034 ** unchanged.
4035 */
4036 case SQLITE_FCNTL_DB_UNCHANGED: {
4037 ((unixFile*)id)->dbUpdate = 0;
4038 return SQLITE_OK;
4039 }
4040#endif
drhd2cb50b2009-01-09 21:41:17 +00004041#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh4bf66fd2015-02-19 02:43:02 +00004042 case SQLITE_FCNTL_SET_LOCKPROXYFILE:
4043 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00004044 return proxyFileControl(id,op,pArg);
drh7708e972008-11-29 00:56:52 +00004045 }
drhd2cb50b2009-01-09 21:41:17 +00004046#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
drh9e33c2c2007-08-31 18:34:59 +00004047 }
drh0b52b7d2011-01-26 19:46:22 +00004048 return SQLITE_NOTFOUND;
drh9cbe6352005-11-29 03:13:21 +00004049}
4050
4051/*
danefe16972017-07-20 19:49:14 +00004052** If pFd->sectorSize is non-zero when this function is called, it is a
4053** no-op. Otherwise, the values of pFd->sectorSize and
4054** pFd->deviceCharacteristics are set according to the file-system
4055** characteristics.
danielk1977a3d4c882007-03-23 10:08:38 +00004056**
danefe16972017-07-20 19:49:14 +00004057** There are two versions of this function. One for QNX and one for all
4058** other systems.
danielk1977a3d4c882007-03-23 10:08:38 +00004059*/
danefe16972017-07-20 19:49:14 +00004060#ifndef __QNXNTO__
4061static void setDeviceCharacteristics(unixFile *pFd){
drhd76dba72017-07-22 16:00:34 +00004062 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
danefe16972017-07-20 19:49:14 +00004063 if( pFd->sectorSize==0 ){
drhd76dba72017-07-22 16:00:34 +00004064#if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
danefe16972017-07-20 19:49:14 +00004065 int res;
dan9d709542017-07-21 21:06:24 +00004066 u32 f = 0;
drh537dddf2012-10-26 13:46:24 +00004067
danefe16972017-07-20 19:49:14 +00004068 /* Check for support for F2FS atomic batch writes. */
dan9d709542017-07-21 21:06:24 +00004069 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
4070 if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
dan77b4f522017-07-27 18:34:00 +00004071 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
danefe16972017-07-20 19:49:14 +00004072 }
drhd76dba72017-07-22 16:00:34 +00004073#endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
danefe16972017-07-20 19:49:14 +00004074
4075 /* Set the POWERSAFE_OVERWRITE flag if requested. */
4076 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
4077 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
4078 }
4079
4080 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4081 }
4082}
4083#else
drh537dddf2012-10-26 13:46:24 +00004084#include <sys/dcmd_blk.h>
4085#include <sys/statvfs.h>
danefe16972017-07-20 19:49:14 +00004086static void setDeviceCharacteristics(unixFile *pFile){
drh537dddf2012-10-26 13:46:24 +00004087 if( pFile->sectorSize == 0 ){
4088 struct statvfs fsInfo;
4089
4090 /* Set defaults for non-supported filesystems */
4091 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4092 pFile->deviceCharacteristics = 0;
4093 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
drha9be5082018-01-15 14:32:37 +00004094 return;
drh537dddf2012-10-26 13:46:24 +00004095 }
4096
4097 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
4098 pFile->sectorSize = fsInfo.f_bsize;
4099 pFile->deviceCharacteristics =
4100 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
4101 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4102 ** the write succeeds */
4103 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4104 ** so it is ordered */
4105 0;
4106 }else if( strstr(fsInfo.f_basetype, "etfs") ){
4107 pFile->sectorSize = fsInfo.f_bsize;
4108 pFile->deviceCharacteristics =
4109 /* etfs cluster size writes are atomic */
4110 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
4111 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4112 ** the write succeeds */
4113 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4114 ** so it is ordered */
4115 0;
4116 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
4117 pFile->sectorSize = fsInfo.f_bsize;
4118 pFile->deviceCharacteristics =
4119 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
4120 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4121 ** the write succeeds */
4122 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4123 ** so it is ordered */
4124 0;
4125 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
4126 pFile->sectorSize = fsInfo.f_bsize;
4127 pFile->deviceCharacteristics =
4128 /* full bitset of atomics from max sector size and smaller */
4129 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4130 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4131 ** so it is ordered */
4132 0;
4133 }else if( strstr(fsInfo.f_basetype, "dos") ){
4134 pFile->sectorSize = fsInfo.f_bsize;
4135 pFile->deviceCharacteristics =
4136 /* full bitset of atomics from max sector size and smaller */
4137 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
4138 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
4139 ** so it is ordered */
4140 0;
4141 }else{
4142 pFile->deviceCharacteristics =
4143 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
4144 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
4145 ** the write succeeds */
4146 0;
4147 }
4148 }
4149 /* Last chance verification. If the sector size isn't a multiple of 512
4150 ** then it isn't valid.*/
4151 if( pFile->sectorSize % 512 != 0 ){
4152 pFile->deviceCharacteristics = 0;
4153 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
4154 }
drh537dddf2012-10-26 13:46:24 +00004155}
danefe16972017-07-20 19:49:14 +00004156#endif
4157
4158/*
4159** Return the sector size in bytes of the underlying block device for
4160** the specified file. This is almost always 512 bytes, but may be
4161** larger for some devices.
4162**
4163** SQLite code assumes this function cannot fail. It also assumes that
4164** if two files are created in the same file-system directory (i.e.
4165** a database and its journal file) that the sector size will be the
4166** same for both.
4167*/
4168static int unixSectorSize(sqlite3_file *id){
4169 unixFile *pFd = (unixFile*)id;
4170 setDeviceCharacteristics(pFd);
4171 return pFd->sectorSize;
4172}
danielk1977a3d4c882007-03-23 10:08:38 +00004173
danielk197790949c22007-08-17 16:50:38 +00004174/*
drhf12b3f62011-12-21 14:42:29 +00004175** Return the device characteristics for the file.
4176**
drhcb15f352011-12-23 01:04:17 +00004177** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
peter.d.reid60ec9142014-09-06 16:39:46 +00004178** However, that choice is controversial since technically the underlying
drhcb15f352011-12-23 01:04:17 +00004179** file system does not always provide powersafe overwrites. (In other
4180** words, after a power-loss event, parts of the file that were never
4181** written might end up being altered.) However, non-PSOW behavior is very,
4182** very rare. And asserting PSOW makes a large reduction in the amount
4183** of required I/O for journaling, since a lot of padding is eliminated.
4184** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
4185** available to turn it off and URI query parameter available to turn it off.
danielk197790949c22007-08-17 16:50:38 +00004186*/
drhf12b3f62011-12-21 14:42:29 +00004187static int unixDeviceCharacteristics(sqlite3_file *id){
danefe16972017-07-20 19:49:14 +00004188 unixFile *pFd = (unixFile*)id;
4189 setDeviceCharacteristics(pFd);
4190 return pFd->deviceCharacteristics;
danielk197762079062007-08-15 17:08:46 +00004191}
4192
dan702eec12014-06-23 10:04:58 +00004193#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
drhd9e5c4f2010-05-12 18:01:39 +00004194
dan702eec12014-06-23 10:04:58 +00004195/*
4196** Return the system page size.
4197**
4198** This function should not be called directly by other code in this file.
4199** Instead, it should be called via macro osGetpagesize().
4200*/
4201static int unixGetpagesize(void){
drh8cd5b252015-03-02 22:06:43 +00004202#if OS_VXWORKS
4203 return 1024;
4204#elif defined(_BSD_SOURCE)
dan702eec12014-06-23 10:04:58 +00004205 return getpagesize();
4206#else
4207 return (int)sysconf(_SC_PAGESIZE);
4208#endif
4209}
4210
4211#endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
4212
4213#ifndef SQLITE_OMIT_WAL
drhd9e5c4f2010-05-12 18:01:39 +00004214
4215/*
drhd91c68f2010-05-14 14:52:25 +00004216** Object used to represent an shared memory buffer.
4217**
4218** When multiple threads all reference the same wal-index, each thread
4219** has its own unixShm object, but they all point to a single instance
4220** of this unixShmNode object. In other words, each wal-index is opened
4221** only once per process.
4222**
4223** Each unixShmNode object is connected to a single unixInodeInfo object.
4224** We could coalesce this object into unixInodeInfo, but that would mean
4225** every open file that does not use shared memory (in other words, most
4226** open files) would have to carry around this extra information. So
4227** the unixInodeInfo object contains a pointer to this unixShmNode object
4228** and the unixShmNode object is created only when needed.
drhd9e5c4f2010-05-12 18:01:39 +00004229**
4230** unixMutexHeld() must be true when creating or destroying
4231** this object or while reading or writing the following fields:
4232**
4233** nRef
drhd9e5c4f2010-05-12 18:01:39 +00004234**
4235** The following fields are read-only after the object is created:
4236**
drh8820c8d2018-10-02 19:58:08 +00004237** hShm
drhd9e5c4f2010-05-12 18:01:39 +00004238** zFilename
4239**
drh8820c8d2018-10-02 19:58:08 +00004240** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
drhd9e5c4f2010-05-12 18:01:39 +00004241** unixMutexHeld() is true when reading or writing any other field
4242** in this structure.
drhd9e5c4f2010-05-12 18:01:39 +00004243*/
drhd91c68f2010-05-14 14:52:25 +00004244struct unixShmNode {
4245 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
drh24efa542018-10-02 19:36:40 +00004246 sqlite3_mutex *pShmMutex; /* Mutex to access this object */
drhd9e5c4f2010-05-12 18:01:39 +00004247 char *zFilename; /* Name of the mmapped file */
drh8820c8d2018-10-02 19:58:08 +00004248 int hShm; /* Open file descriptor */
dan18801912010-06-14 14:07:50 +00004249 int szRegion; /* Size of shared-memory regions */
drh66dfec8b2011-06-01 20:01:49 +00004250 u16 nRegion; /* Size of array apRegion */
4251 u8 isReadonly; /* True if read-only */
dan92c02da2017-11-01 20:59:28 +00004252 u8 isUnlocked; /* True if no DMS lock held */
dan18801912010-06-14 14:07:50 +00004253 char **apRegion; /* Array of mapped shared-memory regions */
drhd9e5c4f2010-05-12 18:01:39 +00004254 int nRef; /* Number of unixShm objects pointing to this */
4255 unixShm *pFirst; /* All unixShm objects pointing to this */
drhd9e5c4f2010-05-12 18:01:39 +00004256#ifdef SQLITE_DEBUG
4257 u8 exclMask; /* Mask of exclusive locks held */
4258 u8 sharedMask; /* Mask of shared locks held */
4259 u8 nextShmId; /* Next available unixShm.id value */
4260#endif
4261};
4262
4263/*
drhd9e5c4f2010-05-12 18:01:39 +00004264** Structure used internally by this VFS to record the state of an
4265** open shared memory connection.
4266**
drhd91c68f2010-05-14 14:52:25 +00004267** The following fields are initialized when this object is created and
4268** are read-only thereafter:
drhd9e5c4f2010-05-12 18:01:39 +00004269**
drh24efa542018-10-02 19:36:40 +00004270** unixShm.pShmNode
drhd91c68f2010-05-14 14:52:25 +00004271** unixShm.id
4272**
drh24efa542018-10-02 19:36:40 +00004273** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
4274** be held while accessing any read/write fields.
drhd9e5c4f2010-05-12 18:01:39 +00004275*/
4276struct unixShm {
drhd91c68f2010-05-14 14:52:25 +00004277 unixShmNode *pShmNode; /* The underlying unixShmNode object */
4278 unixShm *pNext; /* Next unixShm with the same unixShmNode */
drh24efa542018-10-02 19:36:40 +00004279 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
drhfd532312011-08-31 18:35:34 +00004280 u8 id; /* Id of this connection within its unixShmNode */
drh73b64e42010-05-30 19:55:15 +00004281 u16 sharedMask; /* Mask of shared locks held */
4282 u16 exclMask; /* Mask of exclusive locks held */
drhd9e5c4f2010-05-12 18:01:39 +00004283};
4284
4285/*
drhd9e5c4f2010-05-12 18:01:39 +00004286** Constants used for locking
4287*/
drhbd9676c2010-06-23 17:58:38 +00004288#define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
drh42224412010-05-31 14:28:25 +00004289#define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
drhd9e5c4f2010-05-12 18:01:39 +00004290
drhd9e5c4f2010-05-12 18:01:39 +00004291/*
drh73b64e42010-05-30 19:55:15 +00004292** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
drhd9e5c4f2010-05-12 18:01:39 +00004293**
4294** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
4295** otherwise.
4296*/
4297static int unixShmSystemLock(
drhbbf76ee2015-03-10 20:22:35 +00004298 unixFile *pFile, /* Open connection to the WAL file */
drhd91c68f2010-05-14 14:52:25 +00004299 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
drh73b64e42010-05-30 19:55:15 +00004300 int ofst, /* First byte of the locking range */
4301 int n /* Number of bytes to lock */
drhd9e5c4f2010-05-12 18:01:39 +00004302){
drhbbf76ee2015-03-10 20:22:35 +00004303 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
4304 struct flock f; /* The posix advisory locking structure */
4305 int rc = SQLITE_OK; /* Result code form fcntl() */
drhd9e5c4f2010-05-12 18:01:39 +00004306
drhd91c68f2010-05-14 14:52:25 +00004307 /* Access to the unixShmNode object is serialized by the caller */
drhbbf76ee2015-03-10 20:22:35 +00004308 pShmNode = pFile->pInode->pShmNode;
drh24efa542018-10-02 19:36:40 +00004309 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
drh9b7e8e12018-10-02 20:16:41 +00004310 assert( pShmNode->nRef>0 || unixMutexHeld() );
drhd9e5c4f2010-05-12 18:01:39 +00004311
dan9181ae92017-10-26 17:05:22 +00004312 /* Shared locks never span more than one byte */
4313 assert( n==1 || lockType!=F_RDLCK );
4314
4315 /* Locks are within range */
4316 assert( n>=1 && n<=SQLITE_SHM_NLOCK );
4317
drh8820c8d2018-10-02 19:58:08 +00004318 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004319 /* Initialize the locking parameters */
drh3cb93392011-03-12 18:10:44 +00004320 f.l_type = lockType;
4321 f.l_whence = SEEK_SET;
4322 f.l_start = ofst;
4323 f.l_len = n;
drh8820c8d2018-10-02 19:58:08 +00004324 rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
drh3cb93392011-03-12 18:10:44 +00004325 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
4326 }
drhd9e5c4f2010-05-12 18:01:39 +00004327
4328 /* Update the global lock state and do debug tracing */
4329#ifdef SQLITE_DEBUG
dan9181ae92017-10-26 17:05:22 +00004330 { u16 mask;
4331 OSTRACE(("SHM-LOCK "));
4332 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
4333 if( rc==SQLITE_OK ){
4334 if( lockType==F_UNLCK ){
4335 OSTRACE(("unlock %d ok", ofst));
4336 pShmNode->exclMask &= ~mask;
4337 pShmNode->sharedMask &= ~mask;
4338 }else if( lockType==F_RDLCK ){
4339 OSTRACE(("read-lock %d ok", ofst));
4340 pShmNode->exclMask &= ~mask;
4341 pShmNode->sharedMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004342 }else{
dan9181ae92017-10-26 17:05:22 +00004343 assert( lockType==F_WRLCK );
4344 OSTRACE(("write-lock %d ok", ofst));
4345 pShmNode->exclMask |= mask;
4346 pShmNode->sharedMask &= ~mask;
drhd9e5c4f2010-05-12 18:01:39 +00004347 }
dan9181ae92017-10-26 17:05:22 +00004348 }else{
4349 if( lockType==F_UNLCK ){
4350 OSTRACE(("unlock %d failed", ofst));
4351 }else if( lockType==F_RDLCK ){
4352 OSTRACE(("read-lock failed"));
4353 }else{
4354 assert( lockType==F_WRLCK );
4355 OSTRACE(("write-lock %d failed", ofst));
4356 }
4357 }
4358 OSTRACE((" - afterwards %03x,%03x\n",
4359 pShmNode->sharedMask, pShmNode->exclMask));
drh73b64e42010-05-30 19:55:15 +00004360 }
drhd9e5c4f2010-05-12 18:01:39 +00004361#endif
4362
4363 return rc;
4364}
4365
dan781e34c2014-03-20 08:59:47 +00004366/*
dan781e34c2014-03-20 08:59:47 +00004367** Return the minimum number of 32KB shm regions that should be mapped at
4368** a time, assuming that each mapping must be an integer multiple of the
4369** current system page-size.
4370**
4371** Usually, this is 1. The exception seems to be systems that are configured
4372** to use 64KB pages - in this case each mapping must cover at least two
4373** shm regions.
4374*/
4375static int unixShmRegionPerMap(void){
4376 int shmsz = 32*1024; /* SHM region size */
danbc760632014-03-20 09:42:09 +00004377 int pgsz = osGetpagesize(); /* System page size */
dan781e34c2014-03-20 08:59:47 +00004378 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
4379 if( pgsz<shmsz ) return 1;
4380 return pgsz/shmsz;
4381}
drhd9e5c4f2010-05-12 18:01:39 +00004382
4383/*
drhd91c68f2010-05-14 14:52:25 +00004384** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
drhd9e5c4f2010-05-12 18:01:39 +00004385**
4386** This is not a VFS shared-memory method; it is a utility function called
4387** by VFS shared-memory methods.
4388*/
drhd91c68f2010-05-14 14:52:25 +00004389static void unixShmPurge(unixFile *pFd){
4390 unixShmNode *p = pFd->pInode->pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004391 assert( unixMutexHeld() );
drhf3b1ed02015-12-02 13:11:03 +00004392 if( p && ALWAYS(p->nRef==0) ){
dan781e34c2014-03-20 08:59:47 +00004393 int nShmPerMap = unixShmRegionPerMap();
dan13a3cb82010-06-11 19:04:21 +00004394 int i;
drhd91c68f2010-05-14 14:52:25 +00004395 assert( p->pInode==pFd->pInode );
drh24efa542018-10-02 19:36:40 +00004396 sqlite3_mutex_free(p->pShmMutex);
dan781e34c2014-03-20 08:59:47 +00004397 for(i=0; i<p->nRegion; i+=nShmPerMap){
drh8820c8d2018-10-02 19:58:08 +00004398 if( p->hShm>=0 ){
drhd1ab8062013-03-25 20:50:25 +00004399 osMunmap(p->apRegion[i], p->szRegion);
drh3cb93392011-03-12 18:10:44 +00004400 }else{
4401 sqlite3_free(p->apRegion[i]);
4402 }
dan13a3cb82010-06-11 19:04:21 +00004403 }
dan18801912010-06-14 14:07:50 +00004404 sqlite3_free(p->apRegion);
drh8820c8d2018-10-02 19:58:08 +00004405 if( p->hShm>=0 ){
4406 robust_close(pFd, p->hShm, __LINE__);
4407 p->hShm = -1;
drh0e9365c2011-03-02 02:08:13 +00004408 }
drhd91c68f2010-05-14 14:52:25 +00004409 p->pInode->pShmNode = 0;
4410 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004411 }
4412}
4413
4414/*
dan92c02da2017-11-01 20:59:28 +00004415** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
4416** take it now. Return SQLITE_OK if successful, or an SQLite error
4417** code otherwise.
4418**
4419** If the DMS cannot be locked because this is a readonly_shm=1
4420** connection and no other process already holds a lock, return
drh7e45e3a2017-11-08 17:32:12 +00004421** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
dan92c02da2017-11-01 20:59:28 +00004422*/
4423static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
4424 struct flock lock;
4425 int rc = SQLITE_OK;
4426
4427 /* Use F_GETLK to determine the locks other processes are holding
4428 ** on the DMS byte. If it indicates that another process is holding
4429 ** a SHARED lock, then this process may also take a SHARED lock
4430 ** and proceed with opening the *-shm file.
4431 **
4432 ** Or, if no other process is holding any lock, then this process
4433 ** is the first to open it. In this case take an EXCLUSIVE lock on the
4434 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
4435 ** downgrade to a SHARED lock on the DMS byte.
4436 **
4437 ** If another process is holding an EXCLUSIVE lock on the DMS byte,
4438 ** return SQLITE_BUSY to the caller (it will try again). An earlier
4439 ** version of this code attempted the SHARED lock at this point. But
4440 ** this introduced a subtle race condition: if the process holding
4441 ** EXCLUSIVE failed just before truncating the *-shm file, then this
4442 ** process might open and use the *-shm file without truncating it.
4443 ** And if the *-shm file has been corrupted by a power failure or
4444 ** system crash, the database itself may also become corrupt. */
4445 lock.l_whence = SEEK_SET;
4446 lock.l_start = UNIX_SHM_DMS;
4447 lock.l_len = 1;
4448 lock.l_type = F_WRLCK;
drh8820c8d2018-10-02 19:58:08 +00004449 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
dan92c02da2017-11-01 20:59:28 +00004450 rc = SQLITE_IOERR_LOCK;
4451 }else if( lock.l_type==F_UNLCK ){
4452 if( pShmNode->isReadonly ){
4453 pShmNode->isUnlocked = 1;
drh7e45e3a2017-11-08 17:32:12 +00004454 rc = SQLITE_READONLY_CANTINIT;
dan92c02da2017-11-01 20:59:28 +00004455 }else{
4456 rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
drhf7f2a822018-10-11 13:51:48 +00004457 /* The first connection to attach must truncate the -shm file. We
4458 ** truncate to 3 bytes (an arbitrary small number, less than the
4459 ** -shm header size) rather than 0 as a system debugging aid, to
4460 ** help detect if a -shm file truncation is legitimate or is the work
4461 ** or a rogue process. */
4462 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
dan92c02da2017-11-01 20:59:28 +00004463 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
4464 }
4465 }
4466 }else if( lock.l_type==F_WRLCK ){
4467 rc = SQLITE_BUSY;
4468 }
4469
4470 if( rc==SQLITE_OK ){
4471 assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
4472 rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
4473 }
4474 return rc;
4475}
4476
4477/*
danda9fe0c2010-07-13 18:44:03 +00004478** Open a shared-memory area associated with open database file pDbFd.
drh7234c6d2010-06-19 15:10:09 +00004479** This particular implementation uses mmapped files.
drhd9e5c4f2010-05-12 18:01:39 +00004480**
drh7234c6d2010-06-19 15:10:09 +00004481** The file used to implement shared-memory is in the same directory
4482** as the open database file and has the same name as the open database
4483** file with the "-shm" suffix added. For example, if the database file
4484** is "/home/user1/config.db" then the file that is created and mmapped
drha4ced192010-07-15 18:32:40 +00004485** for shared memory will be called "/home/user1/config.db-shm".
4486**
4487** Another approach to is to use files in /dev/shm or /dev/tmp or an
4488** some other tmpfs mount. But if a file in a different directory
4489** from the database file is used, then differing access permissions
4490** or a chroot() might cause two different processes on the same
4491** database to end up using different files for shared memory -
4492** meaning that their memory would not really be shared - resulting
4493** in database corruption. Nevertheless, this tmpfs file usage
4494** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
4495** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
4496** option results in an incompatible build of SQLite; builds of SQLite
4497** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
4498** same database file at the same time, database corruption will likely
4499** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
4500** "unsupported" and may go away in a future SQLite release.
drhd9e5c4f2010-05-12 18:01:39 +00004501**
4502** When opening a new shared-memory file, if no other instances of that
4503** file are currently open, in this process or in other processes, then
4504** the file must be truncated to zero length or have its header cleared.
drh3cb93392011-03-12 18:10:44 +00004505**
4506** If the original database file (pDbFd) is using the "unix-excl" VFS
4507** that means that an exclusive lock is held on the database file and
4508** that no other processes are able to read or write the database. In
4509** that case, we do not really need shared memory. No shared memory
4510** file is created. The shared memory will be simulated with heap memory.
drhd9e5c4f2010-05-12 18:01:39 +00004511*/
danda9fe0c2010-07-13 18:44:03 +00004512static int unixOpenSharedMemory(unixFile *pDbFd){
4513 struct unixShm *p = 0; /* The connection to be opened */
4514 struct unixShmNode *pShmNode; /* The underlying mmapped file */
dan92c02da2017-11-01 20:59:28 +00004515 int rc = SQLITE_OK; /* Result code */
danda9fe0c2010-07-13 18:44:03 +00004516 unixInodeInfo *pInode; /* The inode of fd */
danf12ba662017-11-07 15:43:52 +00004517 char *zShm; /* Name of the file used for SHM */
danda9fe0c2010-07-13 18:44:03 +00004518 int nShmFilename; /* Size of the SHM filename in bytes */
drhd9e5c4f2010-05-12 18:01:39 +00004519
danda9fe0c2010-07-13 18:44:03 +00004520 /* Allocate space for the new unixShm object. */
drhf3cdcdc2015-04-29 16:50:28 +00004521 p = sqlite3_malloc64( sizeof(*p) );
mistachkinfad30392016-02-13 23:43:46 +00004522 if( p==0 ) return SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004523 memset(p, 0, sizeof(*p));
drhd9e5c4f2010-05-12 18:01:39 +00004524 assert( pDbFd->pShm==0 );
drhd9e5c4f2010-05-12 18:01:39 +00004525
danda9fe0c2010-07-13 18:44:03 +00004526 /* Check to see if a unixShmNode object already exists. Reuse an existing
4527 ** one if present. Create a new one if necessary.
drhd9e5c4f2010-05-12 18:01:39 +00004528 */
drh095908e2018-08-13 20:46:18 +00004529 assert( unixFileMutexNotheld(pDbFd) );
drhd9e5c4f2010-05-12 18:01:39 +00004530 unixEnterMutex();
drh8b3cf822010-06-01 21:02:51 +00004531 pInode = pDbFd->pInode;
4532 pShmNode = pInode->pShmNode;
drhd91c68f2010-05-14 14:52:25 +00004533 if( pShmNode==0 ){
danddb0ac42010-07-14 14:48:58 +00004534 struct stat sStat; /* fstat() info for database file */
drh4bf66fd2015-02-19 02:43:02 +00004535#ifndef SQLITE_SHM_DIRECTORY
4536 const char *zBasePath = pDbFd->zPath;
4537#endif
danddb0ac42010-07-14 14:48:58 +00004538
4539 /* Call fstat() to figure out the permissions on the database file. If
4540 ** a new *-shm file is created, an attempt will be made to create it
drh8c815d12012-02-13 20:16:37 +00004541 ** with the same permissions.
danddb0ac42010-07-14 14:48:58 +00004542 */
drhf3b1ed02015-12-02 13:11:03 +00004543 if( osFstat(pDbFd->h, &sStat) ){
danddb0ac42010-07-14 14:48:58 +00004544 rc = SQLITE_IOERR_FSTAT;
4545 goto shm_open_err;
4546 }
4547
drha4ced192010-07-15 18:32:40 +00004548#ifdef SQLITE_SHM_DIRECTORY
drh52bcde02012-01-03 14:50:45 +00004549 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
drha4ced192010-07-15 18:32:40 +00004550#else
drh4bf66fd2015-02-19 02:43:02 +00004551 nShmFilename = 6 + (int)strlen(zBasePath);
drha4ced192010-07-15 18:32:40 +00004552#endif
drhf3cdcdc2015-04-29 16:50:28 +00004553 pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
drhd91c68f2010-05-14 14:52:25 +00004554 if( pShmNode==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004555 rc = SQLITE_NOMEM_BKPT;
drhd9e5c4f2010-05-12 18:01:39 +00004556 goto shm_open_err;
4557 }
drh9cb5a0d2012-01-05 21:19:54 +00004558 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
danf12ba662017-11-07 15:43:52 +00004559 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
drha4ced192010-07-15 18:32:40 +00004560#ifdef SQLITE_SHM_DIRECTORY
danf12ba662017-11-07 15:43:52 +00004561 sqlite3_snprintf(nShmFilename, zShm,
drha4ced192010-07-15 18:32:40 +00004562 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
4563 (u32)sStat.st_ino, (u32)sStat.st_dev);
4564#else
danf12ba662017-11-07 15:43:52 +00004565 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
4566 sqlite3FileSuffix3(pDbFd->zPath, zShm);
drha4ced192010-07-15 18:32:40 +00004567#endif
drh8820c8d2018-10-02 19:58:08 +00004568 pShmNode->hShm = -1;
drhd91c68f2010-05-14 14:52:25 +00004569 pDbFd->pInode->pShmNode = pShmNode;
4570 pShmNode->pInode = pDbFd->pInode;
drh97a7e5e2016-04-26 18:58:54 +00004571 if( sqlite3GlobalConfig.bCoreMutex ){
drh24efa542018-10-02 19:36:40 +00004572 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
4573 if( pShmNode->pShmMutex==0 ){
drh97a7e5e2016-04-26 18:58:54 +00004574 rc = SQLITE_NOMEM_BKPT;
4575 goto shm_open_err;
4576 }
drhd91c68f2010-05-14 14:52:25 +00004577 }
drhd9e5c4f2010-05-12 18:01:39 +00004578
drh3cb93392011-03-12 18:10:44 +00004579 if( pInode->bProcessLock==0 ){
danf12ba662017-11-07 15:43:52 +00004580 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
drhc398c652019-11-22 00:42:01 +00004581 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
4582 (sStat.st_mode&0777));
drh3ec4a0c2011-10-11 18:18:54 +00004583 }
drh8820c8d2018-10-02 19:58:08 +00004584 if( pShmNode->hShm<0 ){
drhc398c652019-11-22 00:42:01 +00004585 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
4586 (sStat.st_mode&0777));
drh8820c8d2018-10-02 19:58:08 +00004587 if( pShmNode->hShm<0 ){
danf12ba662017-11-07 15:43:52 +00004588 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
4589 goto shm_open_err;
4590 }
4591 pShmNode->isReadonly = 1;
drhd9e5c4f2010-05-12 18:01:39 +00004592 }
drhac7c3ac2012-02-11 19:23:48 +00004593
4594 /* If this process is running as root, make sure that the SHM file
4595 ** is owned by the same user that owns the original database. Otherwise,
drhed466822012-05-31 13:10:49 +00004596 ** the original owner will not be able to connect.
drhac7c3ac2012-02-11 19:23:48 +00004597 */
drh8820c8d2018-10-02 19:58:08 +00004598 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
dan176b2a92017-11-01 06:59:19 +00004599
dan92c02da2017-11-01 20:59:28 +00004600 rc = unixLockSharedMemory(pDbFd, pShmNode);
drh7e45e3a2017-11-08 17:32:12 +00004601 if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
drhd9e5c4f2010-05-12 18:01:39 +00004602 }
drhd9e5c4f2010-05-12 18:01:39 +00004603 }
4604
drhd91c68f2010-05-14 14:52:25 +00004605 /* Make the new connection a child of the unixShmNode */
4606 p->pShmNode = pShmNode;
drhd9e5c4f2010-05-12 18:01:39 +00004607#ifdef SQLITE_DEBUG
drhd91c68f2010-05-14 14:52:25 +00004608 p->id = pShmNode->nextShmId++;
drhd9e5c4f2010-05-12 18:01:39 +00004609#endif
drhd91c68f2010-05-14 14:52:25 +00004610 pShmNode->nRef++;
drhd9e5c4f2010-05-12 18:01:39 +00004611 pDbFd->pShm = p;
4612 unixLeaveMutex();
dan0668f592010-07-20 18:59:00 +00004613
4614 /* The reference count on pShmNode has already been incremented under
4615 ** the cover of the unixEnterMutex() mutex and the pointer from the
4616 ** new (struct unixShm) object to the pShmNode has been set. All that is
4617 ** left to do is to link the new object into the linked list starting
drh24efa542018-10-02 19:36:40 +00004618 ** at pShmNode->pFirst. This must be done while holding the
4619 ** pShmNode->pShmMutex.
dan0668f592010-07-20 18:59:00 +00004620 */
drh24efa542018-10-02 19:36:40 +00004621 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan0668f592010-07-20 18:59:00 +00004622 p->pNext = pShmNode->pFirst;
4623 pShmNode->pFirst = p;
drh24efa542018-10-02 19:36:40 +00004624 sqlite3_mutex_leave(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004625 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004626
4627 /* Jump here on any error */
4628shm_open_err:
drhd91c68f2010-05-14 14:52:25 +00004629 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
drhd9e5c4f2010-05-12 18:01:39 +00004630 sqlite3_free(p);
drhd9e5c4f2010-05-12 18:01:39 +00004631 unixLeaveMutex();
4632 return rc;
4633}
4634
4635/*
danda9fe0c2010-07-13 18:44:03 +00004636** This function is called to obtain a pointer to region iRegion of the
4637** shared-memory associated with the database file fd. Shared-memory regions
4638** are numbered starting from zero. Each shared-memory region is szRegion
4639** bytes in size.
4640**
4641** If an error occurs, an error code is returned and *pp is set to NULL.
4642**
4643** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
4644** region has not been allocated (by any client, including one running in a
4645** separate process), then *pp is set to NULL and SQLITE_OK returned. If
4646** bExtend is non-zero and the requested shared-memory region has not yet
4647** been allocated, it is allocated by this function.
4648**
4649** If the shared-memory region has already been allocated or is allocated by
4650** this call as described above, then it is mapped into this processes
4651** address space (if it is not already), *pp is set to point to the mapped
4652** memory and SQLITE_OK returned.
drhd9e5c4f2010-05-12 18:01:39 +00004653*/
danda9fe0c2010-07-13 18:44:03 +00004654static int unixShmMap(
4655 sqlite3_file *fd, /* Handle open on database file */
4656 int iRegion, /* Region to retrieve */
4657 int szRegion, /* Size of regions */
4658 int bExtend, /* True to extend file if necessary */
4659 void volatile **pp /* OUT: Mapped memory */
drhd9e5c4f2010-05-12 18:01:39 +00004660){
danda9fe0c2010-07-13 18:44:03 +00004661 unixFile *pDbFd = (unixFile*)fd;
4662 unixShm *p;
4663 unixShmNode *pShmNode;
4664 int rc = SQLITE_OK;
dan781e34c2014-03-20 08:59:47 +00004665 int nShmPerMap = unixShmRegionPerMap();
4666 int nReqRegion;
drhd9e5c4f2010-05-12 18:01:39 +00004667
danda9fe0c2010-07-13 18:44:03 +00004668 /* If the shared-memory file has not yet been opened, open it now. */
4669 if( pDbFd->pShm==0 ){
4670 rc = unixOpenSharedMemory(pDbFd);
4671 if( rc!=SQLITE_OK ) return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004672 }
drhd9e5c4f2010-05-12 18:01:39 +00004673
danda9fe0c2010-07-13 18:44:03 +00004674 p = pDbFd->pShm;
4675 pShmNode = p->pShmNode;
drh24efa542018-10-02 19:36:40 +00004676 sqlite3_mutex_enter(pShmNode->pShmMutex);
dan92c02da2017-11-01 20:59:28 +00004677 if( pShmNode->isUnlocked ){
4678 rc = unixLockSharedMemory(pDbFd, pShmNode);
4679 if( rc!=SQLITE_OK ) goto shmpage_out;
4680 pShmNode->isUnlocked = 0;
4681 }
danda9fe0c2010-07-13 18:44:03 +00004682 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
drh3cb93392011-03-12 18:10:44 +00004683 assert( pShmNode->pInode==pDbFd->pInode );
drh8820c8d2018-10-02 19:58:08 +00004684 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4685 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
danda9fe0c2010-07-13 18:44:03 +00004686
dan781e34c2014-03-20 08:59:47 +00004687 /* Minimum number of regions required to be mapped. */
4688 nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
4689
4690 if( pShmNode->nRegion<nReqRegion ){
danda9fe0c2010-07-13 18:44:03 +00004691 char **apNew; /* New apRegion[] array */
dan781e34c2014-03-20 08:59:47 +00004692 int nByte = nReqRegion*szRegion; /* Minimum required file size */
danda9fe0c2010-07-13 18:44:03 +00004693 struct stat sStat; /* Used by fstat() */
4694
4695 pShmNode->szRegion = szRegion;
4696
drh8820c8d2018-10-02 19:58:08 +00004697 if( pShmNode->hShm>=0 ){
drh3cb93392011-03-12 18:10:44 +00004698 /* The requested region is not mapped into this processes address space.
4699 ** Check to see if it has been allocated (i.e. if the wal-index file is
4700 ** large enough to contain the requested region).
danda9fe0c2010-07-13 18:44:03 +00004701 */
drh8820c8d2018-10-02 19:58:08 +00004702 if( osFstat(pShmNode->hShm, &sStat) ){
drh3cb93392011-03-12 18:10:44 +00004703 rc = SQLITE_IOERR_SHMSIZE;
danda9fe0c2010-07-13 18:44:03 +00004704 goto shmpage_out;
4705 }
drh3cb93392011-03-12 18:10:44 +00004706
4707 if( sStat.st_size<nByte ){
4708 /* The requested memory region does not exist. If bExtend is set to
4709 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
drh3cb93392011-03-12 18:10:44 +00004710 */
dan47a2b4a2013-04-26 16:09:29 +00004711 if( !bExtend ){
drh0fbb50e2012-11-13 10:54:12 +00004712 goto shmpage_out;
4713 }
dan47a2b4a2013-04-26 16:09:29 +00004714
4715 /* Alternatively, if bExtend is true, extend the file. Do this by
4716 ** writing a single byte to the end of each (OS) page being
4717 ** allocated or extended. Technically, we need only write to the
4718 ** last page in order to extend the file. But writing to all new
4719 ** pages forces the OS to allocate them immediately, which reduces
4720 ** the chances of SIGBUS while accessing the mapped region later on.
4721 */
4722 else{
4723 static const int pgsz = 4096;
4724 int iPg;
4725
4726 /* Write to the last byte of each newly allocated or extended page */
4727 assert( (nByte % pgsz)==0 );
4728 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
drhe1818ec2015-12-01 16:21:35 +00004729 int x = 0;
drh8820c8d2018-10-02 19:58:08 +00004730 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
dan47a2b4a2013-04-26 16:09:29 +00004731 const char *zFile = pShmNode->zFilename;
4732 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
4733 goto shmpage_out;
4734 }
4735 }
drh3cb93392011-03-12 18:10:44 +00004736 }
4737 }
danda9fe0c2010-07-13 18:44:03 +00004738 }
4739
4740 /* Map the requested memory region into this processes address space. */
4741 apNew = (char **)sqlite3_realloc(
dan781e34c2014-03-20 08:59:47 +00004742 pShmNode->apRegion, nReqRegion*sizeof(char *)
danda9fe0c2010-07-13 18:44:03 +00004743 );
4744 if( !apNew ){
mistachkinfad30392016-02-13 23:43:46 +00004745 rc = SQLITE_IOERR_NOMEM_BKPT;
danda9fe0c2010-07-13 18:44:03 +00004746 goto shmpage_out;
4747 }
4748 pShmNode->apRegion = apNew;
dan781e34c2014-03-20 08:59:47 +00004749 while( pShmNode->nRegion<nReqRegion ){
4750 int nMap = szRegion*nShmPerMap;
4751 int i;
drh3cb93392011-03-12 18:10:44 +00004752 void *pMem;
drh8820c8d2018-10-02 19:58:08 +00004753 if( pShmNode->hShm>=0 ){
dan781e34c2014-03-20 08:59:47 +00004754 pMem = osMmap(0, nMap,
drh66dfec8b2011-06-01 20:01:49 +00004755 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
drh8820c8d2018-10-02 19:58:08 +00004756 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
drh3cb93392011-03-12 18:10:44 +00004757 );
4758 if( pMem==MAP_FAILED ){
drh50990db2011-04-13 20:26:13 +00004759 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
drh3cb93392011-03-12 18:10:44 +00004760 goto shmpage_out;
4761 }
4762 }else{
drhb6c4d592018-10-11 02:39:11 +00004763 pMem = sqlite3_malloc64(nMap);
drh3cb93392011-03-12 18:10:44 +00004764 if( pMem==0 ){
mistachkinfad30392016-02-13 23:43:46 +00004765 rc = SQLITE_NOMEM_BKPT;
drh3cb93392011-03-12 18:10:44 +00004766 goto shmpage_out;
4767 }
drhb6c4d592018-10-11 02:39:11 +00004768 memset(pMem, 0, nMap);
danda9fe0c2010-07-13 18:44:03 +00004769 }
dan781e34c2014-03-20 08:59:47 +00004770
4771 for(i=0; i<nShmPerMap; i++){
4772 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
4773 }
4774 pShmNode->nRegion += nShmPerMap;
danda9fe0c2010-07-13 18:44:03 +00004775 }
4776 }
4777
4778shmpage_out:
4779 if( pShmNode->nRegion>iRegion ){
4780 *pp = pShmNode->apRegion[iRegion];
4781 }else{
4782 *pp = 0;
4783 }
drh66dfec8b2011-06-01 20:01:49 +00004784 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
drh24efa542018-10-02 19:36:40 +00004785 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004786 return rc;
drhd9e5c4f2010-05-12 18:01:39 +00004787}
4788
4789/*
drhd9e5c4f2010-05-12 18:01:39 +00004790** Change the lock state for a shared-memory segment.
drh15d68092010-05-31 16:56:14 +00004791**
4792** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
4793** different here than in posix. In xShmLock(), one can go from unlocked
4794** to shared and back or from unlocked to exclusive and back. But one may
4795** not go from shared to exclusive or from exclusive to shared.
drhd9e5c4f2010-05-12 18:01:39 +00004796*/
4797static int unixShmLock(
4798 sqlite3_file *fd, /* Database file holding the shared memory */
drh73b64e42010-05-30 19:55:15 +00004799 int ofst, /* First lock to acquire or release */
4800 int n, /* Number of locks to acquire or release */
4801 int flags /* What to do with the lock */
drhd9e5c4f2010-05-12 18:01:39 +00004802){
drh73b64e42010-05-30 19:55:15 +00004803 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
4804 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
4805 unixShm *pX; /* For looping over all siblings */
4806 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
4807 int rc = SQLITE_OK; /* Result code */
4808 u16 mask; /* Mask of locks to take or release */
drhd9e5c4f2010-05-12 18:01:39 +00004809
drhd91c68f2010-05-14 14:52:25 +00004810 assert( pShmNode==pDbFd->pInode->pShmNode );
4811 assert( pShmNode->pInode==pDbFd->pInode );
drhc99597c2010-05-31 01:41:15 +00004812 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
drh73b64e42010-05-30 19:55:15 +00004813 assert( n>=1 );
4814 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
4815 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
4816 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
4817 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
4818 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
drh8820c8d2018-10-02 19:58:08 +00004819 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
4820 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
drhd91c68f2010-05-14 14:52:25 +00004821
dan97ccc1b2020-03-27 17:23:17 +00004822 /* Check that, if this to be a blocking lock, that locks have been
4823 ** obtained in the following order.
4824 **
4825 ** 1. Checkpointer lock (ofst==1).
4826 ** 2. Recover lock (ofst==2).
4827 ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
4828 ** 4. Write lock (ofst==0).
4829 **
4830 ** In other words, if this is a blocking lock, none of the locks that
4831 ** occur later in the above list than the lock being obtained may be
4832 ** held. */
4833#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
4834 assert( pDbFd->iBusyTimeout==0
4835 || (flags & SQLITE_SHM_UNLOCK) || ofst==0
4836 || ((p->exclMask|p->sharedMask)&~((1<<ofst)-2))==0
4837 );
4838#endif
4839
drhc99597c2010-05-31 01:41:15 +00004840 mask = (1<<(ofst+n)) - (1<<ofst);
drh73b64e42010-05-30 19:55:15 +00004841 assert( n>1 || mask==(1<<ofst) );
drh24efa542018-10-02 19:36:40 +00004842 sqlite3_mutex_enter(pShmNode->pShmMutex);
drh73b64e42010-05-30 19:55:15 +00004843 if( flags & SQLITE_SHM_UNLOCK ){
4844 u16 allMask = 0; /* Mask of locks held by siblings */
4845
4846 /* See if any siblings hold this same lock */
4847 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
4848 if( pX==p ) continue;
4849 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
4850 allMask |= pX->sharedMask;
4851 }
4852
4853 /* Unlock the system-level locks */
4854 if( (mask & allMask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004855 rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
drh73b64e42010-05-30 19:55:15 +00004856 }else{
drhd9e5c4f2010-05-12 18:01:39 +00004857 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004858 }
drh73b64e42010-05-30 19:55:15 +00004859
4860 /* Undo the local locks */
4861 if( rc==SQLITE_OK ){
4862 p->exclMask &= ~mask;
4863 p->sharedMask &= ~mask;
4864 }
4865 }else if( flags & SQLITE_SHM_SHARED ){
4866 u16 allShared = 0; /* Union of locks held by connections other than "p" */
4867
4868 /* Find out which shared locks are already held by sibling connections.
4869 ** If any sibling already holds an exclusive lock, go ahead and return
4870 ** SQLITE_BUSY.
4871 */
4872 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004873 if( (pX->exclMask & mask)!=0 ){
drhd9e5c4f2010-05-12 18:01:39 +00004874 rc = SQLITE_BUSY;
drh73b64e42010-05-30 19:55:15 +00004875 break;
4876 }
4877 allShared |= pX->sharedMask;
4878 }
4879
4880 /* Get shared locks at the system level, if necessary */
4881 if( rc==SQLITE_OK ){
4882 if( (allShared & mask)==0 ){
drhbbf76ee2015-03-10 20:22:35 +00004883 rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004884 }else{
drh73b64e42010-05-30 19:55:15 +00004885 rc = SQLITE_OK;
drhd9e5c4f2010-05-12 18:01:39 +00004886 }
drhd9e5c4f2010-05-12 18:01:39 +00004887 }
drh73b64e42010-05-30 19:55:15 +00004888
4889 /* Get the local shared locks */
4890 if( rc==SQLITE_OK ){
4891 p->sharedMask |= mask;
4892 }
4893 }else{
4894 /* Make sure no sibling connections hold locks that will block this
4895 ** lock. If any do, return SQLITE_BUSY right away.
4896 */
4897 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
drh73b64e42010-05-30 19:55:15 +00004898 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
4899 rc = SQLITE_BUSY;
4900 break;
4901 }
4902 }
4903
4904 /* Get the exclusive locks at the system level. Then if successful
4905 ** also mark the local connection as being locked.
4906 */
4907 if( rc==SQLITE_OK ){
drhbbf76ee2015-03-10 20:22:35 +00004908 rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
drhd9e5c4f2010-05-12 18:01:39 +00004909 if( rc==SQLITE_OK ){
drh15d68092010-05-31 16:56:14 +00004910 assert( (p->sharedMask & mask)==0 );
drh73b64e42010-05-30 19:55:15 +00004911 p->exclMask |= mask;
drhd9e5c4f2010-05-12 18:01:39 +00004912 }
drhd9e5c4f2010-05-12 18:01:39 +00004913 }
4914 }
drh24efa542018-10-02 19:36:40 +00004915 sqlite3_mutex_leave(pShmNode->pShmMutex);
drh20e1f082010-05-31 16:10:12 +00004916 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
drh5ac93652015-03-21 20:59:43 +00004917 p->id, osGetpid(0), p->sharedMask, p->exclMask));
drhd9e5c4f2010-05-12 18:01:39 +00004918 return rc;
4919}
4920
drh286a2882010-05-20 23:51:06 +00004921/*
4922** Implement a memory barrier or memory fence on shared memory.
4923**
4924** All loads and stores begun before the barrier must complete before
4925** any load or store begun after the barrier.
4926*/
4927static void unixShmBarrier(
dan18801912010-06-14 14:07:50 +00004928 sqlite3_file *fd /* Database file holding the shared memory */
drh286a2882010-05-20 23:51:06 +00004929){
drhff828942010-06-26 21:34:06 +00004930 UNUSED_PARAMETER(fd);
drh22c733d2015-09-24 12:40:43 +00004931 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
dana86acc22018-09-12 20:32:19 +00004932 assert( fd->pMethods->xLock==nolockLock
4933 || unixFileMutexNotheld((unixFile*)fd)
4934 );
drh22c733d2015-09-24 12:40:43 +00004935 unixEnterMutex(); /* Also mutex, for redundancy */
drhb29ad852010-06-01 00:03:57 +00004936 unixLeaveMutex();
drh286a2882010-05-20 23:51:06 +00004937}
4938
dan18801912010-06-14 14:07:50 +00004939/*
danda9fe0c2010-07-13 18:44:03 +00004940** Close a connection to shared-memory. Delete the underlying
4941** storage if deleteFlag is true.
drhe11fedc2010-07-14 00:14:30 +00004942**
4943** If there is no shared memory associated with the connection then this
4944** routine is a harmless no-op.
dan18801912010-06-14 14:07:50 +00004945*/
danda9fe0c2010-07-13 18:44:03 +00004946static int unixShmUnmap(
4947 sqlite3_file *fd, /* The underlying database file */
4948 int deleteFlag /* Delete shared-memory if true */
dan13a3cb82010-06-11 19:04:21 +00004949){
danda9fe0c2010-07-13 18:44:03 +00004950 unixShm *p; /* The connection to be closed */
4951 unixShmNode *pShmNode; /* The underlying shared-memory file */
4952 unixShm **pp; /* For looping over sibling connections */
4953 unixFile *pDbFd; /* The underlying database file */
dan13a3cb82010-06-11 19:04:21 +00004954
danda9fe0c2010-07-13 18:44:03 +00004955 pDbFd = (unixFile*)fd;
4956 p = pDbFd->pShm;
4957 if( p==0 ) return SQLITE_OK;
4958 pShmNode = p->pShmNode;
4959
4960 assert( pShmNode==pDbFd->pInode->pShmNode );
4961 assert( pShmNode->pInode==pDbFd->pInode );
4962
4963 /* Remove connection p from the set of connections associated
4964 ** with pShmNode */
drh24efa542018-10-02 19:36:40 +00004965 sqlite3_mutex_enter(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004966 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
4967 *pp = p->pNext;
dan13a3cb82010-06-11 19:04:21 +00004968
danda9fe0c2010-07-13 18:44:03 +00004969 /* Free the connection p */
4970 sqlite3_free(p);
4971 pDbFd->pShm = 0;
drh24efa542018-10-02 19:36:40 +00004972 sqlite3_mutex_leave(pShmNode->pShmMutex);
danda9fe0c2010-07-13 18:44:03 +00004973
4974 /* If pShmNode->nRef has reached 0, then close the underlying
4975 ** shared-memory file, too */
drh095908e2018-08-13 20:46:18 +00004976 assert( unixFileMutexNotheld(pDbFd) );
danda9fe0c2010-07-13 18:44:03 +00004977 unixEnterMutex();
4978 assert( pShmNode->nRef>0 );
4979 pShmNode->nRef--;
4980 if( pShmNode->nRef==0 ){
drh8820c8d2018-10-02 19:58:08 +00004981 if( deleteFlag && pShmNode->hShm>=0 ){
drh4bf66fd2015-02-19 02:43:02 +00004982 osUnlink(pShmNode->zFilename);
4983 }
danda9fe0c2010-07-13 18:44:03 +00004984 unixShmPurge(pDbFd);
4985 }
4986 unixLeaveMutex();
4987
4988 return SQLITE_OK;
dan13a3cb82010-06-11 19:04:21 +00004989}
drh286a2882010-05-20 23:51:06 +00004990
danda9fe0c2010-07-13 18:44:03 +00004991
drhd9e5c4f2010-05-12 18:01:39 +00004992#else
drh6b017cc2010-06-14 18:01:46 +00004993# define unixShmMap 0
danda9fe0c2010-07-13 18:44:03 +00004994# define unixShmLock 0
drh286a2882010-05-20 23:51:06 +00004995# define unixShmBarrier 0
danda9fe0c2010-07-13 18:44:03 +00004996# define unixShmUnmap 0
drhd9e5c4f2010-05-12 18:01:39 +00004997#endif /* #ifndef SQLITE_OMIT_WAL */
4998
mistachkine98844f2013-08-24 00:59:24 +00004999#if SQLITE_MAX_MMAP_SIZE>0
drh734c9862008-11-28 15:37:20 +00005000/*
danaef49d72013-03-25 16:28:54 +00005001** If it is currently memory mapped, unmap file pFd.
dand306e1a2013-03-20 18:25:49 +00005002*/
danf23da962013-03-23 21:00:41 +00005003static void unixUnmapfile(unixFile *pFd){
5004 assert( pFd->nFetchOut==0 );
5005 if( pFd->pMapRegion ){
drh9b4c59f2013-04-15 17:03:42 +00005006 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
danf23da962013-03-23 21:00:41 +00005007 pFd->pMapRegion = 0;
5008 pFd->mmapSize = 0;
drh9b4c59f2013-04-15 17:03:42 +00005009 pFd->mmapSizeActual = 0;
danf23da962013-03-23 21:00:41 +00005010 }
5011}
dan5d8a1372013-03-19 19:28:06 +00005012
danaef49d72013-03-25 16:28:54 +00005013/*
dane6ecd662013-04-01 17:56:59 +00005014** Attempt to set the size of the memory mapping maintained by file
5015** descriptor pFd to nNew bytes. Any existing mapping is discarded.
5016**
5017** If successful, this function sets the following variables:
5018**
5019** unixFile.pMapRegion
5020** unixFile.mmapSize
drh9b4c59f2013-04-15 17:03:42 +00005021** unixFile.mmapSizeActual
dane6ecd662013-04-01 17:56:59 +00005022**
5023** If unsuccessful, an error message is logged via sqlite3_log() and
5024** the three variables above are zeroed. In this case SQLite should
5025** continue accessing the database using the xRead() and xWrite()
5026** methods.
5027*/
5028static void unixRemapfile(
5029 unixFile *pFd, /* File descriptor object */
5030 i64 nNew /* Required mapping size */
5031){
dan4ff7bc42013-04-02 12:04:09 +00005032 const char *zErr = "mmap";
dane6ecd662013-04-01 17:56:59 +00005033 int h = pFd->h; /* File descriptor open on db file */
5034 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
drh9b4c59f2013-04-15 17:03:42 +00005035 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
dane6ecd662013-04-01 17:56:59 +00005036 u8 *pNew = 0; /* Location of new mapping */
5037 int flags = PROT_READ; /* Flags to pass to mmap() */
5038
5039 assert( pFd->nFetchOut==0 );
5040 assert( nNew>pFd->mmapSize );
drh9b4c59f2013-04-15 17:03:42 +00005041 assert( nNew<=pFd->mmapSizeMax );
dane6ecd662013-04-01 17:56:59 +00005042 assert( nNew>0 );
drh9b4c59f2013-04-15 17:03:42 +00005043 assert( pFd->mmapSizeActual>=pFd->mmapSize );
dan4ff7bc42013-04-02 12:04:09 +00005044 assert( MAP_FAILED!=0 );
dane6ecd662013-04-01 17:56:59 +00005045
danfe33e392015-11-17 20:56:06 +00005046#ifdef SQLITE_MMAP_READWRITE
dane6ecd662013-04-01 17:56:59 +00005047 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
danfe33e392015-11-17 20:56:06 +00005048#endif
dane6ecd662013-04-01 17:56:59 +00005049
5050 if( pOrig ){
dan781e34c2014-03-20 08:59:47 +00005051#if HAVE_MREMAP
5052 i64 nReuse = pFd->mmapSize;
5053#else
danbc760632014-03-20 09:42:09 +00005054 const int szSyspage = osGetpagesize();
dane6ecd662013-04-01 17:56:59 +00005055 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
dan781e34c2014-03-20 08:59:47 +00005056#endif
dane6ecd662013-04-01 17:56:59 +00005057 u8 *pReq = &pOrig[nReuse];
5058
5059 /* Unmap any pages of the existing mapping that cannot be reused. */
5060 if( nReuse!=nOrig ){
5061 osMunmap(pReq, nOrig-nReuse);
5062 }
5063
5064#if HAVE_MREMAP
5065 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
dan4ff7bc42013-04-02 12:04:09 +00005066 zErr = "mremap";
dane6ecd662013-04-01 17:56:59 +00005067#else
5068 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
5069 if( pNew!=MAP_FAILED ){
5070 if( pNew!=pReq ){
5071 osMunmap(pNew, nNew - nReuse);
dan4ff7bc42013-04-02 12:04:09 +00005072 pNew = 0;
dane6ecd662013-04-01 17:56:59 +00005073 }else{
5074 pNew = pOrig;
5075 }
5076 }
5077#endif
5078
dan48ccef82013-04-02 20:55:01 +00005079 /* The attempt to extend the existing mapping failed. Free it. */
5080 if( pNew==MAP_FAILED || pNew==0 ){
dane6ecd662013-04-01 17:56:59 +00005081 osMunmap(pOrig, nReuse);
5082 }
5083 }
5084
5085 /* If pNew is still NULL, try to create an entirely new mapping. */
5086 if( pNew==0 ){
5087 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
dane6ecd662013-04-01 17:56:59 +00005088 }
5089
dan4ff7bc42013-04-02 12:04:09 +00005090 if( pNew==MAP_FAILED ){
5091 pNew = 0;
5092 nNew = 0;
5093 unixLogError(SQLITE_OK, zErr, pFd->zPath);
5094
5095 /* If the mmap() above failed, assume that all subsequent mmap() calls
5096 ** will probably fail too. Fall back to using xRead/xWrite exclusively
5097 ** in this case. */
drh9b4c59f2013-04-15 17:03:42 +00005098 pFd->mmapSizeMax = 0;
dan4ff7bc42013-04-02 12:04:09 +00005099 }
dane6ecd662013-04-01 17:56:59 +00005100 pFd->pMapRegion = (void *)pNew;
drh9b4c59f2013-04-15 17:03:42 +00005101 pFd->mmapSize = pFd->mmapSizeActual = nNew;
dane6ecd662013-04-01 17:56:59 +00005102}
5103
5104/*
danaef49d72013-03-25 16:28:54 +00005105** Memory map or remap the file opened by file-descriptor pFd (if the file
5106** is already mapped, the existing mapping is replaced by the new). Or, if
5107** there already exists a mapping for this file, and there are still
5108** outstanding xFetch() references to it, this function is a no-op.
5109**
5110** If parameter nByte is non-negative, then it is the requested size of
5111** the mapping to create. Otherwise, if nByte is less than zero, then the
5112** requested size is the size of the file on disk. The actual size of the
5113** created mapping is either the requested size or the value configured
drh0d0614b2013-03-25 23:09:28 +00005114** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
danaef49d72013-03-25 16:28:54 +00005115**
5116** SQLITE_OK is returned if no error occurs (even if the mapping is not
5117** recreated as a result of outstanding references) or an SQLite error
5118** code otherwise.
5119*/
drhf3b1ed02015-12-02 13:11:03 +00005120static int unixMapfile(unixFile *pFd, i64 nMap){
danf23da962013-03-23 21:00:41 +00005121 assert( nMap>=0 || pFd->nFetchOut==0 );
drh333e6ca2015-12-02 15:44:39 +00005122 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005123 if( pFd->nFetchOut>0 ) return SQLITE_OK;
5124
5125 if( nMap<0 ){
drh3044b512014-06-16 16:41:52 +00005126 struct stat statbuf; /* Low-level file information */
drhf3b1ed02015-12-02 13:11:03 +00005127 if( osFstat(pFd->h, &statbuf) ){
danf23da962013-03-23 21:00:41 +00005128 return SQLITE_IOERR_FSTAT;
daneb97b292013-03-20 14:26:59 +00005129 }
drh3044b512014-06-16 16:41:52 +00005130 nMap = statbuf.st_size;
danf23da962013-03-23 21:00:41 +00005131 }
drh9b4c59f2013-04-15 17:03:42 +00005132 if( nMap>pFd->mmapSizeMax ){
5133 nMap = pFd->mmapSizeMax;
daneb97b292013-03-20 14:26:59 +00005134 }
5135
drh333e6ca2015-12-02 15:44:39 +00005136 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
danf23da962013-03-23 21:00:41 +00005137 if( nMap!=pFd->mmapSize ){
drh333e6ca2015-12-02 15:44:39 +00005138 unixRemapfile(pFd, nMap);
dan5d8a1372013-03-19 19:28:06 +00005139 }
5140
danf23da962013-03-23 21:00:41 +00005141 return SQLITE_OK;
5142}
mistachkine98844f2013-08-24 00:59:24 +00005143#endif /* SQLITE_MAX_MMAP_SIZE>0 */
danf23da962013-03-23 21:00:41 +00005144
danaef49d72013-03-25 16:28:54 +00005145/*
5146** If possible, return a pointer to a mapping of file fd starting at offset
5147** iOff. The mapping must be valid for at least nAmt bytes.
5148**
5149** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
5150** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
5151** Finally, if an error does occur, return an SQLite error code. The final
5152** value of *pp is undefined in this case.
5153**
5154** If this function does return a pointer, the caller must eventually
5155** release the reference by calling unixUnfetch().
5156*/
danf23da962013-03-23 21:00:41 +00005157static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
drh9b4c59f2013-04-15 17:03:42 +00005158#if SQLITE_MAX_MMAP_SIZE>0
danf23da962013-03-23 21:00:41 +00005159 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
drhfbc7e882013-04-11 01:16:15 +00005160#endif
danf23da962013-03-23 21:00:41 +00005161 *pp = 0;
5162
drh9b4c59f2013-04-15 17:03:42 +00005163#if SQLITE_MAX_MMAP_SIZE>0
5164 if( pFd->mmapSizeMax>0 ){
danf23da962013-03-23 21:00:41 +00005165 if( pFd->pMapRegion==0 ){
5166 int rc = unixMapfile(pFd, -1);
5167 if( rc!=SQLITE_OK ) return rc;
5168 }
5169 if( pFd->mmapSize >= iOff+nAmt ){
5170 *pp = &((u8 *)pFd->pMapRegion)[iOff];
5171 pFd->nFetchOut++;
5172 }
5173 }
drh6e0b6d52013-04-09 16:19:20 +00005174#endif
danf23da962013-03-23 21:00:41 +00005175 return SQLITE_OK;
5176}
5177
danaef49d72013-03-25 16:28:54 +00005178/*
dandf737fe2013-03-25 17:00:24 +00005179** If the third argument is non-NULL, then this function releases a
5180** reference obtained by an earlier call to unixFetch(). The second
5181** argument passed to this function must be the same as the corresponding
5182** argument that was passed to the unixFetch() invocation.
5183**
5184** Or, if the third argument is NULL, then this function is being called
5185** to inform the VFS layer that, according to POSIX, any existing mapping
5186** may now be invalid and should be unmapped.
danaef49d72013-03-25 16:28:54 +00005187*/
dandf737fe2013-03-25 17:00:24 +00005188static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
mistachkinb5ca3cb2013-08-24 01:12:03 +00005189#if SQLITE_MAX_MMAP_SIZE>0
drh1bcbc622014-01-09 13:39:07 +00005190 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
dan9871c592014-01-10 16:40:21 +00005191 UNUSED_PARAMETER(iOff);
drh1bcbc622014-01-09 13:39:07 +00005192
danaef49d72013-03-25 16:28:54 +00005193 /* If p==0 (unmap the entire file) then there must be no outstanding
5194 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
5195 ** then there must be at least one outstanding. */
danf23da962013-03-23 21:00:41 +00005196 assert( (p==0)==(pFd->nFetchOut==0) );
5197
dandf737fe2013-03-25 17:00:24 +00005198 /* If p!=0, it must match the iOff value. */
5199 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
5200
danf23da962013-03-23 21:00:41 +00005201 if( p ){
5202 pFd->nFetchOut--;
5203 }else{
5204 unixUnmapfile(pFd);
5205 }
5206
5207 assert( pFd->nFetchOut>=0 );
drh1bcbc622014-01-09 13:39:07 +00005208#else
5209 UNUSED_PARAMETER(fd);
5210 UNUSED_PARAMETER(p);
dan9871c592014-01-10 16:40:21 +00005211 UNUSED_PARAMETER(iOff);
mistachkinb5ca3cb2013-08-24 01:12:03 +00005212#endif
danf23da962013-03-23 21:00:41 +00005213 return SQLITE_OK;
dan5d8a1372013-03-19 19:28:06 +00005214}
5215
5216/*
drh734c9862008-11-28 15:37:20 +00005217** Here ends the implementation of all sqlite3_file methods.
5218**
5219********************** End sqlite3_file Methods *******************************
5220******************************************************************************/
5221
5222/*
drh6b9d6dd2008-12-03 19:34:47 +00005223** This division contains definitions of sqlite3_io_methods objects that
5224** implement various file locking strategies. It also contains definitions
5225** of "finder" functions. A finder-function is used to locate the appropriate
5226** sqlite3_io_methods object for a particular database file. The pAppData
5227** field of the sqlite3_vfs VFS objects are initialized to be pointers to
5228** the correct finder-function for that VFS.
5229**
5230** Most finder functions return a pointer to a fixed sqlite3_io_methods
5231** object. The only interesting finder-function is autolockIoFinder, which
5232** looks at the filesystem type and tries to guess the best locking
5233** strategy from that.
5234**
peter.d.reid60ec9142014-09-06 16:39:46 +00005235** For finder-function F, two objects are created:
drh1875f7a2008-12-08 18:19:17 +00005236**
5237** (1) The real finder-function named "FImpt()".
5238**
dane946c392009-08-22 11:39:46 +00005239** (2) A constant pointer to this function named just "F".
drh1875f7a2008-12-08 18:19:17 +00005240**
5241**
5242** A pointer to the F pointer is used as the pAppData value for VFS
5243** objects. We have to do this instead of letting pAppData point
5244** directly at the finder-function since C90 rules prevent a void*
5245** from be cast into a function pointer.
5246**
drh6b9d6dd2008-12-03 19:34:47 +00005247**
drh7708e972008-11-29 00:56:52 +00005248** Each instance of this macro generates two objects:
drh734c9862008-11-28 15:37:20 +00005249**
drh7708e972008-11-29 00:56:52 +00005250** * A constant sqlite3_io_methods object call METHOD that has locking
5251** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
5252**
5253** * An I/O method finder function called FINDER that returns a pointer
5254** to the METHOD object in the previous bullet.
drh734c9862008-11-28 15:37:20 +00005255*/
drhe6d41732015-02-21 00:49:00 +00005256#define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
drh7708e972008-11-29 00:56:52 +00005257static const sqlite3_io_methods METHOD = { \
drhd9e5c4f2010-05-12 18:01:39 +00005258 VERSION, /* iVersion */ \
drh7708e972008-11-29 00:56:52 +00005259 CLOSE, /* xClose */ \
5260 unixRead, /* xRead */ \
5261 unixWrite, /* xWrite */ \
5262 unixTruncate, /* xTruncate */ \
5263 unixSync, /* xSync */ \
5264 unixFileSize, /* xFileSize */ \
5265 LOCK, /* xLock */ \
5266 UNLOCK, /* xUnlock */ \
5267 CKLOCK, /* xCheckReservedLock */ \
5268 unixFileControl, /* xFileControl */ \
5269 unixSectorSize, /* xSectorSize */ \
drhd9e5c4f2010-05-12 18:01:39 +00005270 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
drhd9f94412014-09-22 03:22:27 +00005271 SHMMAP, /* xShmMap */ \
danda9fe0c2010-07-13 18:44:03 +00005272 unixShmLock, /* xShmLock */ \
drh286a2882010-05-20 23:51:06 +00005273 unixShmBarrier, /* xShmBarrier */ \
dan5d8a1372013-03-19 19:28:06 +00005274 unixShmUnmap, /* xShmUnmap */ \
danf23da962013-03-23 21:00:41 +00005275 unixFetch, /* xFetch */ \
5276 unixUnfetch, /* xUnfetch */ \
drh7708e972008-11-29 00:56:52 +00005277}; \
drh0c2694b2009-09-03 16:23:44 +00005278static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
5279 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
drh7708e972008-11-29 00:56:52 +00005280 return &METHOD; \
drh1875f7a2008-12-08 18:19:17 +00005281} \
drh0c2694b2009-09-03 16:23:44 +00005282static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
drh1875f7a2008-12-08 18:19:17 +00005283 = FINDER##Impl;
drh7708e972008-11-29 00:56:52 +00005284
5285/*
5286** Here are all of the sqlite3_io_methods objects for each of the
5287** locking strategies. Functions that return pointers to these methods
5288** are also created.
5289*/
5290IOMETHODS(
5291 posixIoFinder, /* Finder function name */
5292 posixIoMethods, /* sqlite3_io_methods object name */
dan5d8a1372013-03-19 19:28:06 +00005293 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005294 unixClose, /* xClose method */
5295 unixLock, /* xLock method */
5296 unixUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005297 unixCheckReservedLock, /* xCheckReservedLock method */
5298 unixShmMap /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005299)
drh7708e972008-11-29 00:56:52 +00005300IOMETHODS(
5301 nolockIoFinder, /* Finder function name */
5302 nolockIoMethods, /* sqlite3_io_methods object name */
drh3e2c8422018-08-13 11:32:07 +00005303 3, /* shared memory and mmap are enabled */
drh7708e972008-11-29 00:56:52 +00005304 nolockClose, /* xClose method */
5305 nolockLock, /* xLock method */
5306 nolockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005307 nolockCheckReservedLock, /* xCheckReservedLock method */
5308 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005309)
drh7708e972008-11-29 00:56:52 +00005310IOMETHODS(
5311 dotlockIoFinder, /* Finder function name */
5312 dotlockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005313 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005314 dotlockClose, /* xClose method */
5315 dotlockLock, /* xLock method */
5316 dotlockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005317 dotlockCheckReservedLock, /* xCheckReservedLock method */
5318 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005319)
drh7708e972008-11-29 00:56:52 +00005320
drhe89b2912015-03-03 20:42:01 +00005321#if SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005322IOMETHODS(
5323 flockIoFinder, /* Finder function name */
5324 flockIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005325 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005326 flockClose, /* xClose method */
5327 flockLock, /* xLock method */
5328 flockUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005329 flockCheckReservedLock, /* xCheckReservedLock method */
5330 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005331)
drh7708e972008-11-29 00:56:52 +00005332#endif
5333
drh6c7d5c52008-11-21 20:32:33 +00005334#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005335IOMETHODS(
5336 semIoFinder, /* Finder function name */
5337 semIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005338 1, /* shared memory is disabled */
drh8cd5b252015-03-02 22:06:43 +00005339 semXClose, /* xClose method */
5340 semXLock, /* xLock method */
5341 semXUnlock, /* xUnlock method */
5342 semXCheckReservedLock, /* xCheckReservedLock method */
drhd9f94412014-09-22 03:22:27 +00005343 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005344)
aswiftaebf4132008-11-21 00:10:35 +00005345#endif
drh7708e972008-11-29 00:56:52 +00005346
drhd2cb50b2009-01-09 21:41:17 +00005347#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005348IOMETHODS(
5349 afpIoFinder, /* Finder function name */
5350 afpIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005351 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005352 afpClose, /* xClose method */
5353 afpLock, /* xLock method */
5354 afpUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005355 afpCheckReservedLock, /* xCheckReservedLock method */
5356 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005357)
drh715ff302008-12-03 22:32:44 +00005358#endif
5359
5360/*
5361** The proxy locking method is a "super-method" in the sense that it
5362** opens secondary file descriptors for the conch and lock files and
5363** it uses proxy, dot-file, AFP, and flock() locking methods on those
5364** secondary files. For this reason, the division that implements
5365** proxy locking is located much further down in the file. But we need
5366** to go ahead and define the sqlite3_io_methods and finder function
5367** for proxy locking here. So we forward declare the I/O methods.
5368*/
drhd2cb50b2009-01-09 21:41:17 +00005369#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00005370static int proxyClose(sqlite3_file*);
5371static int proxyLock(sqlite3_file*, int);
5372static int proxyUnlock(sqlite3_file*, int);
5373static int proxyCheckReservedLock(sqlite3_file*, int*);
drh7708e972008-11-29 00:56:52 +00005374IOMETHODS(
5375 proxyIoFinder, /* Finder function name */
5376 proxyIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005377 1, /* shared memory is disabled */
drh7708e972008-11-29 00:56:52 +00005378 proxyClose, /* xClose method */
5379 proxyLock, /* xLock method */
5380 proxyUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005381 proxyCheckReservedLock, /* xCheckReservedLock method */
5382 0 /* xShmMap method */
drh1875f7a2008-12-08 18:19:17 +00005383)
aswiftaebf4132008-11-21 00:10:35 +00005384#endif
drh7708e972008-11-29 00:56:52 +00005385
drh7ed97b92010-01-20 13:07:21 +00005386/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
5387#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5388IOMETHODS(
5389 nfsIoFinder, /* Finder function name */
5390 nfsIoMethods, /* sqlite3_io_methods object name */
drh6e1f4822010-07-13 23:41:40 +00005391 1, /* shared memory is disabled */
drh7ed97b92010-01-20 13:07:21 +00005392 unixClose, /* xClose method */
5393 unixLock, /* xLock method */
5394 nfsUnlock, /* xUnlock method */
drhd9f94412014-09-22 03:22:27 +00005395 unixCheckReservedLock, /* xCheckReservedLock method */
5396 0 /* xShmMap method */
drh7ed97b92010-01-20 13:07:21 +00005397)
5398#endif
drh7708e972008-11-29 00:56:52 +00005399
drhd2cb50b2009-01-09 21:41:17 +00005400#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh7708e972008-11-29 00:56:52 +00005401/*
drh6b9d6dd2008-12-03 19:34:47 +00005402** This "finder" function attempts to determine the best locking strategy
5403** for the database file "filePath". It then returns the sqlite3_io_methods
drh7708e972008-11-29 00:56:52 +00005404** object that implements that strategy.
5405**
5406** This is for MacOSX only.
5407*/
drh1875f7a2008-12-08 18:19:17 +00005408static const sqlite3_io_methods *autolockIoFinderImpl(
drh7708e972008-11-29 00:56:52 +00005409 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005410 unixFile *pNew /* open file object for the database file */
drh7708e972008-11-29 00:56:52 +00005411){
5412 static const struct Mapping {
drh6b9d6dd2008-12-03 19:34:47 +00005413 const char *zFilesystem; /* Filesystem type name */
5414 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
drh7708e972008-11-29 00:56:52 +00005415 } aMap[] = {
5416 { "hfs", &posixIoMethods },
5417 { "ufs", &posixIoMethods },
5418 { "afpfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005419 { "smbfs", &afpIoMethods },
drh7708e972008-11-29 00:56:52 +00005420 { "webdav", &nolockIoMethods },
5421 { 0, 0 }
5422 };
5423 int i;
5424 struct statfs fsInfo;
5425 struct flock lockInfo;
5426
5427 if( !filePath ){
drh6b9d6dd2008-12-03 19:34:47 +00005428 /* If filePath==NULL that means we are dealing with a transient file
5429 ** that does not need to be locked. */
drh7708e972008-11-29 00:56:52 +00005430 return &nolockIoMethods;
5431 }
5432 if( statfs(filePath, &fsInfo) != -1 ){
5433 if( fsInfo.f_flags & MNT_RDONLY ){
5434 return &nolockIoMethods;
5435 }
5436 for(i=0; aMap[i].zFilesystem; i++){
5437 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
5438 return aMap[i].pMethods;
5439 }
5440 }
5441 }
5442
5443 /* Default case. Handles, amongst others, "nfs".
5444 ** Test byte-range lock using fcntl(). If the call succeeds,
5445 ** assume that the file-system supports POSIX style locks.
drh734c9862008-11-28 15:37:20 +00005446 */
drh7708e972008-11-29 00:56:52 +00005447 lockInfo.l_len = 1;
5448 lockInfo.l_start = 0;
5449 lockInfo.l_whence = SEEK_SET;
5450 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005451 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
drh7ed97b92010-01-20 13:07:21 +00005452 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
5453 return &nfsIoMethods;
5454 } else {
5455 return &posixIoMethods;
5456 }
drh7708e972008-11-29 00:56:52 +00005457 }else{
5458 return &dotlockIoMethods;
5459 }
5460}
drh0c2694b2009-09-03 16:23:44 +00005461static const sqlite3_io_methods
5462 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
drh1875f7a2008-12-08 18:19:17 +00005463
drhd2cb50b2009-01-09 21:41:17 +00005464#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh7708e972008-11-29 00:56:52 +00005465
drhe89b2912015-03-03 20:42:01 +00005466#if OS_VXWORKS
5467/*
5468** This "finder" function for VxWorks checks to see if posix advisory
5469** locking works. If it does, then that is what is used. If it does not
5470** work, then fallback to named semaphore locking.
chw78a13182009-04-07 05:35:03 +00005471*/
drhe89b2912015-03-03 20:42:01 +00005472static const sqlite3_io_methods *vxworksIoFinderImpl(
chw78a13182009-04-07 05:35:03 +00005473 const char *filePath, /* name of the database file */
drh0c2694b2009-09-03 16:23:44 +00005474 unixFile *pNew /* the open file object */
chw78a13182009-04-07 05:35:03 +00005475){
5476 struct flock lockInfo;
5477
5478 if( !filePath ){
5479 /* If filePath==NULL that means we are dealing with a transient file
5480 ** that does not need to be locked. */
5481 return &nolockIoMethods;
5482 }
5483
5484 /* Test if fcntl() is supported and use POSIX style locks.
5485 ** Otherwise fall back to the named semaphore method.
5486 */
5487 lockInfo.l_len = 1;
5488 lockInfo.l_start = 0;
5489 lockInfo.l_whence = SEEK_SET;
5490 lockInfo.l_type = F_RDLCK;
drh99ab3b12011-03-02 15:09:07 +00005491 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
chw78a13182009-04-07 05:35:03 +00005492 return &posixIoMethods;
5493 }else{
5494 return &semIoMethods;
5495 }
5496}
drh0c2694b2009-09-03 16:23:44 +00005497static const sqlite3_io_methods
drhe89b2912015-03-03 20:42:01 +00005498 *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
chw78a13182009-04-07 05:35:03 +00005499
drhe89b2912015-03-03 20:42:01 +00005500#endif /* OS_VXWORKS */
chw78a13182009-04-07 05:35:03 +00005501
drh7708e972008-11-29 00:56:52 +00005502/*
peter.d.reid60ec9142014-09-06 16:39:46 +00005503** An abstract type for a pointer to an IO method finder function:
drh7708e972008-11-29 00:56:52 +00005504*/
drh0c2694b2009-09-03 16:23:44 +00005505typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
drh7708e972008-11-29 00:56:52 +00005506
aswiftaebf4132008-11-21 00:10:35 +00005507
drh734c9862008-11-28 15:37:20 +00005508/****************************************************************************
5509**************************** sqlite3_vfs methods ****************************
5510**
5511** This division contains the implementation of methods on the
5512** sqlite3_vfs object.
5513*/
5514
danielk1977a3d4c882007-03-23 10:08:38 +00005515/*
danielk1977e339d652008-06-28 11:23:00 +00005516** Initialize the contents of the unixFile structure pointed to by pId.
danielk1977ad94b582007-08-20 06:44:22 +00005517*/
5518static int fillInUnixFile(
danielk1977e339d652008-06-28 11:23:00 +00005519 sqlite3_vfs *pVfs, /* Pointer to vfs object */
drhbfe66312006-10-03 17:40:40 +00005520 int h, /* Open file descriptor of file being opened */
drh218c5082008-03-07 00:27:10 +00005521 sqlite3_file *pId, /* Write to the unixFile structure here */
drhda0e7682008-07-30 15:27:54 +00005522 const char *zFilename, /* Name of the file being opened */
drhc02a43a2012-01-10 23:18:38 +00005523 int ctrlFlags /* Zero or more UNIXFILE_* values */
drhbfe66312006-10-03 17:40:40 +00005524){
drh7708e972008-11-29 00:56:52 +00005525 const sqlite3_io_methods *pLockingStyle;
drhda0e7682008-07-30 15:27:54 +00005526 unixFile *pNew = (unixFile *)pId;
5527 int rc = SQLITE_OK;
5528
drh8af6c222010-05-14 12:43:01 +00005529 assert( pNew->pInode==NULL );
drh218c5082008-03-07 00:27:10 +00005530
drhb07028f2011-10-14 21:49:18 +00005531 /* No locking occurs in temporary files */
drhc02a43a2012-01-10 23:18:38 +00005532 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
drhb07028f2011-10-14 21:49:18 +00005533
drh308c2a52010-05-14 11:30:18 +00005534 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
danielk1977ad94b582007-08-20 06:44:22 +00005535 pNew->h = h;
drhde60fc22011-12-14 17:53:36 +00005536 pNew->pVfs = pVfs;
drhd9e5c4f2010-05-12 18:01:39 +00005537 pNew->zPath = zFilename;
drhc02a43a2012-01-10 23:18:38 +00005538 pNew->ctrlFlags = (u8)ctrlFlags;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005539#if SQLITE_MAX_MMAP_SIZE>0
danede01a92013-05-17 12:10:52 +00005540 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
mistachkinb5ca3cb2013-08-24 01:12:03 +00005541#endif
drhc02a43a2012-01-10 23:18:38 +00005542 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
5543 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
drhcb15f352011-12-23 01:04:17 +00005544 pNew->ctrlFlags |= UNIXFILE_PSOW;
drhbec7c972011-12-23 00:25:02 +00005545 }
drh503a6862013-03-01 01:07:17 +00005546 if( strcmp(pVfs->zName,"unix-excl")==0 ){
drhf12b3f62011-12-21 14:42:29 +00005547 pNew->ctrlFlags |= UNIXFILE_EXCL;
drha7e61d82011-03-12 17:02:57 +00005548 }
drh339eb0b2008-03-07 15:34:11 +00005549
drh6c7d5c52008-11-21 20:32:33 +00005550#if OS_VXWORKS
drh107886a2008-11-21 22:21:50 +00005551 pNew->pId = vxworksFindFileId(zFilename);
5552 if( pNew->pId==0 ){
drhc02a43a2012-01-10 23:18:38 +00005553 ctrlFlags |= UNIXFILE_NOLOCK;
mistachkinfad30392016-02-13 23:43:46 +00005554 rc = SQLITE_NOMEM_BKPT;
chw97185482008-11-17 08:05:31 +00005555 }
5556#endif
5557
drhc02a43a2012-01-10 23:18:38 +00005558 if( ctrlFlags & UNIXFILE_NOLOCK ){
drh7708e972008-11-29 00:56:52 +00005559 pLockingStyle = &nolockIoMethods;
drhda0e7682008-07-30 15:27:54 +00005560 }else{
drh0c2694b2009-09-03 16:23:44 +00005561 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
aswiftaebf4132008-11-21 00:10:35 +00005562#if SQLITE_ENABLE_LOCKING_STYLE
5563 /* Cache zFilename in the locking context (AFP and dotlock override) for
5564 ** proxyLock activation is possible (remote proxy is based on db name)
5565 ** zFilename remains valid until file is closed, to support */
5566 pNew->lockingContext = (void*)zFilename;
5567#endif
drhda0e7682008-07-30 15:27:54 +00005568 }
danielk1977e339d652008-06-28 11:23:00 +00005569
drh7ed97b92010-01-20 13:07:21 +00005570 if( pLockingStyle == &posixIoMethods
5571#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
5572 || pLockingStyle == &nfsIoMethods
5573#endif
5574 ){
drh7708e972008-11-29 00:56:52 +00005575 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005576 rc = findInodeInfo(pNew, &pNew->pInode);
dane946c392009-08-22 11:39:46 +00005577 if( rc!=SQLITE_OK ){
mistachkin48864df2013-03-21 21:20:32 +00005578 /* If an error occurred in findInodeInfo(), close the file descriptor
drh8af6c222010-05-14 12:43:01 +00005579 ** immediately, before releasing the mutex. findInodeInfo() may fail
dane946c392009-08-22 11:39:46 +00005580 ** in two scenarios:
5581 **
5582 ** (a) A call to fstat() failed.
5583 ** (b) A malloc failed.
5584 **
5585 ** Scenario (b) may only occur if the process is holding no other
5586 ** file descriptors open on the same file. If there were other file
5587 ** descriptors on this file, then no malloc would be required by
drh8af6c222010-05-14 12:43:01 +00005588 ** findInodeInfo(). If this is the case, it is quite safe to close
dane946c392009-08-22 11:39:46 +00005589 ** handle h - as it is guaranteed that no posix locks will be released
5590 ** by doing so.
5591 **
5592 ** If scenario (a) caused the error then things are not so safe. The
5593 ** implicit assumption here is that if fstat() fails, things are in
5594 ** such bad shape that dropping a lock or two doesn't matter much.
5595 */
drh0e9365c2011-03-02 02:08:13 +00005596 robust_close(pNew, h, __LINE__);
dane946c392009-08-22 11:39:46 +00005597 h = -1;
5598 }
drh7708e972008-11-29 00:56:52 +00005599 unixLeaveMutex();
5600 }
danielk1977e339d652008-06-28 11:23:00 +00005601
drhd2cb50b2009-01-09 21:41:17 +00005602#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
aswiftf0551ee2008-12-03 21:26:19 +00005603 else if( pLockingStyle == &afpIoMethods ){
drh7708e972008-11-29 00:56:52 +00005604 /* AFP locking uses the file path so it needs to be included in
5605 ** the afpLockingContext.
5606 */
5607 afpLockingContext *pCtx;
drhf3cdcdc2015-04-29 16:50:28 +00005608 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh7708e972008-11-29 00:56:52 +00005609 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005610 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005611 }else{
5612 /* NB: zFilename exists and remains valid until the file is closed
5613 ** according to requirement F11141. So we do not need to make a
5614 ** copy of the filename. */
5615 pCtx->dbPath = zFilename;
drh7ed97b92010-01-20 13:07:21 +00005616 pCtx->reserved = 0;
drh7708e972008-11-29 00:56:52 +00005617 srandomdev();
drh6c7d5c52008-11-21 20:32:33 +00005618 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005619 rc = findInodeInfo(pNew, &pNew->pInode);
drh7ed97b92010-01-20 13:07:21 +00005620 if( rc!=SQLITE_OK ){
5621 sqlite3_free(pNew->lockingContext);
drh0e9365c2011-03-02 02:08:13 +00005622 robust_close(pNew, h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00005623 h = -1;
5624 }
drh7708e972008-11-29 00:56:52 +00005625 unixLeaveMutex();
drhbfe66312006-10-03 17:40:40 +00005626 }
drh7708e972008-11-29 00:56:52 +00005627 }
5628#endif
danielk1977e339d652008-06-28 11:23:00 +00005629
drh7708e972008-11-29 00:56:52 +00005630 else if( pLockingStyle == &dotlockIoMethods ){
5631 /* Dotfile locking uses the file path so it needs to be included in
5632 ** the dotlockLockingContext
5633 */
5634 char *zLockFile;
5635 int nFilename;
drhb07028f2011-10-14 21:49:18 +00005636 assert( zFilename!=0 );
drhea678832008-12-10 19:26:22 +00005637 nFilename = (int)strlen(zFilename) + 6;
drhf3cdcdc2015-04-29 16:50:28 +00005638 zLockFile = (char *)sqlite3_malloc64(nFilename);
drh7708e972008-11-29 00:56:52 +00005639 if( zLockFile==0 ){
mistachkinfad30392016-02-13 23:43:46 +00005640 rc = SQLITE_NOMEM_BKPT;
drh7708e972008-11-29 00:56:52 +00005641 }else{
5642 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
danielk1977e339d652008-06-28 11:23:00 +00005643 }
drh7708e972008-11-29 00:56:52 +00005644 pNew->lockingContext = zLockFile;
5645 }
danielk1977e339d652008-06-28 11:23:00 +00005646
drh6c7d5c52008-11-21 20:32:33 +00005647#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00005648 else if( pLockingStyle == &semIoMethods ){
5649 /* Named semaphore locking uses the file path so it needs to be
5650 ** included in the semLockingContext
5651 */
5652 unixEnterMutex();
drh8af6c222010-05-14 12:43:01 +00005653 rc = findInodeInfo(pNew, &pNew->pInode);
5654 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
5655 char *zSemName = pNew->pInode->aSemName;
drh7708e972008-11-29 00:56:52 +00005656 int n;
drh2238dcc2009-08-27 17:56:20 +00005657 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
drh7708e972008-11-29 00:56:52 +00005658 pNew->pId->zCanonicalName);
drh2238dcc2009-08-27 17:56:20 +00005659 for( n=1; zSemName[n]; n++ )
drh7708e972008-11-29 00:56:52 +00005660 if( zSemName[n]=='/' ) zSemName[n] = '_';
drh8af6c222010-05-14 12:43:01 +00005661 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
5662 if( pNew->pInode->pSem == SEM_FAILED ){
mistachkinfad30392016-02-13 23:43:46 +00005663 rc = SQLITE_NOMEM_BKPT;
drh8af6c222010-05-14 12:43:01 +00005664 pNew->pInode->aSemName[0] = '\0';
chw97185482008-11-17 08:05:31 +00005665 }
chw97185482008-11-17 08:05:31 +00005666 }
drh7708e972008-11-29 00:56:52 +00005667 unixLeaveMutex();
danielk1977e339d652008-06-28 11:23:00 +00005668 }
drh7708e972008-11-29 00:56:52 +00005669#endif
aswift5b1a2562008-08-22 00:22:35 +00005670
drh4bf66fd2015-02-19 02:43:02 +00005671 storeLastErrno(pNew, 0);
drh6c7d5c52008-11-21 20:32:33 +00005672#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00005673 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005674 if( h>=0 ) robust_close(pNew, h, __LINE__);
drh309e6552010-02-05 18:00:26 +00005675 h = -1;
drh036ac7f2011-08-08 23:18:05 +00005676 osUnlink(zFilename);
drhc5797542013-04-27 12:13:29 +00005677 pNew->ctrlFlags |= UNIXFILE_DELETE;
chw97185482008-11-17 08:05:31 +00005678 }
chw97185482008-11-17 08:05:31 +00005679#endif
danielk1977e339d652008-06-28 11:23:00 +00005680 if( rc!=SQLITE_OK ){
drh0e9365c2011-03-02 02:08:13 +00005681 if( h>=0 ) robust_close(pNew, h, __LINE__);
danielk1977e339d652008-06-28 11:23:00 +00005682 }else{
drh7708e972008-11-29 00:56:52 +00005683 pNew->pMethod = pLockingStyle;
danielk1977e339d652008-06-28 11:23:00 +00005684 OpenCounter(+1);
drhfbc7e882013-04-11 01:16:15 +00005685 verifyDbFile(pNew);
drhbfe66312006-10-03 17:40:40 +00005686 }
danielk1977e339d652008-06-28 11:23:00 +00005687 return rc;
drh054889e2005-11-30 03:20:31 +00005688}
drh9c06c952005-11-26 00:25:00 +00005689
danielk1977ad94b582007-08-20 06:44:22 +00005690/*
drh8b3cf822010-06-01 21:02:51 +00005691** Return the name of a directory in which to put temporary files.
5692** If no suitable temporary file directory can be found, return NULL.
danielk197717b90b52008-06-06 11:11:25 +00005693*/
drh7234c6d2010-06-19 15:10:09 +00005694static const char *unixTempFileDir(void){
danielk197717b90b52008-06-06 11:11:25 +00005695 static const char *azDirs[] = {
5696 0,
aswiftaebf4132008-11-21 00:10:35 +00005697 0,
danielk197717b90b52008-06-06 11:11:25 +00005698 "/var/tmp",
5699 "/usr/tmp",
5700 "/tmp",
drhb7e50ad2015-11-28 21:49:53 +00005701 "."
danielk197717b90b52008-06-06 11:11:25 +00005702 };
drh2aab11f2016-04-29 20:30:56 +00005703 unsigned int i = 0;
drh8b3cf822010-06-01 21:02:51 +00005704 struct stat buf;
drhb7e50ad2015-11-28 21:49:53 +00005705 const char *zDir = sqlite3_temp_directory;
drh8b3cf822010-06-01 21:02:51 +00005706
drhb7e50ad2015-11-28 21:49:53 +00005707 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
5708 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
drh2aab11f2016-04-29 20:30:56 +00005709 while(1){
5710 if( zDir!=0
5711 && osStat(zDir, &buf)==0
5712 && S_ISDIR(buf.st_mode)
5713 && osAccess(zDir, 03)==0
5714 ){
5715 return zDir;
5716 }
5717 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
5718 zDir = azDirs[i++];
drh8b3cf822010-06-01 21:02:51 +00005719 }
drh7694e062016-04-21 23:37:24 +00005720 return 0;
drh8b3cf822010-06-01 21:02:51 +00005721}
5722
5723/*
5724** Create a temporary file name in zBuf. zBuf must be allocated
5725** by the calling process and must be big enough to hold at least
5726** pVfs->mxPathname bytes.
5727*/
5728static int unixGetTempname(int nBuf, char *zBuf){
drh8b3cf822010-06-01 21:02:51 +00005729 const char *zDir;
drhb7e50ad2015-11-28 21:49:53 +00005730 int iLimit = 0;
danielk197717b90b52008-06-06 11:11:25 +00005731
5732 /* It's odd to simulate an io-error here, but really this is just
5733 ** using the io-error infrastructure to test that SQLite handles this
5734 ** function failing.
5735 */
drh7694e062016-04-21 23:37:24 +00005736 zBuf[0] = 0;
danielk197717b90b52008-06-06 11:11:25 +00005737 SimulateIOError( return SQLITE_IOERR );
5738
drh7234c6d2010-06-19 15:10:09 +00005739 zDir = unixTempFileDir();
drh7694e062016-04-21 23:37:24 +00005740 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
danielk197717b90b52008-06-06 11:11:25 +00005741 do{
drh970942e2015-11-25 23:13:14 +00005742 u64 r;
5743 sqlite3_randomness(sizeof(r), &r);
5744 assert( nBuf>2 );
5745 zBuf[nBuf-2] = 0;
5746 sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
5747 zDir, r, 0);
drhb7e50ad2015-11-28 21:49:53 +00005748 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
drh99ab3b12011-03-02 15:09:07 +00005749 }while( osAccess(zBuf,0)==0 );
danielk197717b90b52008-06-06 11:11:25 +00005750 return SQLITE_OK;
5751}
5752
drhd2cb50b2009-01-09 21:41:17 +00005753#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drhc66d5b62008-12-03 22:48:32 +00005754/*
5755** Routine to transform a unixFile into a proxy-locking unixFile.
5756** Implementation in the proxy-lock division, but used by unixOpen()
5757** if SQLITE_PREFER_PROXY_LOCKING is defined.
5758*/
5759static int proxyTransformUnixFile(unixFile*, const char*);
drh947bd802008-12-04 12:34:15 +00005760#endif
drhc66d5b62008-12-03 22:48:32 +00005761
dan08da86a2009-08-21 17:18:03 +00005762/*
5763** Search for an unused file descriptor that was opened on the database
5764** file (not a journal or master-journal file) identified by pathname
5765** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
5766** argument to this function.
5767**
5768** Such a file descriptor may exist if a database connection was closed
5769** but the associated file descriptor could not be closed because some
5770** other file descriptor open on the same file is holding a file-lock.
5771** Refer to comments in the unixClose() function and the lengthy comment
5772** describing "Posix Advisory Locking" at the start of this file for
5773** further details. Also, ticket #4018.
5774**
5775** If a suitable file descriptor is found, then it is returned. If no
5776** such file descriptor is located, -1 is returned.
5777*/
dane946c392009-08-22 11:39:46 +00005778static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
5779 UnixUnusedFd *pUnused = 0;
5780
5781 /* Do not search for an unused file descriptor on vxworks. Not because
5782 ** vxworks would not benefit from the change (it might, we're not sure),
5783 ** but because no way to test it is currently available. It is better
5784 ** not to risk breaking vxworks support for the sake of such an obscure
5785 ** feature. */
5786#if !OS_VXWORKS
dan08da86a2009-08-21 17:18:03 +00005787 struct stat sStat; /* Results of stat() call */
5788
drhc68886b2017-08-18 16:09:52 +00005789 unixEnterMutex();
5790
dan08da86a2009-08-21 17:18:03 +00005791 /* A stat() call may fail for various reasons. If this happens, it is
5792 ** almost certain that an open() call on the same path will also fail.
5793 ** For this reason, if an error occurs in the stat() call here, it is
5794 ** ignored and -1 is returned. The caller will try to open a new file
5795 ** descriptor on the same path, fail, and return an error to SQLite.
5796 **
5797 ** Even if a subsequent open() call does succeed, the consequences of
peter.d.reid60ec9142014-09-06 16:39:46 +00005798 ** not searching for a reusable file descriptor are not dire. */
drh095908e2018-08-13 20:46:18 +00005799 if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
drhd91c68f2010-05-14 14:52:25 +00005800 unixInodeInfo *pInode;
dan08da86a2009-08-21 17:18:03 +00005801
drh8af6c222010-05-14 12:43:01 +00005802 pInode = inodeList;
5803 while( pInode && (pInode->fileId.dev!=sStat.st_dev
drh25ef7f52016-12-05 20:06:45 +00005804 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
drh8af6c222010-05-14 12:43:01 +00005805 pInode = pInode->pNext;
drh9061ad12010-01-05 00:14:49 +00005806 }
drh8af6c222010-05-14 12:43:01 +00005807 if( pInode ){
dane946c392009-08-22 11:39:46 +00005808 UnixUnusedFd **pp;
drh095908e2018-08-13 20:46:18 +00005809 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
5810 sqlite3_mutex_enter(pInode->pLockMutex);
drh55220a62019-08-06 20:55:06 +00005811 flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
drh8af6c222010-05-14 12:43:01 +00005812 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
dane946c392009-08-22 11:39:46 +00005813 pUnused = *pp;
5814 if( pUnused ){
5815 *pp = pUnused->pNext;
dan08da86a2009-08-21 17:18:03 +00005816 }
drh095908e2018-08-13 20:46:18 +00005817 sqlite3_mutex_leave(pInode->pLockMutex);
dan08da86a2009-08-21 17:18:03 +00005818 }
dan08da86a2009-08-21 17:18:03 +00005819 }
drhc68886b2017-08-18 16:09:52 +00005820 unixLeaveMutex();
dane946c392009-08-22 11:39:46 +00005821#endif /* if !OS_VXWORKS */
5822 return pUnused;
dan08da86a2009-08-21 17:18:03 +00005823}
danielk197717b90b52008-06-06 11:11:25 +00005824
5825/*
dan1bf4ca72016-08-11 18:05:47 +00005826** Find the mode, uid and gid of file zFile.
5827*/
5828static int getFileMode(
5829 const char *zFile, /* File name */
5830 mode_t *pMode, /* OUT: Permissions of zFile */
5831 uid_t *pUid, /* OUT: uid of zFile. */
5832 gid_t *pGid /* OUT: gid of zFile. */
5833){
5834 struct stat sStat; /* Output of stat() on database file */
5835 int rc = SQLITE_OK;
5836 if( 0==osStat(zFile, &sStat) ){
5837 *pMode = sStat.st_mode & 0777;
5838 *pUid = sStat.st_uid;
5839 *pGid = sStat.st_gid;
5840 }else{
5841 rc = SQLITE_IOERR_FSTAT;
5842 }
5843 return rc;
5844}
5845
5846/*
danddb0ac42010-07-14 14:48:58 +00005847** This function is called by unixOpen() to determine the unix permissions
drhf65bc912010-07-14 20:51:34 +00005848** to create new files with. If no error occurs, then SQLITE_OK is returned
danddb0ac42010-07-14 14:48:58 +00005849** and a value suitable for passing as the third argument to open(2) is
5850** written to *pMode. If an IO error occurs, an SQLite error code is
5851** returned and the value of *pMode is not modified.
5852**
peter.d.reid60ec9142014-09-06 16:39:46 +00005853** In most cases, this routine sets *pMode to 0, which will become
drh8c815d12012-02-13 20:16:37 +00005854** an indication to robust_open() to create the file using
5855** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
5856** But if the file being opened is a WAL or regular journal file, then
drh8ab58662010-07-15 18:38:39 +00005857** this function queries the file-system for the permissions on the
5858** corresponding database file and sets *pMode to this value. Whenever
5859** possible, WAL and journal files are created using the same permissions
5860** as the associated database file.
drh81cc5162011-05-17 20:36:21 +00005861**
5862** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
5863** original filename is unavailable. But 8_3_NAMES is only used for
5864** FAT filesystems and permissions do not matter there, so just use
drh1116b172019-09-25 10:36:31 +00005865** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
danddb0ac42010-07-14 14:48:58 +00005866*/
5867static int findCreateFileMode(
5868 const char *zPath, /* Path of file (possibly) being created */
5869 int flags, /* Flags passed as 4th argument to xOpen() */
drhac7c3ac2012-02-11 19:23:48 +00005870 mode_t *pMode, /* OUT: Permissions to open file with */
5871 uid_t *pUid, /* OUT: uid to set on the file */
5872 gid_t *pGid /* OUT: gid to set on the file */
danddb0ac42010-07-14 14:48:58 +00005873){
5874 int rc = SQLITE_OK; /* Return Code */
drh8c815d12012-02-13 20:16:37 +00005875 *pMode = 0;
drhac7c3ac2012-02-11 19:23:48 +00005876 *pUid = 0;
5877 *pGid = 0;
drh8ab58662010-07-15 18:38:39 +00005878 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
danddb0ac42010-07-14 14:48:58 +00005879 char zDb[MAX_PATHNAME+1]; /* Database file path */
5880 int nDb; /* Number of valid bytes in zDb */
danddb0ac42010-07-14 14:48:58 +00005881
dana0c989d2010-11-05 18:07:37 +00005882 /* zPath is a path to a WAL or journal file. The following block derives
5883 ** the path to the associated database file from zPath. This block handles
5884 ** the following naming conventions:
5885 **
5886 ** "<path to db>-journal"
5887 ** "<path to db>-wal"
drh81cc5162011-05-17 20:36:21 +00005888 ** "<path to db>-journalNN"
5889 ** "<path to db>-walNN"
dana0c989d2010-11-05 18:07:37 +00005890 **
drhd337c5b2011-10-20 18:23:35 +00005891 ** where NN is a decimal number. The NN naming schemes are
dana0c989d2010-11-05 18:07:37 +00005892 ** used by the test_multiplex.c module.
5893 */
5894 nDb = sqlite3Strlen30(zPath) - 1;
drhc47167a2011-10-05 15:26:13 +00005895 while( zPath[nDb]!='-' ){
dan629ec142017-09-14 20:41:17 +00005896 /* In normal operation, the journal file name will always contain
5897 ** a '-' character. However in 8+3 filename mode, or if a corrupt
5898 ** rollback journal specifies a master journal with a goofy name, then
5899 ** the '-' might be missing. */
drh90e5dda2015-12-03 20:42:28 +00005900 if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
drhc47167a2011-10-05 15:26:13 +00005901 nDb--;
5902 }
danddb0ac42010-07-14 14:48:58 +00005903 memcpy(zDb, zPath, nDb);
5904 zDb[nDb] = '\0';
dana0c989d2010-11-05 18:07:37 +00005905
dan1bf4ca72016-08-11 18:05:47 +00005906 rc = getFileMode(zDb, pMode, pUid, pGid);
danddb0ac42010-07-14 14:48:58 +00005907 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
5908 *pMode = 0600;
dan1bf4ca72016-08-11 18:05:47 +00005909 }else if( flags & SQLITE_OPEN_URI ){
5910 /* If this is a main database file and the file was opened using a URI
5911 ** filename, check for the "modeof" parameter. If present, interpret
5912 ** its value as a filename and try to copy the mode, uid and gid from
5913 ** that file. */
5914 const char *z = sqlite3_uri_parameter(zPath, "modeof");
5915 if( z ){
5916 rc = getFileMode(z, pMode, pUid, pGid);
5917 }
danddb0ac42010-07-14 14:48:58 +00005918 }
5919 return rc;
5920}
5921
5922/*
danielk1977ad94b582007-08-20 06:44:22 +00005923** Open the file zPath.
5924**
danielk1977b4b47412007-08-17 15:53:36 +00005925** Previously, the SQLite OS layer used three functions in place of this
5926** one:
5927**
5928** sqlite3OsOpenReadWrite();
5929** sqlite3OsOpenReadOnly();
5930** sqlite3OsOpenExclusive();
5931**
5932** These calls correspond to the following combinations of flags:
5933**
5934** ReadWrite() -> (READWRITE | CREATE)
5935** ReadOnly() -> (READONLY)
5936** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
5937**
5938** The old OpenExclusive() accepted a boolean argument - "delFlag". If
5939** true, the file was configured to be automatically deleted when the
5940** file handle closed. To achieve the same effect using this new
5941** interface, add the DELETEONCLOSE flag to those specified above for
5942** OpenExclusive().
5943*/
5944static int unixOpen(
drh6b9d6dd2008-12-03 19:34:47 +00005945 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
5946 const char *zPath, /* Pathname of file to be opened */
5947 sqlite3_file *pFile, /* The file descriptor to be filled in */
5948 int flags, /* Input flags to control the opening */
5949 int *pOutFlags /* Output flags returned to SQLite core */
danielk1977b4b47412007-08-17 15:53:36 +00005950){
dan08da86a2009-08-21 17:18:03 +00005951 unixFile *p = (unixFile *)pFile;
5952 int fd = -1; /* File descriptor returned by open() */
drh6b9d6dd2008-12-03 19:34:47 +00005953 int openFlags = 0; /* Flags to pass to open() */
drhc398c652019-11-22 00:42:01 +00005954 int eType = flags&0x0FFF00; /* Type of file to open */
drhda0e7682008-07-30 15:27:54 +00005955 int noLock; /* True to omit locking primitives */
dan08da86a2009-08-21 17:18:03 +00005956 int rc = SQLITE_OK; /* Function Return Code */
drhc02a43a2012-01-10 23:18:38 +00005957 int ctrlFlags = 0; /* UNIXFILE_* flags */
danielk1977b4b47412007-08-17 15:53:36 +00005958
5959 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
5960 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
5961 int isCreate = (flags & SQLITE_OPEN_CREATE);
5962 int isReadonly = (flags & SQLITE_OPEN_READONLY);
5963 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
drh7ed97b92010-01-20 13:07:21 +00005964#if SQLITE_ENABLE_LOCKING_STYLE
5965 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
5966#endif
drh3d4435b2011-08-26 20:55:50 +00005967#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
5968 struct statfs fsInfo;
5969#endif
danielk1977b4b47412007-08-17 15:53:36 +00005970
danielk1977fee2d252007-08-18 10:59:19 +00005971 /* If creating a master or main-file journal, this function will open
5972 ** a file-descriptor on the directory too. The first time unixSync()
5973 ** is called the directory file descriptor will be fsync()ed and close()d.
5974 */
drha803a2c2017-12-13 20:02:29 +00005975 int isNewJrnl = (isCreate && (
danddb0ac42010-07-14 14:48:58 +00005976 eType==SQLITE_OPEN_MASTER_JOURNAL
5977 || eType==SQLITE_OPEN_MAIN_JOURNAL
5978 || eType==SQLITE_OPEN_WAL
5979 ));
danielk1977fee2d252007-08-18 10:59:19 +00005980
danielk197717b90b52008-06-06 11:11:25 +00005981 /* If argument zPath is a NULL pointer, this function is required to open
5982 ** a temporary file. Use this buffer to store the file name in.
5983 */
drhc02a43a2012-01-10 23:18:38 +00005984 char zTmpname[MAX_PATHNAME+2];
danielk197717b90b52008-06-06 11:11:25 +00005985 const char *zName = zPath;
5986
danielk1977fee2d252007-08-18 10:59:19 +00005987 /* Check the following statements are true:
5988 **
5989 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
5990 ** (b) if CREATE is set, then READWRITE must also be set, and
5991 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
drh33f4e022007-09-03 15:19:34 +00005992 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
danielk1977fee2d252007-08-18 10:59:19 +00005993 */
danielk1977b4b47412007-08-17 15:53:36 +00005994 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
danielk1977b4b47412007-08-17 15:53:36 +00005995 assert(isCreate==0 || isReadWrite);
danielk1977b4b47412007-08-17 15:53:36 +00005996 assert(isExclusive==0 || isCreate);
drh33f4e022007-09-03 15:19:34 +00005997 assert(isDelete==0 || isCreate);
5998
danddb0ac42010-07-14 14:48:58 +00005999 /* The main DB, main journal, WAL file and master journal are never
6000 ** automatically deleted. Nor are they ever temporary files. */
dan08da86a2009-08-21 17:18:03 +00006001 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
6002 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
6003 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006004 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
danielk1977b4b47412007-08-17 15:53:36 +00006005
danielk1977fee2d252007-08-18 10:59:19 +00006006 /* Assert that the upper layer has set one of the "file-type" flags. */
6007 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
6008 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
6009 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
danddb0ac42010-07-14 14:48:58 +00006010 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
danielk1977fee2d252007-08-18 10:59:19 +00006011 );
6012
drhb00d8622014-01-01 15:18:36 +00006013 /* Detect a pid change and reset the PRNG. There is a race condition
6014 ** here such that two or more threads all trying to open databases at
6015 ** the same instant might all reset the PRNG. But multiple resets
6016 ** are harmless.
6017 */
drh5ac93652015-03-21 20:59:43 +00006018 if( randomnessPid!=osGetpid(0) ){
6019 randomnessPid = osGetpid(0);
drhb00d8622014-01-01 15:18:36 +00006020 sqlite3_randomness(0,0);
6021 }
dan08da86a2009-08-21 17:18:03 +00006022 memset(p, 0, sizeof(unixFile));
danielk1977e339d652008-06-28 11:23:00 +00006023
dan08da86a2009-08-21 17:18:03 +00006024 if( eType==SQLITE_OPEN_MAIN_DB ){
dane946c392009-08-22 11:39:46 +00006025 UnixUnusedFd *pUnused;
6026 pUnused = findReusableFd(zName, flags);
6027 if( pUnused ){
6028 fd = pUnused->fd;
6029 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006030 pUnused = sqlite3_malloc64(sizeof(*pUnused));
dane946c392009-08-22 11:39:46 +00006031 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006032 return SQLITE_NOMEM_BKPT;
dane946c392009-08-22 11:39:46 +00006033 }
6034 }
drhc68886b2017-08-18 16:09:52 +00006035 p->pPreallocatedUnused = pUnused;
drhc02a43a2012-01-10 23:18:38 +00006036
6037 /* Database filenames are double-zero terminated if they are not
6038 ** URIs with parameters. Hence, they can always be passed into
6039 ** sqlite3_uri_parameter(). */
6040 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
6041
dan08da86a2009-08-21 17:18:03 +00006042 }else if( !zName ){
6043 /* If zName is NULL, the upper layer is requesting a temp file. */
drha803a2c2017-12-13 20:02:29 +00006044 assert(isDelete && !isNewJrnl);
drhb7e50ad2015-11-28 21:49:53 +00006045 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
danielk197717b90b52008-06-06 11:11:25 +00006046 if( rc!=SQLITE_OK ){
6047 return rc;
6048 }
6049 zName = zTmpname;
drhc02a43a2012-01-10 23:18:38 +00006050
6051 /* Generated temporary filenames are always double-zero terminated
6052 ** for use by sqlite3_uri_parameter(). */
6053 assert( zName[strlen(zName)+1]==0 );
danielk197717b90b52008-06-06 11:11:25 +00006054 }
6055
dan08da86a2009-08-21 17:18:03 +00006056 /* Determine the value of the flags parameter passed to POSIX function
6057 ** open(). These must be calculated even if open() is not called, as
6058 ** they may be stored as part of the file handle and used by the
6059 ** 'conch file' locking functions later on. */
drh734c9862008-11-28 15:37:20 +00006060 if( isReadonly ) openFlags |= O_RDONLY;
6061 if( isReadWrite ) openFlags |= O_RDWR;
6062 if( isCreate ) openFlags |= O_CREAT;
6063 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
drhc398c652019-11-22 00:42:01 +00006064 openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
danielk1977b4b47412007-08-17 15:53:36 +00006065
danielk1977b4b47412007-08-17 15:53:36 +00006066 if( fd<0 ){
danddb0ac42010-07-14 14:48:58 +00006067 mode_t openMode; /* Permissions to create file with */
drhac7c3ac2012-02-11 19:23:48 +00006068 uid_t uid; /* Userid for the file */
6069 gid_t gid; /* Groupid for the file */
6070 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
danddb0ac42010-07-14 14:48:58 +00006071 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006072 assert( !p->pPreallocatedUnused );
drh8ab58662010-07-15 18:38:39 +00006073 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
danddb0ac42010-07-14 14:48:58 +00006074 return rc;
6075 }
drhad4f1e52011-03-04 15:43:57 +00006076 fd = robust_open(zName, openFlags, openMode);
drh308c2a52010-05-14 11:30:18 +00006077 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
drh5a2d9702015-11-26 02:21:05 +00006078 assert( !isExclusive || (openFlags & O_CREAT)!=0 );
dana688ca52018-01-10 11:56:03 +00006079 if( fd<0 ){
6080 if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
6081 /* If unable to create a journal because the directory is not
6082 ** writable, change the error code to indicate that. */
6083 rc = SQLITE_READONLY_DIRECTORY;
6084 }else if( errno!=EISDIR && isReadWrite ){
6085 /* Failed to open the file for read/write access. Try read-only. */
6086 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
6087 openFlags &= ~(O_RDWR|O_CREAT);
6088 flags |= SQLITE_OPEN_READONLY;
6089 openFlags |= O_RDONLY;
6090 isReadonly = 1;
6091 fd = robust_open(zName, openFlags, openMode);
6092 }
dan08da86a2009-08-21 17:18:03 +00006093 }
6094 if( fd<0 ){
dana688ca52018-01-10 11:56:03 +00006095 int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
6096 if( rc==SQLITE_OK ) rc = rc2;
dane946c392009-08-22 11:39:46 +00006097 goto open_finished;
dan08da86a2009-08-21 17:18:03 +00006098 }
drhac7c3ac2012-02-11 19:23:48 +00006099
drh1116b172019-09-25 10:36:31 +00006100 /* The owner of the rollback journal or WAL file should always be the
6101 ** same as the owner of the database file. Try to ensure that this is
6102 ** the case. The chown() system call will be a no-op if the current
6103 ** process lacks root privileges, be we should at least try. Without
6104 ** this step, if a root process opens a database file, it can leave
6105 ** behinds a journal/WAL that is owned by root and hence make the
6106 ** database inaccessible to unprivileged processes.
6107 **
drhedf8a7b2019-09-25 11:49:36 +00006108 ** If openMode==0, then that means uid and gid are not set correctly
drh1116b172019-09-25 10:36:31 +00006109 ** (probably because SQLite is configured to use 8+3 filename mode) and
6110 ** in that case we do not want to attempt the chown().
drhac7c3ac2012-02-11 19:23:48 +00006111 */
drhedf8a7b2019-09-25 11:49:36 +00006112 if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
drh6226ca22015-11-24 15:06:28 +00006113 robustFchown(fd, uid, gid);
drhac7c3ac2012-02-11 19:23:48 +00006114 }
danielk1977b4b47412007-08-17 15:53:36 +00006115 }
dan08da86a2009-08-21 17:18:03 +00006116 assert( fd>=0 );
dan08da86a2009-08-21 17:18:03 +00006117 if( pOutFlags ){
6118 *pOutFlags = flags;
6119 }
6120
drhc68886b2017-08-18 16:09:52 +00006121 if( p->pPreallocatedUnused ){
6122 p->pPreallocatedUnused->fd = fd;
drh55220a62019-08-06 20:55:06 +00006123 p->pPreallocatedUnused->flags =
6124 flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
dane946c392009-08-22 11:39:46 +00006125 }
6126
danielk1977b4b47412007-08-17 15:53:36 +00006127 if( isDelete ){
drh6c7d5c52008-11-21 20:32:33 +00006128#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006129 zPath = zName;
drh0bdbc902014-06-16 18:35:06 +00006130#elif defined(SQLITE_UNLINK_AFTER_CLOSE)
6131 zPath = sqlite3_mprintf("%s", zName);
6132 if( zPath==0 ){
6133 robust_close(p, fd, __LINE__);
mistachkinfad30392016-02-13 23:43:46 +00006134 return SQLITE_NOMEM_BKPT;
drh0bdbc902014-06-16 18:35:06 +00006135 }
chw97185482008-11-17 08:05:31 +00006136#else
drh036ac7f2011-08-08 23:18:05 +00006137 osUnlink(zName);
chw97185482008-11-17 08:05:31 +00006138#endif
danielk1977b4b47412007-08-17 15:53:36 +00006139 }
drh41022642008-11-21 00:24:42 +00006140#if SQLITE_ENABLE_LOCKING_STYLE
6141 else{
dan08da86a2009-08-21 17:18:03 +00006142 p->openFlags = openFlags;
drh08c6d442009-02-09 17:34:07 +00006143 }
6144#endif
drh7ed97b92010-01-20 13:07:21 +00006145
6146#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
drh7ed97b92010-01-20 13:07:21 +00006147 if( fstatfs(fd, &fsInfo) == -1 ){
drh4bf66fd2015-02-19 02:43:02 +00006148 storeLastErrno(p, errno);
drh0e9365c2011-03-02 02:08:13 +00006149 robust_close(p, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006150 return SQLITE_IOERR_ACCESS;
6151 }
6152 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
6153 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6154 }
drh4bf66fd2015-02-19 02:43:02 +00006155 if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
6156 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
6157 }
drh7ed97b92010-01-20 13:07:21 +00006158#endif
drhc02a43a2012-01-10 23:18:38 +00006159
6160 /* Set up appropriate ctrlFlags */
6161 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
6162 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
drh86151e82015-12-08 14:37:16 +00006163 noLock = eType!=SQLITE_OPEN_MAIN_DB;
drhc02a43a2012-01-10 23:18:38 +00006164 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
drha803a2c2017-12-13 20:02:29 +00006165 if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
drhc02a43a2012-01-10 23:18:38 +00006166 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
6167
drh7ed97b92010-01-20 13:07:21 +00006168#if SQLITE_ENABLE_LOCKING_STYLE
aswiftaebf4132008-11-21 00:10:35 +00006169#if SQLITE_PREFER_PROXY_LOCKING
drh7ed97b92010-01-20 13:07:21 +00006170 isAutoProxy = 1;
6171#endif
6172 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
aswiftaebf4132008-11-21 00:10:35 +00006173 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
6174 int useProxy = 0;
6175
dan08da86a2009-08-21 17:18:03 +00006176 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
6177 ** never use proxy, NULL means use proxy for non-local files only. */
aswiftaebf4132008-11-21 00:10:35 +00006178 if( envforce!=NULL ){
6179 useProxy = atoi(envforce)>0;
6180 }else{
aswiftaebf4132008-11-21 00:10:35 +00006181 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
6182 }
6183 if( useProxy ){
drhc02a43a2012-01-10 23:18:38 +00006184 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
aswiftaebf4132008-11-21 00:10:35 +00006185 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00006186 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
drh7ed97b92010-01-20 13:07:21 +00006187 if( rc!=SQLITE_OK ){
6188 /* Use unixClose to clean up the resources added in fillInUnixFile
6189 ** and clear all the structure's references. Specifically,
6190 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
6191 */
6192 unixClose(pFile);
6193 return rc;
6194 }
aswiftaebf4132008-11-21 00:10:35 +00006195 }
dane946c392009-08-22 11:39:46 +00006196 goto open_finished;
aswiftaebf4132008-11-21 00:10:35 +00006197 }
6198 }
6199#endif
6200
dan3ed0f1c2017-09-14 21:12:07 +00006201 assert( zPath==0 || zPath[0]=='/'
6202 || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
6203 );
drhc02a43a2012-01-10 23:18:38 +00006204 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
6205
dane946c392009-08-22 11:39:46 +00006206open_finished:
6207 if( rc!=SQLITE_OK ){
drhc68886b2017-08-18 16:09:52 +00006208 sqlite3_free(p->pPreallocatedUnused);
dane946c392009-08-22 11:39:46 +00006209 }
6210 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006211}
6212
dane946c392009-08-22 11:39:46 +00006213
danielk1977b4b47412007-08-17 15:53:36 +00006214/*
danielk1977fee2d252007-08-18 10:59:19 +00006215** Delete the file at zPath. If the dirSync argument is true, fsync()
6216** the directory after deleting the file.
danielk1977b4b47412007-08-17 15:53:36 +00006217*/
drh6b9d6dd2008-12-03 19:34:47 +00006218static int unixDelete(
6219 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
6220 const char *zPath, /* Name of file to be deleted */
6221 int dirSync /* If true, fsync() directory after deleting file */
6222){
danielk1977fee2d252007-08-18 10:59:19 +00006223 int rc = SQLITE_OK;
danielk1977397d65f2008-11-19 11:35:39 +00006224 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006225 SimulateIOError(return SQLITE_IOERR_DELETE);
dan9fc5b4a2012-11-09 20:17:26 +00006226 if( osUnlink(zPath)==(-1) ){
drhbd945542014-08-13 11:39:42 +00006227 if( errno==ENOENT
6228#if OS_VXWORKS
drh19541f32014-09-01 13:37:55 +00006229 || osAccess(zPath,0)!=0
drhbd945542014-08-13 11:39:42 +00006230#endif
6231 ){
dan9fc5b4a2012-11-09 20:17:26 +00006232 rc = SQLITE_IOERR_DELETE_NOENT;
6233 }else{
drhb4308162012-11-09 21:40:02 +00006234 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
dan9fc5b4a2012-11-09 20:17:26 +00006235 }
drhb4308162012-11-09 21:40:02 +00006236 return rc;
drh5d4feff2010-07-14 01:45:22 +00006237 }
danielk1977d39fa702008-10-16 13:27:40 +00006238#ifndef SQLITE_DISABLE_DIRSYNC
drhe3495192012-01-05 16:07:30 +00006239 if( (dirSync & 1)!=0 ){
danielk1977fee2d252007-08-18 10:59:19 +00006240 int fd;
drh90315a22011-08-10 01:52:12 +00006241 rc = osOpenDirectory(zPath, &fd);
danielk1977fee2d252007-08-18 10:59:19 +00006242 if( rc==SQLITE_OK ){
drh6d258992016-02-04 09:48:12 +00006243 if( full_fsync(fd,0,0) ){
dane18d4952011-02-21 11:46:24 +00006244 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
danielk1977fee2d252007-08-18 10:59:19 +00006245 }
drh0e9365c2011-03-02 02:08:13 +00006246 robust_close(0, fd, __LINE__);
drhacb6b282015-11-26 10:37:05 +00006247 }else{
6248 assert( rc==SQLITE_CANTOPEN );
drh1ee6f742011-08-23 20:11:32 +00006249 rc = SQLITE_OK;
danielk1977fee2d252007-08-18 10:59:19 +00006250 }
6251 }
danielk1977d138dd82008-10-15 16:02:48 +00006252#endif
danielk1977fee2d252007-08-18 10:59:19 +00006253 return rc;
danielk1977b4b47412007-08-17 15:53:36 +00006254}
6255
danielk197790949c22007-08-17 16:50:38 +00006256/*
mistachkin48864df2013-03-21 21:20:32 +00006257** Test the existence of or access permissions of file zPath. The
danielk197790949c22007-08-17 16:50:38 +00006258** test performed depends on the value of flags:
6259**
6260** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
6261** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
6262** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
6263**
6264** Otherwise return 0.
6265*/
danielk1977861f7452008-06-05 11:39:11 +00006266static int unixAccess(
drh6b9d6dd2008-12-03 19:34:47 +00006267 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
6268 const char *zPath, /* Path of the file to examine */
6269 int flags, /* What do we want to learn about the zPath file? */
6270 int *pResOut /* Write result boolean here */
danielk1977861f7452008-06-05 11:39:11 +00006271){
danielk1977397d65f2008-11-19 11:35:39 +00006272 UNUSED_PARAMETER(NotUsed);
danielk1977861f7452008-06-05 11:39:11 +00006273 SimulateIOError( return SQLITE_IOERR_ACCESS; );
drhd260b5b2015-11-25 18:03:33 +00006274 assert( pResOut!=0 );
danielk1977b4b47412007-08-17 15:53:36 +00006275
drhc398c652019-11-22 00:42:01 +00006276 /* The spec says there are three possible values for flags. But only
6277 ** two of them are actually used */
6278 assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
drhd260b5b2015-11-25 18:03:33 +00006279
6280 if( flags==SQLITE_ACCESS_EXISTS ){
dan83acd422010-06-18 11:10:06 +00006281 struct stat buf;
drh96e8eeb2019-12-26 00:56:50 +00006282 *pResOut = 0==osStat(zPath, &buf) &&
drh09bee572019-12-27 13:30:46 +00006283 (!S_ISREG(buf.st_mode) || buf.st_size>0);
drh0933aad2019-11-18 17:46:38 +00006284 }else{
drhc398c652019-11-22 00:42:01 +00006285 *pResOut = osAccess(zPath, W_OK|R_OK)==0;
dan83acd422010-06-18 11:10:06 +00006286 }
danielk1977861f7452008-06-05 11:39:11 +00006287 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006288}
6289
danielk1977b4b47412007-08-17 15:53:36 +00006290/*
danielk1977b4b47412007-08-17 15:53:36 +00006291**
danielk1977b4b47412007-08-17 15:53:36 +00006292*/
dane88ec182016-01-25 17:04:48 +00006293static int mkFullPathname(
dancaf6b152016-01-25 18:05:49 +00006294 const char *zPath, /* Input path */
6295 char *zOut, /* Output buffer */
dane88ec182016-01-25 17:04:48 +00006296 int nOut /* Allocated size of buffer zOut */
danielk1977adfb9b02007-09-17 07:02:56 +00006297){
dancaf6b152016-01-25 18:05:49 +00006298 int nPath = sqlite3Strlen30(zPath);
6299 int iOff = 0;
6300 if( zPath[0]!='/' ){
6301 if( osGetcwd(zOut, nOut-2)==0 ){
dane18d4952011-02-21 11:46:24 +00006302 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006303 }
dancaf6b152016-01-25 18:05:49 +00006304 iOff = sqlite3Strlen30(zOut);
6305 zOut[iOff++] = '/';
danielk1977b4b47412007-08-17 15:53:36 +00006306 }
dan23496702016-01-26 13:56:42 +00006307 if( (iOff+nPath+1)>nOut ){
6308 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
6309 ** even if it returns an error. */
6310 zOut[iOff] = '\0';
6311 return SQLITE_CANTOPEN_BKPT;
6312 }
dancaf6b152016-01-25 18:05:49 +00006313 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
danielk1977b4b47412007-08-17 15:53:36 +00006314 return SQLITE_OK;
danielk1977b4b47412007-08-17 15:53:36 +00006315}
6316
dane88ec182016-01-25 17:04:48 +00006317/*
6318** Turn a relative pathname into a full pathname. The relative path
6319** is stored as a nul-terminated string in the buffer pointed to by
6320** zPath.
6321**
6322** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
6323** (in this case, MAX_PATHNAME bytes). The full-path is written to
6324** this buffer before returning.
6325*/
6326static int unixFullPathname(
6327 sqlite3_vfs *pVfs, /* Pointer to vfs object */
6328 const char *zPath, /* Possibly relative input path */
6329 int nOut, /* Size of output buffer in bytes */
6330 char *zOut /* Output buffer */
6331){
danaf1b36b2016-01-25 18:43:05 +00006332#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
dancaf6b152016-01-25 18:05:49 +00006333 return mkFullPathname(zPath, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006334#else
6335 int rc = SQLITE_OK;
6336 int nByte;
drhc398c652019-11-22 00:42:01 +00006337 int nLink = 0; /* Number of symbolic links followed so far */
dane88ec182016-01-25 17:04:48 +00006338 const char *zIn = zPath; /* Input path for each iteration of loop */
6339 char *zDel = 0;
6340
6341 assert( pVfs->mxPathname==MAX_PATHNAME );
6342 UNUSED_PARAMETER(pVfs);
6343
6344 /* It's odd to simulate an io-error here, but really this is just
6345 ** using the io-error infrastructure to test that SQLite handles this
6346 ** function failing. This function could fail if, for example, the
6347 ** current working directory has been unlinked.
6348 */
6349 SimulateIOError( return SQLITE_ERROR );
6350
6351 do {
6352
dancaf6b152016-01-25 18:05:49 +00006353 /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
6354 ** link, or false otherwise. */
6355 int bLink = 0;
6356 struct stat buf;
6357 if( osLstat(zIn, &buf)!=0 ){
6358 if( errno!=ENOENT ){
danaf1b36b2016-01-25 18:43:05 +00006359 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
dane88ec182016-01-25 17:04:48 +00006360 }
dane88ec182016-01-25 17:04:48 +00006361 }else{
dancaf6b152016-01-25 18:05:49 +00006362 bLink = S_ISLNK(buf.st_mode);
6363 }
6364
6365 if( bLink ){
drhc398c652019-11-22 00:42:01 +00006366 nLink++;
dane88ec182016-01-25 17:04:48 +00006367 if( zDel==0 ){
6368 zDel = sqlite3_malloc(nOut);
mistachkinfad30392016-02-13 23:43:46 +00006369 if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
drhc398c652019-11-22 00:42:01 +00006370 }else if( nLink>=SQLITE_MAX_SYMLINKS ){
dancaf6b152016-01-25 18:05:49 +00006371 rc = SQLITE_CANTOPEN_BKPT;
dane88ec182016-01-25 17:04:48 +00006372 }
dancaf6b152016-01-25 18:05:49 +00006373
6374 if( rc==SQLITE_OK ){
6375 nByte = osReadlink(zIn, zDel, nOut-1);
6376 if( nByte<0 ){
6377 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
dan23496702016-01-26 13:56:42 +00006378 }else{
6379 if( zDel[0]!='/' ){
6380 int n;
6381 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
6382 if( nByte+n+1>nOut ){
6383 rc = SQLITE_CANTOPEN_BKPT;
6384 }else{
6385 memmove(&zDel[n], zDel, nByte+1);
6386 memcpy(zDel, zIn, n);
6387 nByte += n;
6388 }
dancaf6b152016-01-25 18:05:49 +00006389 }
6390 zDel[nByte] = '\0';
6391 }
6392 }
6393
6394 zIn = zDel;
dane88ec182016-01-25 17:04:48 +00006395 }
6396
dan23496702016-01-26 13:56:42 +00006397 assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
6398 if( rc==SQLITE_OK && zIn!=zOut ){
dancaf6b152016-01-25 18:05:49 +00006399 rc = mkFullPathname(zIn, zOut, nOut);
dane88ec182016-01-25 17:04:48 +00006400 }
dancaf6b152016-01-25 18:05:49 +00006401 if( bLink==0 ) break;
6402 zIn = zOut;
6403 }while( rc==SQLITE_OK );
dane88ec182016-01-25 17:04:48 +00006404
6405 sqlite3_free(zDel);
drhc398c652019-11-22 00:42:01 +00006406 if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
dane88ec182016-01-25 17:04:48 +00006407 return rc;
danaf1b36b2016-01-25 18:43:05 +00006408#endif /* HAVE_READLINK && HAVE_LSTAT */
dane88ec182016-01-25 17:04:48 +00006409}
6410
drh0ccebe72005-06-07 22:22:50 +00006411
drh761df872006-12-21 01:29:22 +00006412#ifndef SQLITE_OMIT_LOAD_EXTENSION
6413/*
6414** Interfaces for opening a shared library, finding entry points
6415** within the shared library, and closing the shared library.
6416*/
6417#include <dlfcn.h>
danielk1977397d65f2008-11-19 11:35:39 +00006418static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
6419 UNUSED_PARAMETER(NotUsed);
drh761df872006-12-21 01:29:22 +00006420 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
6421}
danielk197795c8a542007-09-01 06:51:27 +00006422
6423/*
6424** SQLite calls this function immediately after a call to unixDlSym() or
6425** unixDlOpen() fails (returns a null pointer). If a more detailed error
6426** message is available, it is written to zBufOut. If no error message
6427** is available, zBufOut is left unmodified and SQLite uses a default
6428** error message.
6429*/
danielk1977397d65f2008-11-19 11:35:39 +00006430static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
dan32390532010-11-29 18:36:22 +00006431 const char *zErr;
danielk1977397d65f2008-11-19 11:35:39 +00006432 UNUSED_PARAMETER(NotUsed);
drh6c7d5c52008-11-21 20:32:33 +00006433 unixEnterMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006434 zErr = dlerror();
6435 if( zErr ){
drh153c62c2007-08-24 03:51:33 +00006436 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
danielk1977b4b47412007-08-17 15:53:36 +00006437 }
drh6c7d5c52008-11-21 20:32:33 +00006438 unixLeaveMutex();
danielk1977b4b47412007-08-17 15:53:36 +00006439}
drh1875f7a2008-12-08 18:19:17 +00006440static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
6441 /*
6442 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
6443 ** cast into a pointer to a function. And yet the library dlsym() routine
6444 ** returns a void* which is really a pointer to a function. So how do we
6445 ** use dlsym() with -pedantic-errors?
6446 **
6447 ** Variable x below is defined to be a pointer to a function taking
6448 ** parameters void* and const char* and returning a pointer to a function.
6449 ** We initialize x by assigning it a pointer to the dlsym() function.
6450 ** (That assignment requires a cast.) Then we call the function that
6451 ** x points to.
6452 **
6453 ** This work-around is unlikely to work correctly on any system where
6454 ** you really cannot cast a function pointer into void*. But then, on the
6455 ** other hand, dlsym() will not work on such a system either, so we have
6456 ** not really lost anything.
6457 */
6458 void (*(*x)(void*,const char*))(void);
danielk1977397d65f2008-11-19 11:35:39 +00006459 UNUSED_PARAMETER(NotUsed);
drh1875f7a2008-12-08 18:19:17 +00006460 x = (void(*(*)(void*,const char*))(void))dlsym;
6461 return (*x)(p, zSym);
drh761df872006-12-21 01:29:22 +00006462}
danielk1977397d65f2008-11-19 11:35:39 +00006463static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
6464 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006465 dlclose(pHandle);
drh761df872006-12-21 01:29:22 +00006466}
danielk1977b4b47412007-08-17 15:53:36 +00006467#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
6468 #define unixDlOpen 0
6469 #define unixDlError 0
6470 #define unixDlSym 0
6471 #define unixDlClose 0
6472#endif
6473
6474/*
danielk197790949c22007-08-17 16:50:38 +00006475** Write nBuf bytes of random data to the supplied buffer zBuf.
drhbbd42a62004-05-22 17:41:58 +00006476*/
danielk1977397d65f2008-11-19 11:35:39 +00006477static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
6478 UNUSED_PARAMETER(NotUsed);
danielk197700e13612008-11-17 19:18:54 +00006479 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
danielk197790949c22007-08-17 16:50:38 +00006480
drhbbd42a62004-05-22 17:41:58 +00006481 /* We have to initialize zBuf to prevent valgrind from reporting
6482 ** errors. The reports issued by valgrind are incorrect - we would
6483 ** prefer that the randomness be increased by making use of the
6484 ** uninitialized space in zBuf - but valgrind errors tend to worry
6485 ** some users. Rather than argue, it seems easier just to initialize
6486 ** the whole array and silence valgrind, even if that means less randomness
6487 ** in the random seed.
6488 **
6489 ** When testing, initializing zBuf[] to zero is all we do. That means
drhf1a221e2006-01-15 17:27:17 +00006490 ** that we always use the same random number sequence. This makes the
drhbbd42a62004-05-22 17:41:58 +00006491 ** tests repeatable.
6492 */
danielk1977b4b47412007-08-17 15:53:36 +00006493 memset(zBuf, 0, nBuf);
drh5ac93652015-03-21 20:59:43 +00006494 randomnessPid = osGetpid(0);
drh6a412b82015-04-30 12:31:49 +00006495#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
drhbbd42a62004-05-22 17:41:58 +00006496 {
drhb00d8622014-01-01 15:18:36 +00006497 int fd, got;
drhad4f1e52011-03-04 15:43:57 +00006498 fd = robust_open("/dev/urandom", O_RDONLY, 0);
drh842b8642005-01-21 17:53:17 +00006499 if( fd<0 ){
drh07397232006-01-06 14:46:46 +00006500 time_t t;
6501 time(&t);
danielk197790949c22007-08-17 16:50:38 +00006502 memcpy(zBuf, &t, sizeof(t));
drhb00d8622014-01-01 15:18:36 +00006503 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
6504 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
6505 nBuf = sizeof(t) + sizeof(randomnessPid);
drh842b8642005-01-21 17:53:17 +00006506 }else{
drhc18b4042012-02-10 03:10:27 +00006507 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
drh0e9365c2011-03-02 02:08:13 +00006508 robust_close(0, fd, __LINE__);
drh842b8642005-01-21 17:53:17 +00006509 }
drhbbd42a62004-05-22 17:41:58 +00006510 }
6511#endif
drh72cbd072008-10-14 17:58:38 +00006512 return nBuf;
drhbbd42a62004-05-22 17:41:58 +00006513}
6514
danielk1977b4b47412007-08-17 15:53:36 +00006515
drhbbd42a62004-05-22 17:41:58 +00006516/*
6517** Sleep for a little while. Return the amount of time slept.
danielk1977b4b47412007-08-17 15:53:36 +00006518** The argument is the number of microseconds we want to sleep.
drh4a50aac2007-08-23 02:47:53 +00006519** The return value is the number of microseconds of sleep actually
6520** requested from the underlying operating system, a number which
6521** might be greater than or equal to the argument, but not less
6522** than the argument.
drhbbd42a62004-05-22 17:41:58 +00006523*/
danielk1977397d65f2008-11-19 11:35:39 +00006524static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
drh6c7d5c52008-11-21 20:32:33 +00006525#if OS_VXWORKS
chw97185482008-11-17 08:05:31 +00006526 struct timespec sp;
6527
6528 sp.tv_sec = microseconds / 1000000;
6529 sp.tv_nsec = (microseconds % 1000000) * 1000;
6530 nanosleep(&sp, NULL);
drhd43fe202009-03-01 22:29:20 +00006531 UNUSED_PARAMETER(NotUsed);
danielk1977397d65f2008-11-19 11:35:39 +00006532 return microseconds;
6533#elif defined(HAVE_USLEEP) && HAVE_USLEEP
danielk1977b4b47412007-08-17 15:53:36 +00006534 usleep(microseconds);
drhd43fe202009-03-01 22:29:20 +00006535 UNUSED_PARAMETER(NotUsed);
danielk1977b4b47412007-08-17 15:53:36 +00006536 return microseconds;
drhbbd42a62004-05-22 17:41:58 +00006537#else
danielk1977b4b47412007-08-17 15:53:36 +00006538 int seconds = (microseconds+999999)/1000000;
6539 sleep(seconds);
drhd43fe202009-03-01 22:29:20 +00006540 UNUSED_PARAMETER(NotUsed);
drh4a50aac2007-08-23 02:47:53 +00006541 return seconds*1000000;
drha3fad6f2006-01-18 14:06:37 +00006542#endif
drh88f474a2006-01-02 20:00:12 +00006543}
6544
6545/*
drh6b9d6dd2008-12-03 19:34:47 +00006546** The following variable, if set to a non-zero value, is interpreted as
6547** the number of seconds since 1970 and is used to set the result of
6548** sqlite3OsCurrentTime() during testing.
drhbbd42a62004-05-22 17:41:58 +00006549*/
6550#ifdef SQLITE_TEST
drh6b9d6dd2008-12-03 19:34:47 +00006551int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
drhbbd42a62004-05-22 17:41:58 +00006552#endif
6553
6554/*
drhb7e8ea22010-05-03 14:32:30 +00006555** Find the current time (in Universal Coordinated Time). Write into *piNow
6556** the current time and date as a Julian Day number times 86_400_000. In
6557** other words, write into *piNow the number of milliseconds since the Julian
6558** epoch of noon in Greenwich on November 24, 4714 B.C according to the
6559** proleptic Gregorian calendar.
6560**
drh31702252011-10-12 23:13:43 +00006561** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
6562** cannot be found.
drhb7e8ea22010-05-03 14:32:30 +00006563*/
6564static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
6565 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
drh31702252011-10-12 23:13:43 +00006566 int rc = SQLITE_OK;
drhb7e8ea22010-05-03 14:32:30 +00006567#if defined(NO_GETTOD)
6568 time_t t;
6569 time(&t);
dan15eac4e2010-11-22 17:26:07 +00006570 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
drhb7e8ea22010-05-03 14:32:30 +00006571#elif OS_VXWORKS
6572 struct timespec sNow;
6573 clock_gettime(CLOCK_REALTIME, &sNow);
6574 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
6575#else
6576 struct timeval sNow;
drh970942e2015-11-25 23:13:14 +00006577 (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
6578 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
drhb7e8ea22010-05-03 14:32:30 +00006579#endif
6580
6581#ifdef SQLITE_TEST
6582 if( sqlite3_current_time ){
6583 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
6584 }
6585#endif
6586 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006587 return rc;
drhb7e8ea22010-05-03 14:32:30 +00006588}
6589
drhc3dfa5e2016-01-22 19:44:03 +00006590#ifndef SQLITE_OMIT_DEPRECATED
drhb7e8ea22010-05-03 14:32:30 +00006591/*
drhbbd42a62004-05-22 17:41:58 +00006592** Find the current time (in Universal Coordinated Time). Write the
6593** current time and date as a Julian Day number into *prNow and
6594** return 0. Return 1 if the time and date cannot be found.
6595*/
danielk1977397d65f2008-11-19 11:35:39 +00006596static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
drhb87a6662011-10-13 01:01:14 +00006597 sqlite3_int64 i = 0;
drh31702252011-10-12 23:13:43 +00006598 int rc;
drhff828942010-06-26 21:34:06 +00006599 UNUSED_PARAMETER(NotUsed);
drh31702252011-10-12 23:13:43 +00006600 rc = unixCurrentTimeInt64(0, &i);
drh0dcb0a72010-05-03 18:22:52 +00006601 *prNow = i/86400000.0;
drh31702252011-10-12 23:13:43 +00006602 return rc;
drhbbd42a62004-05-22 17:41:58 +00006603}
drh5337dac2015-11-25 15:15:03 +00006604#else
6605# define unixCurrentTime 0
6606#endif
danielk1977b4b47412007-08-17 15:53:36 +00006607
drh6b9d6dd2008-12-03 19:34:47 +00006608/*
drh1b9f2142016-03-17 16:01:23 +00006609** The xGetLastError() method is designed to return a better
6610** low-level error message when operating-system problems come up
6611** during SQLite operation. Only the integer return code is currently
6612** used.
drh6b9d6dd2008-12-03 19:34:47 +00006613*/
danielk1977397d65f2008-11-19 11:35:39 +00006614static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
6615 UNUSED_PARAMETER(NotUsed);
6616 UNUSED_PARAMETER(NotUsed2);
6617 UNUSED_PARAMETER(NotUsed3);
drh1b9f2142016-03-17 16:01:23 +00006618 return errno;
danielk1977bcb97fe2008-06-06 15:49:29 +00006619}
6620
drhf2424c52010-04-26 00:04:55 +00006621
6622/*
drh734c9862008-11-28 15:37:20 +00006623************************ End of sqlite3_vfs methods ***************************
6624******************************************************************************/
6625
drh715ff302008-12-03 22:32:44 +00006626/******************************************************************************
6627************************** Begin Proxy Locking ********************************
6628**
6629** Proxy locking is a "uber-locking-method" in this sense: It uses the
6630** other locking methods on secondary lock files. Proxy locking is a
6631** meta-layer over top of the primitive locking implemented above. For
6632** this reason, the division that implements of proxy locking is deferred
6633** until late in the file (here) after all of the other I/O methods have
6634** been defined - so that the primitive locking methods are available
6635** as services to help with the implementation of proxy locking.
6636**
6637****
6638**
6639** The default locking schemes in SQLite use byte-range locks on the
6640** database file to coordinate safe, concurrent access by multiple readers
6641** and writers [http://sqlite.org/lockingv3.html]. The five file locking
6642** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
6643** as POSIX read & write locks over fixed set of locations (via fsctl),
6644** on AFP and SMB only exclusive byte-range locks are available via fsctl
6645** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
6646** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
6647** address in the shared range is taken for a SHARED lock, the entire
6648** shared range is taken for an EXCLUSIVE lock):
6649**
drhf2f105d2012-08-20 15:53:54 +00006650** PENDING_BYTE 0x40000000
drh715ff302008-12-03 22:32:44 +00006651** RESERVED_BYTE 0x40000001
6652** SHARED_RANGE 0x40000002 -> 0x40000200
6653**
6654** This works well on the local file system, but shows a nearly 100x
6655** slowdown in read performance on AFP because the AFP client disables
6656** the read cache when byte-range locks are present. Enabling the read
6657** cache exposes a cache coherency problem that is present on all OS X
6658** supported network file systems. NFS and AFP both observe the
6659** close-to-open semantics for ensuring cache coherency
6660** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
6661** address the requirements for concurrent database access by multiple
6662** readers and writers
6663** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
6664**
6665** To address the performance and cache coherency issues, proxy file locking
6666** changes the way database access is controlled by limiting access to a
6667** single host at a time and moving file locks off of the database file
6668** and onto a proxy file on the local file system.
6669**
6670**
6671** Using proxy locks
6672** -----------------
6673**
6674** C APIs
6675**
drh4bf66fd2015-02-19 02:43:02 +00006676** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
drh715ff302008-12-03 22:32:44 +00006677** <proxy_path> | ":auto:");
drh4bf66fd2015-02-19 02:43:02 +00006678** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
6679** &<proxy_path>);
drh715ff302008-12-03 22:32:44 +00006680**
6681**
6682** SQL pragmas
6683**
6684** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
6685** PRAGMA [database.]lock_proxy_file
6686**
6687** Specifying ":auto:" means that if there is a conch file with a matching
6688** host ID in it, the proxy path in the conch file will be used, otherwise
6689** a proxy path based on the user's temp dir
6690** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
6691** actual proxy file name is generated from the name and path of the
6692** database file. For example:
6693**
6694** For database path "/Users/me/foo.db"
6695** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
6696**
6697** Once a lock proxy is configured for a database connection, it can not
6698** be removed, however it may be switched to a different proxy path via
6699** the above APIs (assuming the conch file is not being held by another
6700** connection or process).
6701**
6702**
6703** How proxy locking works
6704** -----------------------
6705**
6706** Proxy file locking relies primarily on two new supporting files:
6707**
6708** * conch file to limit access to the database file to a single host
6709** at a time
6710**
6711** * proxy file to act as a proxy for the advisory locks normally
6712** taken on the database
6713**
6714** The conch file - to use a proxy file, sqlite must first "hold the conch"
6715** by taking an sqlite-style shared lock on the conch file, reading the
6716** contents and comparing the host's unique host ID (see below) and lock
6717** proxy path against the values stored in the conch. The conch file is
6718** stored in the same directory as the database file and the file name
6719** is patterned after the database file name as ".<databasename>-conch".
peter.d.reid60ec9142014-09-06 16:39:46 +00006720** If the conch file does not exist, or its contents do not match the
drh715ff302008-12-03 22:32:44 +00006721** host ID and/or proxy path, then the lock is escalated to an exclusive
6722** lock and the conch file contents is updated with the host ID and proxy
6723** path and the lock is downgraded to a shared lock again. If the conch
6724** is held by another process (with a shared lock), the exclusive lock
6725** will fail and SQLITE_BUSY is returned.
6726**
6727** The proxy file - a single-byte file used for all advisory file locks
6728** normally taken on the database file. This allows for safe sharing
6729** of the database file for multiple readers and writers on the same
6730** host (the conch ensures that they all use the same local lock file).
6731**
drh715ff302008-12-03 22:32:44 +00006732** Requesting the lock proxy does not immediately take the conch, it is
6733** only taken when the first request to lock database file is made.
6734** This matches the semantics of the traditional locking behavior, where
6735** opening a connection to a database file does not take a lock on it.
6736** The shared lock and an open file descriptor are maintained until
6737** the connection to the database is closed.
6738**
6739** The proxy file and the lock file are never deleted so they only need
6740** to be created the first time they are used.
6741**
6742** Configuration options
6743** ---------------------
6744**
6745** SQLITE_PREFER_PROXY_LOCKING
6746**
6747** Database files accessed on non-local file systems are
6748** automatically configured for proxy locking, lock files are
6749** named automatically using the same logic as
6750** PRAGMA lock_proxy_file=":auto:"
6751**
6752** SQLITE_PROXY_DEBUG
6753**
6754** Enables the logging of error messages during host id file
6755** retrieval and creation
6756**
drh715ff302008-12-03 22:32:44 +00006757** LOCKPROXYDIR
6758**
6759** Overrides the default directory used for lock proxy files that
6760** are named automatically via the ":auto:" setting
6761**
6762** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
6763**
6764** Permissions to use when creating a directory for storing the
6765** lock proxy files, only used when LOCKPROXYDIR is not set.
6766**
6767**
6768** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
6769** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
6770** force proxy locking to be used for every database file opened, and 0
6771** will force automatic proxy locking to be disabled for all database
drh4bf66fd2015-02-19 02:43:02 +00006772** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
drh715ff302008-12-03 22:32:44 +00006773** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
6774*/
6775
6776/*
6777** Proxy locking is only available on MacOSX
6778*/
drhd2cb50b2009-01-09 21:41:17 +00006779#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
drh715ff302008-12-03 22:32:44 +00006780
drh715ff302008-12-03 22:32:44 +00006781/*
6782** The proxyLockingContext has the path and file structures for the remote
6783** and local proxy files in it
6784*/
6785typedef struct proxyLockingContext proxyLockingContext;
6786struct proxyLockingContext {
6787 unixFile *conchFile; /* Open conch file */
6788 char *conchFilePath; /* Name of the conch file */
6789 unixFile *lockProxy; /* Open proxy lock file */
6790 char *lockProxyPath; /* Name of the proxy lock file */
6791 char *dbPath; /* Name of the open file */
drh7ed97b92010-01-20 13:07:21 +00006792 int conchHeld; /* 1 if the conch is held, -1 if lockless */
drh4bf66fd2015-02-19 02:43:02 +00006793 int nFails; /* Number of conch taking failures */
drh715ff302008-12-03 22:32:44 +00006794 void *oldLockingContext; /* Original lockingcontext to restore on close */
6795 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
6796};
6797
drh7ed97b92010-01-20 13:07:21 +00006798/*
6799** The proxy lock file path for the database at dbPath is written into lPath,
6800** which must point to valid, writable memory large enough for a maxLen length
6801** file path.
drh715ff302008-12-03 22:32:44 +00006802*/
drh715ff302008-12-03 22:32:44 +00006803static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
6804 int len;
6805 int dbLen;
6806 int i;
6807
6808#ifdef LOCKPROXYDIR
6809 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
6810#else
6811# ifdef _CS_DARWIN_USER_TEMP_DIR
6812 {
drh7ed97b92010-01-20 13:07:21 +00006813 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
drh308c2a52010-05-14 11:30:18 +00006814 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006815 lPath, errno, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006816 return SQLITE_IOERR_LOCK;
drh715ff302008-12-03 22:32:44 +00006817 }
drh7ed97b92010-01-20 13:07:21 +00006818 len = strlcat(lPath, "sqliteplocks", maxLen);
drh715ff302008-12-03 22:32:44 +00006819 }
6820# else
6821 len = strlcpy(lPath, "/tmp/", maxLen);
6822# endif
6823#endif
6824
6825 if( lPath[len-1]!='/' ){
6826 len = strlcat(lPath, "/", maxLen);
6827 }
6828
6829 /* transform the db path to a unique cache name */
drhea678832008-12-10 19:26:22 +00006830 dbLen = (int)strlen(dbPath);
drh0ab216a2010-07-02 17:10:40 +00006831 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
drh715ff302008-12-03 22:32:44 +00006832 char c = dbPath[i];
6833 lPath[i+len] = (c=='/')?'_':c;
6834 }
6835 lPath[i+len]='\0';
6836 strlcat(lPath, ":auto:", maxLen);
drh5ac93652015-03-21 20:59:43 +00006837 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00006838 return SQLITE_OK;
6839}
6840
drh7ed97b92010-01-20 13:07:21 +00006841/*
6842 ** Creates the lock file and any missing directories in lockPath
6843 */
6844static int proxyCreateLockPath(const char *lockPath){
6845 int i, len;
6846 char buf[MAXPATHLEN];
6847 int start = 0;
6848
6849 assert(lockPath!=NULL);
6850 /* try to create all the intermediate directories */
6851 len = (int)strlen(lockPath);
6852 buf[0] = lockPath[0];
6853 for( i=1; i<len; i++ ){
6854 if( lockPath[i] == '/' && (i - start > 0) ){
6855 /* only mkdir if leaf dir != "." or "/" or ".." */
6856 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
6857 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
6858 buf[i]='\0';
drh9ef6bc42011-11-04 02:24:02 +00006859 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
drh7ed97b92010-01-20 13:07:21 +00006860 int err=errno;
6861 if( err!=EEXIST ) {
drh308c2a52010-05-14 11:30:18 +00006862 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
drh7ed97b92010-01-20 13:07:21 +00006863 "'%s' proxy lock path=%s pid=%d\n",
drh5ac93652015-03-21 20:59:43 +00006864 buf, strerror(err), lockPath, osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006865 return err;
6866 }
6867 }
6868 }
6869 start=i+1;
6870 }
6871 buf[i] = lockPath[i];
6872 }
drh62aaa6c2015-11-21 17:27:42 +00006873 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00006874 return 0;
6875}
6876
drh715ff302008-12-03 22:32:44 +00006877/*
6878** Create a new VFS file descriptor (stored in memory obtained from
6879** sqlite3_malloc) and open the file named "path" in the file descriptor.
6880**
6881** The caller is responsible not only for closing the file descriptor
6882** but also for freeing the memory associated with the file descriptor.
6883*/
drh7ed97b92010-01-20 13:07:21 +00006884static int proxyCreateUnixFile(
6885 const char *path, /* path for the new unixFile */
6886 unixFile **ppFile, /* unixFile created and returned by ref */
6887 int islockfile /* if non zero missing dirs will be created */
6888) {
6889 int fd = -1;
drh715ff302008-12-03 22:32:44 +00006890 unixFile *pNew;
6891 int rc = SQLITE_OK;
drhc398c652019-11-22 00:42:01 +00006892 int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
drh715ff302008-12-03 22:32:44 +00006893 sqlite3_vfs dummyVfs;
drh7ed97b92010-01-20 13:07:21 +00006894 int terrno = 0;
6895 UnixUnusedFd *pUnused = NULL;
drh715ff302008-12-03 22:32:44 +00006896
drh7ed97b92010-01-20 13:07:21 +00006897 /* 1. first try to open/create the file
6898 ** 2. if that fails, and this is a lock file (not-conch), try creating
6899 ** the parent directories and then try again.
6900 ** 3. if that fails, try to open the file read-only
6901 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
6902 */
6903 pUnused = findReusableFd(path, openFlags);
6904 if( pUnused ){
6905 fd = pUnused->fd;
6906 }else{
drhf3cdcdc2015-04-29 16:50:28 +00006907 pUnused = sqlite3_malloc64(sizeof(*pUnused));
drh7ed97b92010-01-20 13:07:21 +00006908 if( !pUnused ){
mistachkinfad30392016-02-13 23:43:46 +00006909 return SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006910 }
6911 }
6912 if( fd<0 ){
drh8c815d12012-02-13 20:16:37 +00006913 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006914 terrno = errno;
6915 if( fd<0 && errno==ENOENT && islockfile ){
6916 if( proxyCreateLockPath(path) == SQLITE_OK ){
drh8c815d12012-02-13 20:16:37 +00006917 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006918 }
6919 }
6920 }
6921 if( fd<0 ){
drhc398c652019-11-22 00:42:01 +00006922 openFlags = O_RDONLY | O_NOFOLLOW;
drh8c815d12012-02-13 20:16:37 +00006923 fd = robust_open(path, openFlags, 0);
drh7ed97b92010-01-20 13:07:21 +00006924 terrno = errno;
6925 }
6926 if( fd<0 ){
6927 if( islockfile ){
6928 return SQLITE_BUSY;
6929 }
6930 switch (terrno) {
6931 case EACCES:
6932 return SQLITE_PERM;
6933 case EIO:
6934 return SQLITE_IOERR_LOCK; /* even though it is the conch */
6935 default:
drh9978c972010-02-23 17:36:32 +00006936 return SQLITE_CANTOPEN_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006937 }
6938 }
6939
drhf3cdcdc2015-04-29 16:50:28 +00006940 pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
drh7ed97b92010-01-20 13:07:21 +00006941 if( pNew==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00006942 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00006943 goto end_create_proxy;
drh715ff302008-12-03 22:32:44 +00006944 }
6945 memset(pNew, 0, sizeof(unixFile));
drh7ed97b92010-01-20 13:07:21 +00006946 pNew->openFlags = openFlags;
dan211fb082011-04-01 09:04:36 +00006947 memset(&dummyVfs, 0, sizeof(dummyVfs));
drh1875f7a2008-12-08 18:19:17 +00006948 dummyVfs.pAppData = (void*)&autolockIoFinder;
dan211fb082011-04-01 09:04:36 +00006949 dummyVfs.zName = "dummy";
drh7ed97b92010-01-20 13:07:21 +00006950 pUnused->fd = fd;
6951 pUnused->flags = openFlags;
drhc68886b2017-08-18 16:09:52 +00006952 pNew->pPreallocatedUnused = pUnused;
drh7ed97b92010-01-20 13:07:21 +00006953
drhc02a43a2012-01-10 23:18:38 +00006954 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
drh7ed97b92010-01-20 13:07:21 +00006955 if( rc==SQLITE_OK ){
6956 *ppFile = pNew;
6957 return SQLITE_OK;
drh715ff302008-12-03 22:32:44 +00006958 }
drh7ed97b92010-01-20 13:07:21 +00006959end_create_proxy:
drh0e9365c2011-03-02 02:08:13 +00006960 robust_close(pNew, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00006961 sqlite3_free(pNew);
6962 sqlite3_free(pUnused);
drh715ff302008-12-03 22:32:44 +00006963 return rc;
6964}
6965
drh7ed97b92010-01-20 13:07:21 +00006966#ifdef SQLITE_TEST
6967/* simulate multiple hosts by creating unique hostid file paths */
6968int sqlite3_hostid_num = 0;
6969#endif
6970
6971#define PROXY_HOSTIDLEN 16 /* conch file host id length */
6972
drhe4079e12019-09-27 16:33:27 +00006973#if HAVE_GETHOSTUUID
drh0ab216a2010-07-02 17:10:40 +00006974/* Not always defined in the headers as it ought to be */
6975extern int gethostuuid(uuid_t id, const struct timespec *wait);
drh6bca6512015-04-13 23:05:28 +00006976#endif
drh0ab216a2010-07-02 17:10:40 +00006977
drh7ed97b92010-01-20 13:07:21 +00006978/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
6979** bytes of writable memory.
6980*/
6981static int proxyGetHostID(unsigned char *pHostID, int *pError){
drh7ed97b92010-01-20 13:07:21 +00006982 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
6983 memset(pHostID, 0, PROXY_HOSTIDLEN);
drhe4079e12019-09-27 16:33:27 +00006984#if HAVE_GETHOSTUUID
drh29ecd8a2010-12-21 00:16:40 +00006985 {
drh4bf66fd2015-02-19 02:43:02 +00006986 struct timespec timeout = {1, 0}; /* 1 sec timeout */
drh29ecd8a2010-12-21 00:16:40 +00006987 if( gethostuuid(pHostID, &timeout) ){
6988 int err = errno;
6989 if( pError ){
6990 *pError = err;
6991 }
6992 return SQLITE_IOERR;
drh7ed97b92010-01-20 13:07:21 +00006993 }
drh7ed97b92010-01-20 13:07:21 +00006994 }
drh3d4435b2011-08-26 20:55:50 +00006995#else
6996 UNUSED_PARAMETER(pError);
drhe8b0c9b2010-09-25 14:13:17 +00006997#endif
drh7ed97b92010-01-20 13:07:21 +00006998#ifdef SQLITE_TEST
6999 /* simulate multiple hosts by creating unique hostid file paths */
7000 if( sqlite3_hostid_num != 0){
7001 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
7002 }
7003#endif
7004
7005 return SQLITE_OK;
7006}
7007
7008/* The conch file contains the header, host id and lock file path
7009 */
7010#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
7011#define PROXY_HEADERLEN 1 /* conch file header length */
7012#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
7013#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
7014
7015/*
7016** Takes an open conch file, copies the contents to a new path and then moves
7017** it back. The newly created file's file descriptor is assigned to the
7018** conch file structure and finally the original conch file descriptor is
7019** closed. Returns zero if successful.
7020*/
7021static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
7022 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7023 unixFile *conchFile = pCtx->conchFile;
7024 char tPath[MAXPATHLEN];
7025 char buf[PROXY_MAXCONCHLEN];
7026 char *cPath = pCtx->conchFilePath;
7027 size_t readLen = 0;
7028 size_t pathLen = 0;
7029 char errmsg[64] = "";
7030 int fd = -1;
7031 int rc = -1;
drh0ab216a2010-07-02 17:10:40 +00007032 UNUSED_PARAMETER(myHostID);
drh7ed97b92010-01-20 13:07:21 +00007033
7034 /* create a new path by replace the trailing '-conch' with '-break' */
7035 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
7036 if( pathLen>MAXPATHLEN || pathLen<6 ||
7037 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
dan0cb3a1e2010-11-29 17:55:18 +00007038 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
drh7ed97b92010-01-20 13:07:21 +00007039 goto end_breaklock;
7040 }
7041 /* read the conch content */
drhe562be52011-03-02 18:01:10 +00007042 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007043 if( readLen<PROXY_PATHINDEX ){
dan0cb3a1e2010-11-29 17:55:18 +00007044 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
drh7ed97b92010-01-20 13:07:21 +00007045 goto end_breaklock;
7046 }
7047 /* write it out to the temporary break file */
drhc398c652019-11-22 00:42:01 +00007048 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
drh7ed97b92010-01-20 13:07:21 +00007049 if( fd<0 ){
dan0cb3a1e2010-11-29 17:55:18 +00007050 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007051 goto end_breaklock;
7052 }
drhe562be52011-03-02 18:01:10 +00007053 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
dan0cb3a1e2010-11-29 17:55:18 +00007054 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007055 goto end_breaklock;
7056 }
7057 if( rename(tPath, cPath) ){
dan0cb3a1e2010-11-29 17:55:18 +00007058 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
drh7ed97b92010-01-20 13:07:21 +00007059 goto end_breaklock;
7060 }
7061 rc = 0;
7062 fprintf(stderr, "broke stale lock on %s\n", cPath);
drh0e9365c2011-03-02 02:08:13 +00007063 robust_close(pFile, conchFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007064 conchFile->h = fd;
7065 conchFile->openFlags = O_RDWR | O_CREAT;
7066
7067end_breaklock:
7068 if( rc ){
7069 if( fd>=0 ){
drh036ac7f2011-08-08 23:18:05 +00007070 osUnlink(tPath);
drh0e9365c2011-03-02 02:08:13 +00007071 robust_close(pFile, fd, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007072 }
7073 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
7074 }
7075 return rc;
7076}
7077
7078/* Take the requested lock on the conch file and break a stale lock if the
7079** host id matches.
7080*/
7081static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
7082 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7083 unixFile *conchFile = pCtx->conchFile;
7084 int rc = SQLITE_OK;
7085 int nTries = 0;
7086 struct timespec conchModTime;
7087
drh3d4435b2011-08-26 20:55:50 +00007088 memset(&conchModTime, 0, sizeof(conchModTime));
drh7ed97b92010-01-20 13:07:21 +00007089 do {
7090 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7091 nTries ++;
7092 if( rc==SQLITE_BUSY ){
7093 /* If the lock failed (busy):
7094 * 1st try: get the mod time of the conch, wait 0.5s and try again.
7095 * 2nd try: fail if the mod time changed or host id is different, wait
7096 * 10 sec and try again
7097 * 3rd try: break the lock unless the mod time has changed.
7098 */
7099 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007100 if( osFstat(conchFile->h, &buf) ){
drh4bf66fd2015-02-19 02:43:02 +00007101 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007102 return SQLITE_IOERR_LOCK;
7103 }
7104
7105 if( nTries==1 ){
7106 conchModTime = buf.st_mtimespec;
7107 usleep(500000); /* wait 0.5 sec and try the lock again*/
7108 continue;
7109 }
7110
7111 assert( nTries>1 );
7112 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
7113 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
7114 return SQLITE_BUSY;
7115 }
7116
7117 if( nTries==2 ){
7118 char tBuf[PROXY_MAXCONCHLEN];
drhe562be52011-03-02 18:01:10 +00007119 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
drh7ed97b92010-01-20 13:07:21 +00007120 if( len<0 ){
drh4bf66fd2015-02-19 02:43:02 +00007121 storeLastErrno(pFile, errno);
drh7ed97b92010-01-20 13:07:21 +00007122 return SQLITE_IOERR_LOCK;
7123 }
7124 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
7125 /* don't break the lock if the host id doesn't match */
7126 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
7127 return SQLITE_BUSY;
7128 }
7129 }else{
7130 /* don't break the lock on short read or a version mismatch */
7131 return SQLITE_BUSY;
7132 }
7133 usleep(10000000); /* wait 10 sec and try the lock again */
7134 continue;
7135 }
7136
7137 assert( nTries==3 );
7138 if( 0==proxyBreakConchLock(pFile, myHostID) ){
7139 rc = SQLITE_OK;
7140 if( lockType==EXCLUSIVE_LOCK ){
drhe6d41732015-02-21 00:49:00 +00007141 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
drh7ed97b92010-01-20 13:07:21 +00007142 }
7143 if( !rc ){
7144 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
7145 }
7146 }
7147 }
7148 } while( rc==SQLITE_BUSY && nTries<3 );
7149
7150 return rc;
7151}
7152
7153/* Takes the conch by taking a shared lock and read the contents conch, if
drh715ff302008-12-03 22:32:44 +00007154** lockPath is non-NULL, the host ID and lock file path must match. A NULL
7155** lockPath means that the lockPath in the conch file will be used if the
7156** host IDs match, or a new lock path will be generated automatically
7157** and written to the conch file.
7158*/
7159static int proxyTakeConch(unixFile *pFile){
7160 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7161
drh7ed97b92010-01-20 13:07:21 +00007162 if( pCtx->conchHeld!=0 ){
drh715ff302008-12-03 22:32:44 +00007163 return SQLITE_OK;
7164 }else{
7165 unixFile *conchFile = pCtx->conchFile;
drh7ed97b92010-01-20 13:07:21 +00007166 uuid_t myHostID;
7167 int pError = 0;
7168 char readBuf[PROXY_MAXCONCHLEN];
drh715ff302008-12-03 22:32:44 +00007169 char lockPath[MAXPATHLEN];
drh7ed97b92010-01-20 13:07:21 +00007170 char *tempLockPath = NULL;
drh715ff302008-12-03 22:32:44 +00007171 int rc = SQLITE_OK;
drh7ed97b92010-01-20 13:07:21 +00007172 int createConch = 0;
7173 int hostIdMatch = 0;
7174 int readLen = 0;
7175 int tryOldLockPath = 0;
7176 int forceNewLockPath = 0;
7177
drh308c2a52010-05-14 11:30:18 +00007178 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
drh91eb93c2015-03-03 19:56:20 +00007179 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007180 osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007181
drh7ed97b92010-01-20 13:07:21 +00007182 rc = proxyGetHostID(myHostID, &pError);
7183 if( (rc&0xff)==SQLITE_IOERR ){
drh4bf66fd2015-02-19 02:43:02 +00007184 storeLastErrno(pFile, pError);
drh7ed97b92010-01-20 13:07:21 +00007185 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007186 }
drh7ed97b92010-01-20 13:07:21 +00007187 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
drh715ff302008-12-03 22:32:44 +00007188 if( rc!=SQLITE_OK ){
7189 goto end_takeconch;
7190 }
drh7ed97b92010-01-20 13:07:21 +00007191 /* read the existing conch file */
7192 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
7193 if( readLen<0 ){
7194 /* I/O error: lastErrno set by seekAndRead */
drh4bf66fd2015-02-19 02:43:02 +00007195 storeLastErrno(pFile, conchFile->lastErrno);
drh7ed97b92010-01-20 13:07:21 +00007196 rc = SQLITE_IOERR_READ;
7197 goto end_takeconch;
7198 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
7199 readBuf[0]!=(char)PROXY_CONCHVERSION ){
7200 /* a short read or version format mismatch means we need to create a new
7201 ** conch file.
7202 */
7203 createConch = 1;
7204 }
7205 /* if the host id matches and the lock path already exists in the conch
7206 ** we'll try to use the path there, if we can't open that path, we'll
7207 ** retry with a new auto-generated path
7208 */
7209 do { /* in case we need to try again for an :auto: named lock file */
7210
7211 if( !createConch && !forceNewLockPath ){
7212 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
7213 PROXY_HOSTIDLEN);
7214 /* if the conch has data compare the contents */
7215 if( !pCtx->lockProxyPath ){
7216 /* for auto-named local lock file, just check the host ID and we'll
7217 ** use the local lock file path that's already in there
7218 */
7219 if( hostIdMatch ){
7220 size_t pathLen = (readLen - PROXY_PATHINDEX);
7221
7222 if( pathLen>=MAXPATHLEN ){
7223 pathLen=MAXPATHLEN-1;
7224 }
7225 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
7226 lockPath[pathLen] = 0;
7227 tempLockPath = lockPath;
7228 tryOldLockPath = 1;
7229 /* create a copy of the lock path if the conch is taken */
7230 goto end_takeconch;
7231 }
7232 }else if( hostIdMatch
7233 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
7234 readLen-PROXY_PATHINDEX)
7235 ){
7236 /* conch host and lock path match */
7237 goto end_takeconch;
drh715ff302008-12-03 22:32:44 +00007238 }
drh7ed97b92010-01-20 13:07:21 +00007239 }
7240
7241 /* if the conch isn't writable and doesn't match, we can't take it */
7242 if( (conchFile->openFlags&O_RDWR) == 0 ){
7243 rc = SQLITE_BUSY;
drh715ff302008-12-03 22:32:44 +00007244 goto end_takeconch;
7245 }
drh7ed97b92010-01-20 13:07:21 +00007246
7247 /* either the conch didn't match or we need to create a new one */
drh715ff302008-12-03 22:32:44 +00007248 if( !pCtx->lockProxyPath ){
drh7ed97b92010-01-20 13:07:21 +00007249 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
7250 tempLockPath = lockPath;
7251 /* create a copy of the lock path _only_ if the conch is taken */
drh715ff302008-12-03 22:32:44 +00007252 }
drh7ed97b92010-01-20 13:07:21 +00007253
7254 /* update conch with host and path (this will fail if other process
7255 ** has a shared lock already), if the host id matches, use the big
7256 ** stick.
drh715ff302008-12-03 22:32:44 +00007257 */
drh7ed97b92010-01-20 13:07:21 +00007258 futimes(conchFile->h, NULL);
7259 if( hostIdMatch && !createConch ){
drh8af6c222010-05-14 12:43:01 +00007260 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
drh7ed97b92010-01-20 13:07:21 +00007261 /* We are trying for an exclusive lock but another thread in this
7262 ** same process is still holding a shared lock. */
7263 rc = SQLITE_BUSY;
7264 } else {
7265 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007266 }
drh715ff302008-12-03 22:32:44 +00007267 }else{
drh4bf66fd2015-02-19 02:43:02 +00007268 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
drh715ff302008-12-03 22:32:44 +00007269 }
drh7ed97b92010-01-20 13:07:21 +00007270 if( rc==SQLITE_OK ){
7271 char writeBuffer[PROXY_MAXCONCHLEN];
7272 int writeSize = 0;
7273
7274 writeBuffer[0] = (char)PROXY_CONCHVERSION;
7275 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
7276 if( pCtx->lockProxyPath!=NULL ){
drh4bf66fd2015-02-19 02:43:02 +00007277 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
7278 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007279 }else{
7280 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
7281 }
7282 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
drhff812312011-02-23 13:33:46 +00007283 robust_ftruncate(conchFile->h, writeSize);
drh7ed97b92010-01-20 13:07:21 +00007284 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
drh6d258992016-02-04 09:48:12 +00007285 full_fsync(conchFile->h,0,0);
drh7ed97b92010-01-20 13:07:21 +00007286 /* If we created a new conch file (not just updated the contents of a
7287 ** valid conch file), try to match the permissions of the database
7288 */
7289 if( rc==SQLITE_OK && createConch ){
7290 struct stat buf;
drh99ab3b12011-03-02 15:09:07 +00007291 int err = osFstat(pFile->h, &buf);
drh7ed97b92010-01-20 13:07:21 +00007292 if( err==0 ){
7293 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
7294 S_IROTH|S_IWOTH);
7295 /* try to match the database file R/W permissions, ignore failure */
7296#ifndef SQLITE_PROXY_DEBUG
drhe562be52011-03-02 18:01:10 +00007297 osFchmod(conchFile->h, cmode);
drh7ed97b92010-01-20 13:07:21 +00007298#else
drhff812312011-02-23 13:33:46 +00007299 do{
drhe562be52011-03-02 18:01:10 +00007300 rc = osFchmod(conchFile->h, cmode);
drhff812312011-02-23 13:33:46 +00007301 }while( rc==(-1) && errno==EINTR );
7302 if( rc!=0 ){
drh7ed97b92010-01-20 13:07:21 +00007303 int code = errno;
7304 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
7305 cmode, code, strerror(code));
7306 } else {
7307 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
7308 }
7309 }else{
7310 int code = errno;
7311 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
7312 err, code, strerror(code));
7313#endif
7314 }
drh715ff302008-12-03 22:32:44 +00007315 }
7316 }
drh7ed97b92010-01-20 13:07:21 +00007317 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
7318
7319 end_takeconch:
drh308c2a52010-05-14 11:30:18 +00007320 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
drh7ed97b92010-01-20 13:07:21 +00007321 if( rc==SQLITE_OK && pFile->openFlags ){
drh3d4435b2011-08-26 20:55:50 +00007322 int fd;
drh7ed97b92010-01-20 13:07:21 +00007323 if( pFile->h>=0 ){
drhe84009f2011-03-02 17:54:32 +00007324 robust_close(pFile, pFile->h, __LINE__);
drh7ed97b92010-01-20 13:07:21 +00007325 }
7326 pFile->h = -1;
drh8c815d12012-02-13 20:16:37 +00007327 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
drh308c2a52010-05-14 11:30:18 +00007328 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
drh7ed97b92010-01-20 13:07:21 +00007329 if( fd>=0 ){
7330 pFile->h = fd;
7331 }else{
drh9978c972010-02-23 17:36:32 +00007332 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
drh7ed97b92010-01-20 13:07:21 +00007333 during locking */
7334 }
7335 }
7336 if( rc==SQLITE_OK && !pCtx->lockProxy ){
7337 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
7338 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
7339 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
7340 /* we couldn't create the proxy lock file with the old lock file path
7341 ** so try again via auto-naming
7342 */
7343 forceNewLockPath = 1;
7344 tryOldLockPath = 0;
dan2b0ef472010-02-16 12:18:47 +00007345 continue; /* go back to the do {} while start point, try again */
drh7ed97b92010-01-20 13:07:21 +00007346 }
7347 }
7348 if( rc==SQLITE_OK ){
7349 /* Need to make a copy of path if we extracted the value
7350 ** from the conch file or the path was allocated on the stack
7351 */
7352 if( tempLockPath ){
7353 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
7354 if( !pCtx->lockProxyPath ){
mistachkinfad30392016-02-13 23:43:46 +00007355 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007356 }
7357 }
7358 }
7359 if( rc==SQLITE_OK ){
7360 pCtx->conchHeld = 1;
7361
7362 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
7363 afpLockingContext *afpCtx;
7364 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
7365 afpCtx->dbPath = pCtx->lockProxyPath;
7366 }
7367 } else {
7368 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7369 }
drh308c2a52010-05-14 11:30:18 +00007370 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
7371 rc==SQLITE_OK?"ok":"failed"));
drh7ed97b92010-01-20 13:07:21 +00007372 return rc;
drh308c2a52010-05-14 11:30:18 +00007373 } while (1); /* in case we need to retry the :auto: lock file -
7374 ** we should never get here except via the 'continue' call. */
drh715ff302008-12-03 22:32:44 +00007375 }
7376}
7377
7378/*
7379** If pFile holds a lock on a conch file, then release that lock.
7380*/
7381static int proxyReleaseConch(unixFile *pFile){
drh1c5bb4d2010-05-10 17:29:28 +00007382 int rc = SQLITE_OK; /* Subroutine return code */
drh715ff302008-12-03 22:32:44 +00007383 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
7384 unixFile *conchFile; /* Name of the conch file */
7385
7386 pCtx = (proxyLockingContext *)pFile->lockingContext;
7387 conchFile = pCtx->conchFile;
drh308c2a52010-05-14 11:30:18 +00007388 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
drh715ff302008-12-03 22:32:44 +00007389 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
drh5ac93652015-03-21 20:59:43 +00007390 osGetpid(0)));
drh7ed97b92010-01-20 13:07:21 +00007391 if( pCtx->conchHeld>0 ){
7392 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
7393 }
drh715ff302008-12-03 22:32:44 +00007394 pCtx->conchHeld = 0;
drh308c2a52010-05-14 11:30:18 +00007395 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
7396 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007397 return rc;
7398}
7399
7400/*
7401** Given the name of a database file, compute the name of its conch file.
drhf3cdcdc2015-04-29 16:50:28 +00007402** Store the conch filename in memory obtained from sqlite3_malloc64().
drh715ff302008-12-03 22:32:44 +00007403** Make *pConchPath point to the new name. Return SQLITE_OK on success
7404** or SQLITE_NOMEM if unable to obtain memory.
7405**
7406** The caller is responsible for ensuring that the allocated memory
7407** space is eventually freed.
7408**
7409** *pConchPath is set to NULL if a memory allocation error occurs.
7410*/
7411static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
7412 int i; /* Loop counter */
drhea678832008-12-10 19:26:22 +00007413 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
drh715ff302008-12-03 22:32:44 +00007414 char *conchPath; /* buffer in which to construct conch name */
7415
7416 /* Allocate space for the conch filename and initialize the name to
7417 ** the name of the original database file. */
drhf3cdcdc2015-04-29 16:50:28 +00007418 *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
drh715ff302008-12-03 22:32:44 +00007419 if( conchPath==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007420 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007421 }
7422 memcpy(conchPath, dbPath, len+1);
7423
7424 /* now insert a "." before the last / character */
7425 for( i=(len-1); i>=0; i-- ){
7426 if( conchPath[i]=='/' ){
7427 i++;
7428 break;
7429 }
7430 }
7431 conchPath[i]='.';
7432 while ( i<len ){
7433 conchPath[i+1]=dbPath[i];
7434 i++;
7435 }
7436
7437 /* append the "-conch" suffix to the file */
7438 memcpy(&conchPath[i+1], "-conch", 7);
drhea678832008-12-10 19:26:22 +00007439 assert( (int)strlen(conchPath) == len+7 );
drh715ff302008-12-03 22:32:44 +00007440
7441 return SQLITE_OK;
7442}
7443
7444
7445/* Takes a fully configured proxy locking-style unix file and switches
7446** the local lock file path
7447*/
7448static int switchLockProxyPath(unixFile *pFile, const char *path) {
7449 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7450 char *oldPath = pCtx->lockProxyPath;
7451 int rc = SQLITE_OK;
7452
drh308c2a52010-05-14 11:30:18 +00007453 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007454 return SQLITE_BUSY;
7455 }
7456
7457 /* nothing to do if the path is NULL, :auto: or matches the existing path */
7458 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
7459 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
7460 return SQLITE_OK;
7461 }else{
7462 unixFile *lockProxy = pCtx->lockProxy;
7463 pCtx->lockProxy=NULL;
7464 pCtx->conchHeld = 0;
7465 if( lockProxy!=NULL ){
7466 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
7467 if( rc ) return rc;
7468 sqlite3_free(lockProxy);
7469 }
7470 sqlite3_free(oldPath);
7471 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
7472 }
7473
7474 return rc;
7475}
7476
7477/*
7478** pFile is a file that has been opened by a prior xOpen call. dbPath
7479** is a string buffer at least MAXPATHLEN+1 characters in size.
7480**
7481** This routine find the filename associated with pFile and writes it
7482** int dbPath.
7483*/
7484static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
drhd2cb50b2009-01-09 21:41:17 +00007485#if defined(__APPLE__)
drh715ff302008-12-03 22:32:44 +00007486 if( pFile->pMethod == &afpIoMethods ){
7487 /* afp style keeps a reference to the db path in the filePath field
7488 ** of the struct */
drhea678832008-12-10 19:26:22 +00007489 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh4bf66fd2015-02-19 02:43:02 +00007490 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
7491 MAXPATHLEN);
drh7ed97b92010-01-20 13:07:21 +00007492 } else
drh715ff302008-12-03 22:32:44 +00007493#endif
7494 if( pFile->pMethod == &dotlockIoMethods ){
7495 /* dot lock style uses the locking context to store the dot lock
7496 ** file path */
7497 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
7498 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
7499 }else{
7500 /* all other styles use the locking context to store the db file path */
7501 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
drh7ed97b92010-01-20 13:07:21 +00007502 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
drh715ff302008-12-03 22:32:44 +00007503 }
7504 return SQLITE_OK;
7505}
7506
7507/*
7508** Takes an already filled in unix file and alters it so all file locking
7509** will be performed on the local proxy lock file. The following fields
7510** are preserved in the locking context so that they can be restored and
7511** the unix structure properly cleaned up at close time:
7512** ->lockingContext
7513** ->pMethod
7514*/
7515static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
7516 proxyLockingContext *pCtx;
7517 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
7518 char *lockPath=NULL;
7519 int rc = SQLITE_OK;
7520
drh308c2a52010-05-14 11:30:18 +00007521 if( pFile->eFileLock!=NO_LOCK ){
drh715ff302008-12-03 22:32:44 +00007522 return SQLITE_BUSY;
7523 }
7524 proxyGetDbPathForUnixFile(pFile, dbPath);
7525 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
7526 lockPath=NULL;
7527 }else{
7528 lockPath=(char *)path;
7529 }
7530
drh308c2a52010-05-14 11:30:18 +00007531 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
drh5ac93652015-03-21 20:59:43 +00007532 (lockPath ? lockPath : ":auto:"), osGetpid(0)));
drh715ff302008-12-03 22:32:44 +00007533
drhf3cdcdc2015-04-29 16:50:28 +00007534 pCtx = sqlite3_malloc64( sizeof(*pCtx) );
drh715ff302008-12-03 22:32:44 +00007535 if( pCtx==0 ){
mistachkinfad30392016-02-13 23:43:46 +00007536 return SQLITE_NOMEM_BKPT;
drh715ff302008-12-03 22:32:44 +00007537 }
7538 memset(pCtx, 0, sizeof(*pCtx));
7539
7540 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
7541 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007542 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
7543 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
7544 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
7545 ** (c) the file system is read-only, then enable no-locking access.
7546 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
7547 ** that openFlags will have only one of O_RDONLY or O_RDWR.
7548 */
7549 struct statfs fsInfo;
7550 struct stat conchInfo;
7551 int goLockless = 0;
7552
drh99ab3b12011-03-02 15:09:07 +00007553 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
drh7ed97b92010-01-20 13:07:21 +00007554 int err = errno;
7555 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
7556 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
7557 }
7558 }
7559 if( goLockless ){
7560 pCtx->conchHeld = -1; /* read only FS/ lockless */
7561 rc = SQLITE_OK;
7562 }
7563 }
drh715ff302008-12-03 22:32:44 +00007564 }
7565 if( rc==SQLITE_OK && lockPath ){
7566 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
7567 }
7568
7569 if( rc==SQLITE_OK ){
drh7ed97b92010-01-20 13:07:21 +00007570 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
7571 if( pCtx->dbPath==NULL ){
mistachkinfad30392016-02-13 23:43:46 +00007572 rc = SQLITE_NOMEM_BKPT;
drh7ed97b92010-01-20 13:07:21 +00007573 }
7574 }
7575 if( rc==SQLITE_OK ){
drh715ff302008-12-03 22:32:44 +00007576 /* all memory is allocated, proxys are created and assigned,
7577 ** switch the locking context and pMethod then return.
7578 */
drh715ff302008-12-03 22:32:44 +00007579 pCtx->oldLockingContext = pFile->lockingContext;
7580 pFile->lockingContext = pCtx;
7581 pCtx->pOldMethod = pFile->pMethod;
7582 pFile->pMethod = &proxyIoMethods;
7583 }else{
7584 if( pCtx->conchFile ){
drh7ed97b92010-01-20 13:07:21 +00007585 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
drh715ff302008-12-03 22:32:44 +00007586 sqlite3_free(pCtx->conchFile);
7587 }
drhd56b1212010-08-11 06:14:15 +00007588 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007589 sqlite3_free(pCtx->conchFilePath);
7590 sqlite3_free(pCtx);
7591 }
drh308c2a52010-05-14 11:30:18 +00007592 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
7593 (rc==SQLITE_OK ? "ok" : "failed")));
drh715ff302008-12-03 22:32:44 +00007594 return rc;
7595}
7596
7597
7598/*
7599** This routine handles sqlite3_file_control() calls that are specific
7600** to proxy locking.
7601*/
7602static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
7603 switch( op ){
drh4bf66fd2015-02-19 02:43:02 +00007604 case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007605 unixFile *pFile = (unixFile*)id;
7606 if( pFile->pMethod == &proxyIoMethods ){
7607 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
7608 proxyTakeConch(pFile);
7609 if( pCtx->lockProxyPath ){
7610 *(const char **)pArg = pCtx->lockProxyPath;
7611 }else{
7612 *(const char **)pArg = ":auto: (not held)";
7613 }
7614 } else {
7615 *(const char **)pArg = NULL;
7616 }
7617 return SQLITE_OK;
7618 }
drh4bf66fd2015-02-19 02:43:02 +00007619 case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
drh715ff302008-12-03 22:32:44 +00007620 unixFile *pFile = (unixFile*)id;
7621 int rc = SQLITE_OK;
7622 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
7623 if( pArg==NULL || (const char *)pArg==0 ){
7624 if( isProxyStyle ){
drh4bf66fd2015-02-19 02:43:02 +00007625 /* turn off proxy locking - not supported. If support is added for
7626 ** switching proxy locking mode off then it will need to fail if
7627 ** the journal mode is WAL mode.
7628 */
drh715ff302008-12-03 22:32:44 +00007629 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
7630 }else{
7631 /* turn off proxy locking - already off - NOOP */
7632 rc = SQLITE_OK;
7633 }
7634 }else{
7635 const char *proxyPath = (const char *)pArg;
7636 if( isProxyStyle ){
7637 proxyLockingContext *pCtx =
7638 (proxyLockingContext*)pFile->lockingContext;
7639 if( !strcmp(pArg, ":auto:")
7640 || (pCtx->lockProxyPath &&
7641 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
7642 ){
7643 rc = SQLITE_OK;
7644 }else{
7645 rc = switchLockProxyPath(pFile, proxyPath);
7646 }
7647 }else{
7648 /* turn on proxy file locking */
7649 rc = proxyTransformUnixFile(pFile, proxyPath);
7650 }
7651 }
7652 return rc;
7653 }
7654 default: {
7655 assert( 0 ); /* The call assures that only valid opcodes are sent */
7656 }
7657 }
drh8616cff2019-07-13 16:15:23 +00007658 /*NOTREACHED*/ assert(0);
drh715ff302008-12-03 22:32:44 +00007659 return SQLITE_ERROR;
7660}
7661
7662/*
7663** Within this division (the proxying locking implementation) the procedures
7664** above this point are all utilities. The lock-related methods of the
7665** proxy-locking sqlite3_io_method object follow.
7666*/
7667
7668
7669/*
7670** This routine checks if there is a RESERVED lock held on the specified
7671** file by this or any other process. If such a lock is held, set *pResOut
7672** to a non-zero value otherwise *pResOut is set to zero. The return value
7673** is set to SQLITE_OK unless an I/O error occurs during lock checking.
7674*/
7675static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
7676 unixFile *pFile = (unixFile*)id;
7677 int rc = proxyTakeConch(pFile);
7678 if( rc==SQLITE_OK ){
7679 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007680 if( pCtx->conchHeld>0 ){
7681 unixFile *proxy = pCtx->lockProxy;
7682 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
7683 }else{ /* conchHeld < 0 is lockless */
7684 pResOut=0;
7685 }
drh715ff302008-12-03 22:32:44 +00007686 }
7687 return rc;
7688}
7689
7690/*
drh308c2a52010-05-14 11:30:18 +00007691** Lock the file with the lock specified by parameter eFileLock - one
drh715ff302008-12-03 22:32:44 +00007692** of the following:
7693**
7694** (1) SHARED_LOCK
7695** (2) RESERVED_LOCK
7696** (3) PENDING_LOCK
7697** (4) EXCLUSIVE_LOCK
7698**
7699** Sometimes when requesting one lock state, additional lock states
7700** are inserted in between. The locking might fail on one of the later
7701** transitions leaving the lock state different from what it started but
7702** still short of its goal. The following chart shows the allowed
7703** transitions and the inserted intermediate states:
7704**
7705** UNLOCKED -> SHARED
7706** SHARED -> RESERVED
7707** SHARED -> (PENDING) -> EXCLUSIVE
7708** RESERVED -> (PENDING) -> EXCLUSIVE
7709** PENDING -> EXCLUSIVE
7710**
7711** This routine will only increase a lock. Use the sqlite3OsUnlock()
7712** routine to lower a locking level.
7713*/
drh308c2a52010-05-14 11:30:18 +00007714static int proxyLock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007715 unixFile *pFile = (unixFile*)id;
7716 int rc = proxyTakeConch(pFile);
7717 if( rc==SQLITE_OK ){
7718 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007719 if( pCtx->conchHeld>0 ){
7720 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007721 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
7722 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007723 }else{
7724 /* conchHeld < 0 is lockless */
7725 }
drh715ff302008-12-03 22:32:44 +00007726 }
7727 return rc;
7728}
7729
7730
7731/*
drh308c2a52010-05-14 11:30:18 +00007732** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
drh715ff302008-12-03 22:32:44 +00007733** must be either NO_LOCK or SHARED_LOCK.
7734**
7735** If the locking level of the file descriptor is already at or below
7736** the requested locking level, this routine is a no-op.
7737*/
drh308c2a52010-05-14 11:30:18 +00007738static int proxyUnlock(sqlite3_file *id, int eFileLock) {
drh715ff302008-12-03 22:32:44 +00007739 unixFile *pFile = (unixFile*)id;
7740 int rc = proxyTakeConch(pFile);
7741 if( rc==SQLITE_OK ){
7742 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
drh7ed97b92010-01-20 13:07:21 +00007743 if( pCtx->conchHeld>0 ){
7744 unixFile *proxy = pCtx->lockProxy;
drh308c2a52010-05-14 11:30:18 +00007745 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
7746 pFile->eFileLock = proxy->eFileLock;
drh7ed97b92010-01-20 13:07:21 +00007747 }else{
7748 /* conchHeld < 0 is lockless */
7749 }
drh715ff302008-12-03 22:32:44 +00007750 }
7751 return rc;
7752}
7753
7754/*
7755** Close a file that uses proxy locks.
7756*/
7757static int proxyClose(sqlite3_file *id) {
drha8de1e12015-11-30 00:05:39 +00007758 if( ALWAYS(id) ){
drh715ff302008-12-03 22:32:44 +00007759 unixFile *pFile = (unixFile*)id;
7760 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
7761 unixFile *lockProxy = pCtx->lockProxy;
7762 unixFile *conchFile = pCtx->conchFile;
7763 int rc = SQLITE_OK;
7764
7765 if( lockProxy ){
7766 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
7767 if( rc ) return rc;
7768 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
7769 if( rc ) return rc;
7770 sqlite3_free(lockProxy);
7771 pCtx->lockProxy = 0;
7772 }
7773 if( conchFile ){
7774 if( pCtx->conchHeld ){
7775 rc = proxyReleaseConch(pFile);
7776 if( rc ) return rc;
7777 }
7778 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
7779 if( rc ) return rc;
7780 sqlite3_free(conchFile);
7781 }
drhd56b1212010-08-11 06:14:15 +00007782 sqlite3DbFree(0, pCtx->lockProxyPath);
drh715ff302008-12-03 22:32:44 +00007783 sqlite3_free(pCtx->conchFilePath);
drhd56b1212010-08-11 06:14:15 +00007784 sqlite3DbFree(0, pCtx->dbPath);
drh715ff302008-12-03 22:32:44 +00007785 /* restore the original locking context and pMethod then close it */
7786 pFile->lockingContext = pCtx->oldLockingContext;
7787 pFile->pMethod = pCtx->pOldMethod;
7788 sqlite3_free(pCtx);
7789 return pFile->pMethod->xClose(id);
7790 }
7791 return SQLITE_OK;
7792}
7793
7794
7795
drhd2cb50b2009-01-09 21:41:17 +00007796#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
drh715ff302008-12-03 22:32:44 +00007797/*
7798** The proxy locking style is intended for use with AFP filesystems.
7799** And since AFP is only supported on MacOSX, the proxy locking is also
7800** restricted to MacOSX.
7801**
7802**
7803******************* End of the proxy lock implementation **********************
7804******************************************************************************/
7805
drh734c9862008-11-28 15:37:20 +00007806/*
danielk1977e339d652008-06-28 11:23:00 +00007807** Initialize the operating system interface.
drh734c9862008-11-28 15:37:20 +00007808**
7809** This routine registers all VFS implementations for unix-like operating
7810** systems. This routine, and the sqlite3_os_end() routine that follows,
7811** should be the only routines in this file that are visible from other
7812** files.
drh6b9d6dd2008-12-03 19:34:47 +00007813**
7814** This routine is called once during SQLite initialization and by a
7815** single thread. The memory allocation and mutex subsystems have not
7816** necessarily been initialized when this routine is called, and so they
7817** should not be used.
drh153c62c2007-08-24 03:51:33 +00007818*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007819int sqlite3_os_init(void){
drh6b9d6dd2008-12-03 19:34:47 +00007820 /*
7821 ** The following macro defines an initializer for an sqlite3_vfs object.
drh1875f7a2008-12-08 18:19:17 +00007822 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
7823 ** to the "finder" function. (pAppData is a pointer to a pointer because
7824 ** silly C90 rules prohibit a void* from being cast to a function pointer
7825 ** and so we have to go through the intermediate pointer to avoid problems
7826 ** when compiling with -pedantic-errors on GCC.)
7827 **
7828 ** The FINDER parameter to this macro is the name of the pointer to the
drh6b9d6dd2008-12-03 19:34:47 +00007829 ** finder-function. The finder-function returns a pointer to the
7830 ** sqlite_io_methods object that implements the desired locking
7831 ** behaviors. See the division above that contains the IOMETHODS
7832 ** macro for addition information on finder-functions.
7833 **
7834 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
7835 ** object. But the "autolockIoFinder" available on MacOSX does a little
7836 ** more than that; it looks at the filesystem type that hosts the
7837 ** database file and tries to choose an locking method appropriate for
7838 ** that filesystem time.
danielk1977e339d652008-06-28 11:23:00 +00007839 */
drh7708e972008-11-29 00:56:52 +00007840 #define UNIXVFS(VFSNAME, FINDER) { \
drh99ab3b12011-03-02 15:09:07 +00007841 3, /* iVersion */ \
danielk1977e339d652008-06-28 11:23:00 +00007842 sizeof(unixFile), /* szOsFile */ \
7843 MAX_PATHNAME, /* mxPathname */ \
7844 0, /* pNext */ \
drh7708e972008-11-29 00:56:52 +00007845 VFSNAME, /* zName */ \
drh1875f7a2008-12-08 18:19:17 +00007846 (void*)&FINDER, /* pAppData */ \
danielk1977e339d652008-06-28 11:23:00 +00007847 unixOpen, /* xOpen */ \
7848 unixDelete, /* xDelete */ \
7849 unixAccess, /* xAccess */ \
7850 unixFullPathname, /* xFullPathname */ \
7851 unixDlOpen, /* xDlOpen */ \
7852 unixDlError, /* xDlError */ \
7853 unixDlSym, /* xDlSym */ \
7854 unixDlClose, /* xDlClose */ \
7855 unixRandomness, /* xRandomness */ \
7856 unixSleep, /* xSleep */ \
7857 unixCurrentTime, /* xCurrentTime */ \
drhf2424c52010-04-26 00:04:55 +00007858 unixGetLastError, /* xGetLastError */ \
drhb7e8ea22010-05-03 14:32:30 +00007859 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
drh99ab3b12011-03-02 15:09:07 +00007860 unixSetSystemCall, /* xSetSystemCall */ \
drh1df30962011-03-02 19:06:42 +00007861 unixGetSystemCall, /* xGetSystemCall */ \
7862 unixNextSystemCall, /* xNextSystemCall */ \
danielk1977e339d652008-06-28 11:23:00 +00007863 }
7864
drh6b9d6dd2008-12-03 19:34:47 +00007865 /*
7866 ** All default VFSes for unix are contained in the following array.
7867 **
7868 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
7869 ** by the SQLite core when the VFS is registered. So the following
7870 ** array cannot be const.
7871 */
danielk1977e339d652008-06-28 11:23:00 +00007872 static sqlite3_vfs aVfs[] = {
drhe89b2912015-03-03 20:42:01 +00007873#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007874 UNIXVFS("unix", autolockIoFinder ),
drhe89b2912015-03-03 20:42:01 +00007875#elif OS_VXWORKS
7876 UNIXVFS("unix", vxworksIoFinder ),
drh7708e972008-11-29 00:56:52 +00007877#else
7878 UNIXVFS("unix", posixIoFinder ),
7879#endif
7880 UNIXVFS("unix-none", nolockIoFinder ),
7881 UNIXVFS("unix-dotfile", dotlockIoFinder ),
drha7e61d82011-03-12 17:02:57 +00007882 UNIXVFS("unix-excl", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007883#if OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007884 UNIXVFS("unix-namedsem", semIoFinder ),
drh734c9862008-11-28 15:37:20 +00007885#endif
drhe89b2912015-03-03 20:42:01 +00007886#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
drh7708e972008-11-29 00:56:52 +00007887 UNIXVFS("unix-posix", posixIoFinder ),
drh734c9862008-11-28 15:37:20 +00007888#endif
drhe89b2912015-03-03 20:42:01 +00007889#if SQLITE_ENABLE_LOCKING_STYLE
7890 UNIXVFS("unix-flock", flockIoFinder ),
chw78a13182009-04-07 05:35:03 +00007891#endif
drhd2cb50b2009-01-09 21:41:17 +00007892#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
drh7708e972008-11-29 00:56:52 +00007893 UNIXVFS("unix-afp", afpIoFinder ),
drh7ed97b92010-01-20 13:07:21 +00007894 UNIXVFS("unix-nfs", nfsIoFinder ),
drh7708e972008-11-29 00:56:52 +00007895 UNIXVFS("unix-proxy", proxyIoFinder ),
drh734c9862008-11-28 15:37:20 +00007896#endif
drh153c62c2007-08-24 03:51:33 +00007897 };
drh6b9d6dd2008-12-03 19:34:47 +00007898 unsigned int i; /* Loop counter */
7899
drh2aa5a002011-04-13 13:42:25 +00007900 /* Double-check that the aSyscall[] array has been constructed
7901 ** correctly. See ticket [bb3a86e890c8e96ab] */
danefe16972017-07-20 19:49:14 +00007902 assert( ArraySize(aSyscall)==29 );
drh2aa5a002011-04-13 13:42:25 +00007903
drh6b9d6dd2008-12-03 19:34:47 +00007904 /* Register all VFSes defined in the aVfs[] array */
danielk1977e339d652008-06-28 11:23:00 +00007905 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
drh734c9862008-11-28 15:37:20 +00007906 sqlite3_vfs_register(&aVfs[i], i==0);
danielk1977e339d652008-06-28 11:23:00 +00007907 }
drh56115892018-02-05 16:39:12 +00007908 unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
danielk1977c0fa4c52008-06-25 17:19:00 +00007909 return SQLITE_OK;
drh153c62c2007-08-24 03:51:33 +00007910}
danielk1977e339d652008-06-28 11:23:00 +00007911
7912/*
drh6b9d6dd2008-12-03 19:34:47 +00007913** Shutdown the operating system interface.
7914**
7915** Some operating systems might need to do some cleanup in this routine,
7916** to release dynamically allocated objects. But not on unix.
7917** This routine is a no-op for unix.
danielk1977e339d652008-06-28 11:23:00 +00007918*/
danielk1977c0fa4c52008-06-25 17:19:00 +00007919int sqlite3_os_end(void){
drh56115892018-02-05 16:39:12 +00007920 unixBigLock = 0;
danielk1977c0fa4c52008-06-25 17:19:00 +00007921 return SQLITE_OK;
7922}
drhdce8bdb2007-08-16 13:01:44 +00007923
danielk197729bafea2008-06-26 10:41:19 +00007924#endif /* SQLITE_OS_UNIX */